2021-05-31

Throttle function won't run without interval constant

class Neuron {
fire() {
  console.log("Firing!");
}
Function.prototype.myThrottle = function(interval) {
// declare a variable outside of the returned function
let tooSoon = false;
return (...args) => {
  // the function only gets invoked if tooSoon is false
  // it sets tooSoon to true, and uses setTimeout to set it back to
  // false after interval ms
  // any invocation within this interval will skip the if 
  // statement and do nothing
  if (!tooSoon) {
    tooSoon = true;
    setTimeout(() => tooSoon = false, interval);
    this(...args); // confused what this piece of code does. 
  }
}


function printFire(){ return neuron.fire()}
const neuron = new Neuron();
neuron.fire = neuron.fire.myThrottle(500);
const interval = setInterval(printFire, 10);

This piece of code will output "Firing!, once every 500ms". My confusion is when I comment "const interval = setInterval(printFire, 10) ", The code does not run at all. I feel const interval should not get called if we already have neuron.fire = ...myThrottle(500). I'm just confused on the sequence of events in this piece of code. Also the line "this(...args)" is calling a function but not sure what exactly.

Very knew javascript is so all responses will be greatly appreciated. thank you!



from Recent Questions - Stack Overflow https://ift.tt/3fUzDbK
https://ift.tt/eA8V8J

Bottom of Pop Up Form is not fully showing the back ground color

I have been struggling to get the CSS to do what I would like to see in the pop up (which displays a form ) that I am using but the bottom of the pop up form is still not showing all the white background.

The CSS is below with the form that sits inside the pop up. What am I doing wrong and how do I correct this annoyance?


    
    <style>
      * {
        box-sizing: border-box;
    
      }
      .openBtn {
        display: flex;
        justify-content: left;
      }
      .openButton {
        border: none;
        border-radius: 5px;
        background-color: #1c87c9;
        color: white;
        padding: 14px 20px;
        cursor: pointer;
        position: fixed;
      }
      .loginPopup {
        position: relative;
        text-align: center;
        width: 100%;
      }
      .formPopup {
        display: none;
         max-height: 340px;
        position: absolute;
        left: 45%;
        top: 5%;
        transform: translate(-50%, 10%);
        border: 3px solid #999999;
        z-index: 9;
        opacity: 1.0;
      }
      .formContainer {
         max-width: 1600px;
         max-height: 350px;
        padding: 20px;
        background-color: white;
        
      }
   
      .formContainer .btn {
        padding: 12px 20px;
        border: none;
        background-color: #8ebf42;
        color: #fff;
        cursor: pointer;
        width: 30%;
  
        opacity: 1.0;
      }
      .formContainer .cancel {
        background-color: #cc0000;
      }
      .formContainer .btn:hover,
      .openButton:hover {
        opacity: 1;
      }
      
      .boxed {
  border: 1px solid green ;
}
    </style>
        
        
        
        

 
   
        
      <div class="formPopup" id="popupColumnDefinitionForm">
        <form class="formContainer">

          <label for="definecolumns">
            <strong>Please define section map by columns:</strong>
          </label>
            <br><br>
           <label for="columns"  style="font-size: 15px;">Column Number:</label>
            <input type="number" id="column" name="column_number" style="width: 3em; height:18px;" >
            <br><br>
            
           <label for="numberofcolumn" style="font-size: 15px;">Number of plots:</label>
            <input type="number" id="plots" name="number_of_plots" style="width: 3em; " >
            
           <label for="order" style="font-size: 15px;">Order by:</label>
            <select id="order" name="columnorder">
              <option value="top_to_bottom" selected>Top to bottom </option>
              <option value="bottom_to_top"  >Bottom to top </option>   
            </select>
           
           <label for="order" style="font-size: 15px;">Number from:</label>
            <select id="columnnumbering" name="columnnumberorder">
              <option value="left_to_right" selected>Left to right </option>
              <option value="right_to_left"  >Right to Left </option>   
            </select>
            
            
           <label for="columnStart" style="font-size: 15px;">Start with Plot:</label>
            <input type="text" id="startplot" name="startwithplot"  style="width: 7em; font-size: 15px; ">
          
          <br>  
          
          <label for="definecolumns">
            <strong>Defined Section Map by Columns:</strong>
          </label>
          <br>
          <textarea name="definedsectioncolumns" disabled id="CurrentTextArea" cols="50" rows="5" style="overflow:auto;resize:none" >""</textarea>
          <br>
          <br>
          <button type="button" class="btn" onclick="AddColumnDefinitionForm()">Add another column</button>

          <button type="button" class="btn" onclick="DoneColumnDefinitionForm(this)">Done</button>  
        
          <button type="button" class="btn cancel" onclick="CloseColumnDefinitionForm()">Cancel</button>
        

        </form>

      </div>



from Recent Questions - Stack Overflow https://ift.tt/3p3URIp
https://ift.tt/eA8V8J

macOS Blue icons

I'm using Storyboard's to develop a macOS Big Sur application, when I noticed that apps such as Xcode and App Store used nice little blue icons:

App Store XCode

I could not find these in Xcode's interface builder anywhere. Does anybody know how to get those icons? (More specifically Xcode's blue plus button, next to "Create a new Xcode project")



from Recent Questions - Stack Overflow https://ift.tt/3fx9jp4
https://ift.tt/2Tv7Uab

Implicit conversion on type alias does not seem to work ont his code

    trait TriIndexable[M[_,_,_,_]] {
  def get[A,B,C,D](m: M[A,B,C,D])(a: A, b: B, c: C): Unit
}
implicit object TriMapTriIndexable extends TriIndexable[TriMap] {
  def get[A,B,C,D](m: TriMap[A,B,C,D])(a: A, b: B, c: C): Unit = {
    println("Tri indexable get")
  }
}
type TriIntMap[D] = TriMap[Int,Int,Int,D]
trait TupleIntIndexable[M[_]] {
  def get[D](m: M[D])(a: (Int, Int, Int)): Unit
}
implicit object TriIntMapTupleIntIndexable extends TupleIntIndexable[TriIntMap] {
    def get[D](m: TriIntMap[D])(a: (Int, Int, Int)): Unit = {
    println("Tri Int indexable get")
  }
}
class TriMap[A,B,C,D]() {
}
implicit class TriIndexableOps[A,B,C,D,M[_,_,_,_]](
      val tri: M[A,B,C,D]
)(implicit ev: TriIndexable[M]) {
    def get(a: A, b: B, c: C) = {
    ev.get(tri)(a,b,c)
}
}
implicit class TupleIntIndexableOps[D,M[_]](
      val tri: M[D]
)(implicit ev: TupleIntIndexable[M]) {
    def get(a: (Int,Int,Int)) = {
    ev.get(tri)(a)
}
}
val test: TriIntMap[String] = new TriMap[Int,Int,Int,String]()
test.get(5,5,5)
test.get((5,5,5))

Why does this error on the last line? I'm trying to give a subset of TriMaps the ability to index with another object, in this case it's a tuple of three ints. How can I fix this?

https://scastie.scala-lang.org/pMEa7Zq6TLeBxq1k9zG1oA



from Recent Questions - Stack Overflow https://ift.tt/3yKljvf
https://ift.tt/eA8V8J

Using same X and Y axis for all par() plots

I have a loop generating 15 plots, one for each of my factor variables. This is my first time using par() to set up the plot space (I usually use ggplot or lattice, which I probably should have done here). Anyway, I'm generally okay with this, but I would like each graph to have the same X and Y range (1,5) and (0,120), respectively. I've read the par documentation but haven't figured out how to accomplish this. Here is my code:

par(mar=c(2,2,2,2),mfrow = c(4, 4))
for (i in 2:16) {
  plot(df[,i], main=colnames(df)[i],
       ylab = "Count", col="steelblue", las = 2)
}

Thank you!



from Recent Questions - Stack Overflow https://ift.tt/2SBiN9T
https://ift.tt/eA8V8J

Unable to open/use file unless i use Directory path. Pycharm

Just started python and GUIs. it seems that everytime i need to use a file like a picture or music wav file i have to use the directory path and i have to separate my directories with 2\ or i get a unicode error.in the screenshot u can see that in my iconbitmap its normal because it reads the directory normally but in but in mixer or tkinter i have to use the D path with double \error Ive tried moving my desired files to other locations like scripts and include but it doesnt open them. it reconizes the filles name because it goes to autofill but when comes times to load or to activate my function no luck



from Recent Questions - Stack Overflow https://ift.tt/2SItV4Z
https://ift.tt/eA8V8J

How to mock the image response in cypress

My problem

I'm trying to simulate a response from the server containing an image with cy.intercept however, the browser won't display my mocked image. The browser just can't interpret my response as a proper image for <img> tag.

debug tools screenshot

I can still copy the response in debug tools and it seems to be the image I need but probably encoded in the wrong way.

My approach

    cy.readFile('src/assets/logo.png', 'binary').then((imgContent) => {
      cy.intercept('/uploads/test.png', {
        headers: { 'Content-Type': 'image/jpg' },
        body: imgContent,
      })
    });

I've also tried to return base64 image string like this:

    cy.intercept(
      '/uploads/test.png',
      {
        headers: {"Content-Type": "image/jpg"},
        body:
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARCUlEQVR4Xu1deXQURRr...

But it didn't work as well.



from Recent Questions - Stack Overflow https://ift.tt/3wOWX1z
https://ift.tt/3c5646p

syntax error: missing ';' before '}' but im sure im not missing any semicolons C++

the title pretty much explains and i've been looking on google for a while and cant find a working answer here is my code:

#include <SDL.h>
#include <stdio.h>

//Screen dimensions: 1280×720
const int SCREEN_WIDTH = 1280;
const int SCREEN_HEIGHT = 720;

int main(int argc, char* args[])
{
    SDL_Window* window = NULL;
    SDL_Surface* screenSurface = NULL;

    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    }
}


from Recent Questions - Stack Overflow https://ift.tt/34wGfaZ
https://ift.tt/eA8V8J

sqldf only returning one row, same query used in SQL

For some reason I'm only returning one row when it comes to R while at SQL Server, I'm returning the correct number of rows. SQLDF:

CustomerCodingChangesT <- sqldf("
        SELECT c.CustID as ID, c.ReverseSupplier as Supplier, c.ReverseCustomerCode as Code, c.Name, c.Address, c.[From PostCode], c.[From Outlet], c.[From OutletName], 
        o.FullAddress AS [From Address], 
        c.[To PostCode], c.[To Outlet], c.[To OutletName], 
        o1.FullAddress AS [To Address], 
        Max(Cast( c.TotalUnits as varchar)) as [Total Units], '$'+Max(cast(c.TotalValue as varchar)) as [Total Value], '' AS Checked, c.CustRecActive as Active
        FROM CustomerCorrectionSummaryT AS c
        LEFT JOIN OutletMasterT AS o ON c.[From PostCode] = o.Postcode AND c.[From Outlet] = o.Outlet 
        LEFT JOIN OutletMasterT AS o1 ON c.[To PostCode] = o1.Postcode AND c.[To Outlet] = o1.Outlet
        ORDER BY c.totalvalue DESC;")

SQL:

if object_id ('tempdb..#CustomerCodingChanges') is not null drop table #CustomerCodingChanges
SELECT c.CustID as ID, c.ReverseSupplier as Supplier, c.ReverseCustomerCode as Code, c.Name, c.Address, c.[From Postcode], c.[From Outlet], c.[From OutletName], 
o.FullAddress AS [From Address], c.[To Postcode], c.[To Outlet], c.[To OutletName], 
o1.FullAddress AS [To Address], cast(c.TotalUnits as varchar(max)) as [Total Units], '$'+cast(c.TotalValue as varchar(max)) as [Total Value], '' AS Checked, c.CustRecActive as Active
        INTO #CustomerCodingChanges
    FROM #CustomerCorrectionSummary AS c
        LEFT JOIN ndf_061.IRGMaster.dbo.OutletMaster AS o ON c.[From Postcode] = o.postcode AND c.[From Outlet] = o.outlet
        LEFT JOIN ndf_061.IRGMaster.dbo.OutletMaster AS o1 ON c.[To Postcode] = o1.postcode AND c.[To Outlet] = o1.outlet
    ORDER BY c.totalvalue DESC;

Both dataframes for CustomerCorrectionSummaryT and OutletMasterT have the same number of results in R and in SQL so i dont know why it won't also show the same number of result in R versus in SQL. In SQL in returning 22 rows while in R i'm only getting one row which both are correct. R's sqldf just doesn't show all of it. Im thinking it has something to do with my left join function but i don't really know. Lemme know if you need more information!



from Recent Questions - Stack Overflow https://ift.tt/34zK13k
https://ift.tt/eA8V8J

How to make Kotlin use field instead of setter in non-primary constructors too

If I use a primary constructor to initialize a property, its setter won't be called:

open class Foo(open var bar: Any)

open class Baz(bar: Any) : Foo(bar) {
    override var bar: Any
        get() = super.bar
        set(_) = throw UnsupportedOperationException()
}
...
Baz(1) // works, no setter is called

This works too:

open class Foo(bar: Any) {
    open var bar: Any = bar // no exception in Baz(1)
}

But this doesn't:

open class Foo {
    open var bar: Any
    constructor(bar: Any) {
        this.bar = bar // UnsupportedOperationException in Baz(1)
    }
}

This can't even be compiled:

open class Foo(bar: Any) {
    open var bar: Any // Property must be initialized or be abstract
    init {
        this.bar = bar
    }
}

I'm asking because I need to make bar lateinit to be able doing this:

Baz(1) // works
Foo(2) // this too
Foo().bar = 3 // should work too

But this doesn't work in Kotlin:

// 'lateinit' modifier is not allowed on primary constructor parameters
open class Foo(open lateinit var bar: Any)

And there's no syntax like this:

open class Foo() {
    open lateinit var bar: Any
    constructor(bar: Any) {
        // instead of this.bar
        fields.bar = bar // or whatever to bypass the setter
    }
}

Any ideas how to solve this? (besides reflection, adding extra properties and delegates)



from Recent Questions - Stack Overflow https://ift.tt/2SLtrLu
https://ift.tt/eA8V8J

I want the searchbox to disappear from all pages except product page with React.js

When i do this ternay operator the result is that the searchbox desappear from every page. The idea is only to show in /products. Thank you if you could help me with this, very much appreciated.


function Header() {
let location = useLocation();


{location === "/products" ? (
                      <li>
                        <form action="#" class="form-box f-right">
                          <input
                            type="text"
                            name="Search"
                            placeholder="Search products"
                          />
                          <div class="search-icon">
                            <i class="ti-search"></i>
                          </div>
                        </form>
                      </li>
                    ) : null}```


from Recent Questions - Stack Overflow https://ift.tt/3wMkdgK
https://ift.tt/eA8V8J

Pandas Window functions to calculate percentage for groupby

For each Location and Acquisition channel I would like to calculate the percentage. For example: The Digital acquisition channel in Milan makes up 33% of all customers in Milan and 24% of total spend across all acquisition channels in Milan

DF

city   acquisition_channel customers  spend
Milan  Digital             23         120
Milan  Organic             35         324
Milan  Email               12         53
Paris  Digital             44         135
Paris  Organic             24         252
Paris  Email               10         47

Desired Output DF

city   acquisition_channel customers  spend
Milan  Digital             33%         24%
Milan  Organic             50%         65%
Milan  Email               17%         11%
Paris  Digital             56%         31%
Paris  Organic             31%         58%
Paris  Email               13%         11%

This is what I have tried so far, but this is not giving me the desired result

df.groupby(["acquisition_channel","city"])\
.agg({"customers": "sum", "spend" : "sum"})[["customers", "spend"]]\
.apply(lambda x: 100*x/x.sum())\
.sort_values(by=["customers","spend"], ascending=[False,False])


from Recent Questions - Stack Overflow https://ift.tt/34tPR6x
https://ift.tt/eA8V8J

How to programmatically upload a file to input[type=file]

My problem is, I had image srcs I converted to dataUrls. I am now trying to convert the dataUrl to a file and programmatically upload the file to an input[type='file'].

I was able to successfully get the dataUrls of the images, however, I am now creating the function that downloads the dataUrl. The dataUrl downloads, however, in addition to downloading the dataUrl, I want it to also be uploaded to that input[type=file] section.

The code seems to work fine, however, the image never actually uploads. I included a picture of the terminal for when the program runs. It says the input section has the file I added('product_image.png'). But for website I am trying to upload the photo, when a png file is uploaded it displays the image in the same section. However, that is not happening.

Am I not properly providing a source for the file? is the code wrong?

If anyone sees the problem, please let me know!

Terminal Page

  function downloadURI(uri, name) {
            var link = document.createElement("a");
            link.download = name;
            link.href = uri;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            delete link;

            const dT = new ClipboardEvent('').clipboardData || 
              new DataTransfer(); 
            dT.items.add(new File([uri], 'product_image.png'));
            document.querySelector('input[class="mkhogb32"]').files = dT.files;
            console.log(dT);
            console.log(document.querySelector('input[class="mkhogb32"]').files);
          }

Here is an example call:

downloadURI("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAFmklEQVRYR+1YWUiVaxRdx1nLOh7NynMpDbOOA4Z5pdvgQNFDb3VJIknqoVIQExyTNBHRCppoEkW0yVKQsMT7IBZGEZoiRaSlpSYOWM6m5HhZW4x75db5f4en24aDcv7z/Xt9a++99v4+zdTU1BTmaa9fv8a1a9fw9OlTTE5OwtvbGwEBAVi6dCl27NiBdevWzdmDZj4A29racPLkSTx48ABDQ0Pw9fXFnj174O/vj9HRUTx8+BAvXrzA3r17ERsbCxsbG9VA5wywtbUV8fHxKCwsxMTEBHbt2oXTp09j+/bt30F8/foVO3fuRGVlJY4cOYKUlBSsWbNGFcg5ARwfH0dCQgLOnz8vzjZt2oTs7GxhcLa9ffsWHh4e8vXhw4eRm5u7+ABLSkoQFhYGhpiWnp4uof6RkdX379/D3t4eOTk52Lp1q2KQc2IwNDQUt2/flpxiEWRmZsLZ2fmHTo8fP466ujp8+fIFBw4cQHJy8uIBZM6Rvd7eXlhaWuLWrVsIDg7+qcNLly4hPz9fcnXDhg3yv1JTzWBISIg40Ol00Gg0wooxe/78uRQQjarGql+2bJmxZfJcFcBPnz7Bx8cH3d3dsphs7t+/36ijd+/e4ejRo7C2tpZNJSUlYdu2bUbXqQZYUFCAY8eOYWBgAHZ2dqJxDJkxa2hoQHh4OExNTTE2NiY5GBgYaGyZegYPHTqEu3fvSpjo4MmTJ4qcEGBUVJSIN7WRerh7925Fa1WF2MvLC2/evJEXnzlzRoRaibGC4+LihHl2nIyMjMUB6OLigubmZixZsgQvX76EwWBQgg81NTUi7Kx8ivzVq1f/1XF+9hJVDFLrWlpapNdWVFQoAscfPX78WNgmwOXLl4uGuru7K1qvCiClpa+vD6dOnUJqaqoiB/wRZSU6OhqDg4My2bATrVixQtF6VQApERTnvLw86QhKjbp54sQJjIyMyChWXl4OKysrRcsVA7x48SJu3LghIaZksDsotaSkZFy+fFkY5GTj5/e70qXKhZoD6YULF/Dx40eZWmJiYsCqNpZLk5MAuw9FndrJoUGn0y48QDogC+wmXV1dMDc3l4k5Pj4BBw+GYOXK/86p4uJHspnGxkZs3rwZ1dVVisGp6iRpaWm4f/++dANWIwfWadMISIo4da6srAzV1dUiyNwAWbtz544MChwqCgruLTxA5g3Zo/bR+vv78fnz5+8AV61aLeMWi4AzIiudWunk5CRdh+wRaGJiIqKiIhce4Llz5+R8wSqmQ7LX2dkpYV6/3g39/QPo6emRyiQoMse2RtaampoEkJubmwyrBoPx3v3PHSiq4sjISBQXF8uASmbYrvjhhGxubgGeCwmIz8gkpYjFROY4HHBjLKaKCmW9WzXAs2fPCoOUCTMzM3z79k3CTIBk0MrKWkJOVrVaLfR6vQDu6OjAhw8fZJ2rqytevapVFV7FRcJmf+XKFZSWloqDGZAM5ZYtf2BwcOj7IEAhnjleEiDX8rN27Vr5a2KiDqOiEDOXsrKyRJwp1Gx5HD6Zj3r9b9Dp7KWF8dBuYmIiAy0ZJSB+x5zloFtTM11kakwRQL6QRcDTG4EyZDSCMRjcodXawdPTU6qYIaXEsGAoR5ymbW1tERERgfT0NDXYpkVMzc0Cc+z69evS/Nvb22V0IoOjo2NwcHAQUBzHmJ8sIj5nwfCQxQHDwUG3uABn3l5fXy/jflVVFfbt+xOlpX/h5s2bwtiMkV3mKK88eKug169WDU41g7M9PHv2TAbP1tbpOxqG1sLCAhs3bpTLIx6MLC3N5wRsZpGqEM/2NDw8jLq6ejg7u6C2thZBQUEwNdVgfHwSZmYqy/UH25gXQL7z0aMS+Pn5gXcwQUHKTmpqKJ03wKKiIjg6OsqtFbVuoe0XwPky+ovBXwwaY+B/X8V/A+fXNLaIW65OAAAAAElFTkSuQmCC", 'image1.png');



from Recent Questions - Stack Overflow https://ift.tt/3c2hLe4
https://ift.tt/eA8V8J

How do I drop system versioned tables in a sql server database project

We’re using a .net sql server database project to define our database, and it’s not deleting tables from the server even though we have deleted them in the database project. There is an option in the publish profile to drop objects that are in the target but not in the source. However, this doesn’t work for temporal tables as I get an error saying it can’t drop temporal tables as the standard sql drop command is not supported on the temporal table.

Is there a way to drop temporal tables using a SQL server data base project?



from Recent Questions - Stack Overflow https://ift.tt/3yPY9U3
https://ift.tt/eA8V8J

Scene 1, Layer 'Actions', Frame 1, 1084: Syntax error: expecting rightparen before colon

I'm new to ActionScript and I'm confused about these two errors. I already have some prior coding experience from other languages.

Scene 1, Layer 'Actions', Frame 1, Line 78, Column 20 1084: Syntax error: expecting rightparen before colon.

Scene 1, Layer 'Actions', Frame 1, Line 85, Column 20 1084: Syntax error: expecting rightparen before colon.

This is my code.

{
    timeStep += 1; //increment counter
    if (run)
    { //only if run = true is shift key has been pressed
        moveCharacter(evt:KeyboardEvent)
        {
            timeStep = 0; //reset the counter
        }
    }
    else if (timeStep == 2)
    {
        moveCharacter(evt:KeyboardEvent)
        {
            timeStep = 0; //reset the counter
        }
    }
}

I'm not sure where the problem is, I can't see one. Unless I'm blind.



from Recent Questions - Stack Overflow https://ift.tt/34uay24
https://ift.tt/eA8V8J

Python sort_values (inplace=True) but not really?

So I am trying to write a loop in python as I have to compare rows to each other in a table. I have to sort the data, which I do by 'sort_values', the dataframe seems to sort, yet when I step through it with a 'for loop' it is still unsorted? So I'm clearly not understanding how pandas memory allocation works. I have tried sorting to another dataframe and I get the same problem

import pandas as pd

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
        'date1': ['2000-04-18', '2000-04-16', '2000-04-15', '2000-04-25', '2000-04-16', '2000-04-17'],
        'stat1': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}

frame = pd.DataFrame(data) 
 
frame
output original unsorted:
 state  date1   stat1
0   Ohio    2000-04-18  1.5
1   Ohio    2000-04-16  1.7
2   Ohio    2000-04-15  3.6
3   Nevada  2000-04-25  2.4
4   Nevada  2000-04-16  2.9
5   Nevada  2000-04-17  3.2 
frame.sort_values(by=['state','date1'], inplace=True)

frame
sorted output:
    state   date1   stat1
4   Nevada  2000-04-16  2.9
5   Nevada  2000-04-17  3.2
3   Nevada  2000-04-25  2.4
2   Ohio    2000-04-15  3.6
1   Ohio    2000-04-16  1.7
0   Ohio    2000-04-18  1.5
for i1 in range(0, len(frame)):
    state1=frame['state'][i1]
    print(frame['state'][i1],' ', frame['date1'][i1])
output unsorted:
Ohio   2000-04-18
Ohio   2000-04-16
Ohio   2000-04-15
Nevada   2000-04-25
Nevada   2000-04-16
Nevada   2000-04-17


from Recent Questions - Stack Overflow https://ift.tt/3uJRiIN
https://ift.tt/eA8V8J

Do I have to deallocate gcnew System::EventHandler?

So I'm making my first windows application in windows forms and I have noticed that when I press a button multiple times in a row RAM usage rises. I thought I had memory leaks and I found this:

this->button_to_decompress->Click += gcnew System::EventHandler(this, &MyForm::button_to_decompress_Click);

Do I have to manually deallocate this? And if so how do I do that?

My whole code:

#pragma once
#include <msclr/marshal_cppstd.h>
#include "tree.h"

using namespace msclr::interop;

namespace CompressionTool {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace System::IO;

    /// <summary>
    /// 
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
        }

    protected:
        /// <summary>
        /// 
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::ProgressBar^ progressBar1;
    protected:
    private: System::Windows::Forms::Button^ button_to_compress;
    private: System::Windows::Forms::Button^ button_to_decompress;
    private: System::Windows::Forms::OpenFileDialog^ openFileDialog1;
    private: System::Windows::Forms::OpenFileDialog^ openFileDialog2;
    private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1;
    private: System::Windows::Forms::SaveFileDialog^ saveFileDialog2;


    private:
        /// <summary>
        /// 
        /// </summary>
        System::ComponentModel::Container^ components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// 
        /// 
        /// </summary>
        void InitializeComponent(void)
        {
            this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar());
            this->button_to_compress = (gcnew System::Windows::Forms::Button());
            this->button_to_decompress = (gcnew System::Windows::Forms::Button());
            this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
            this->openFileDialog2 = (gcnew System::Windows::Forms::OpenFileDialog());
            this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog());
            this->saveFileDialog2 = (gcnew System::Windows::Forms::SaveFileDialog());
            this->SuspendLayout();
            // 
            // progressBar1
            // 
            this->progressBar1->Location = System::Drawing::Point(12, 144);
            this->progressBar1->Margin = System::Windows::Forms::Padding(3, 2, 3, 2);
            this->progressBar1->MarqueeAnimationSpeed = 20;
            this->progressBar1->Name = L"progressBar1";
            this->progressBar1->Size = System::Drawing::Size(557, 60);
            this->progressBar1->Style = System::Windows::Forms::ProgressBarStyle::Marquee;
            this->progressBar1->TabIndex = 0;
            this->progressBar1->Value = 100;
            // 
            // button_to_compress
            // 
            this->button_to_compress->Location = System::Drawing::Point(12, 12);
            this->button_to_compress->Margin = System::Windows::Forms::Padding(3, 2, 3, 2);
            this->button_to_compress->Name = L"button_to_compress";
            this->button_to_compress->Size = System::Drawing::Size(131, 60);
            this->button_to_compress->TabIndex = 1;
            this->button_to_compress->Text = L"Compress file";
            this->button_to_compress->UseVisualStyleBackColor = true;
            this->button_to_compress->Click += gcnew System::EventHandler(this, &MyForm::button_to_compress_Click);
            // 
            // button_to_decompress
            // 
            this->button_to_decompress->Location = System::Drawing::Point(12, 78);
            this->button_to_decompress->Margin = System::Windows::Forms::Padding(3, 2, 3, 2);
            this->button_to_decompress->Name = L"button_to_decompress";
            this->button_to_decompress->Size = System::Drawing::Size(131, 60);
            this->button_to_decompress->TabIndex = 2;
            this->button_to_decompress->Text = L"Decompress file";
            this->button_to_decompress->UseVisualStyleBackColor = true;
            this->button_to_decompress->Click += gcnew System::EventHandler(this, &MyForm::button_to_decompress_Click);
            // 
            // openFileDialog1
            // 
            this->openFileDialog1->FileName = L"openFileDialog1";
            // 
            // openFileDialog2
            // 
            this->openFileDialog2->FileName = L"openFileDialog2";
            // 
            // MyForm
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(581, 217);
            this->Controls->Add(this->button_to_decompress);
            this->Controls->Add(this->button_to_compress);
            this->Controls->Add(this->progressBar1);
            this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedToolWindow;
            this->Margin = System::Windows::Forms::Padding(3, 2, 3, 2);
            this->MaximizeBox = false;
            this->Name = L"MyForm";
            this->Text = L"CompressionTool";
            this->ResumeLayout(false);
        }
#pragma endregion
    private: System::Void button_to_compress_Click(System::Object^ sender, System::EventArgs^ e)
    {
        OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

        openFileDialog1->InitialDirectory = "c:\\";
        openFileDialog1->Filter = "txt files (*.txt)|*.txt";
        openFileDialog1->FilterIndex = 1;
        openFileDialog1->RestoreDirectory = true;

        if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            Node node;
            Tree tree;
            const char* directory;
            marshal_context^ context = gcnew marshal_context();
            directory = context->marshal_as<const char*>(openFileDialog1->FileName);
            tree.root = node.first_read_of_the_file(directory);
            node.sort_list(tree.root);
            node.make_tree(tree.root);
            tree.create_compressed_file(directory);
            tree.delete_tree(tree.root);

            SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;

            saveFileDialog1->InitialDirectory = "c:\\";
            saveFileDialog1->Filter = "huf files (*.huf)|*.huf";
            saveFileDialog1->FilterIndex = 1;
            saveFileDialog1->RestoreDirectory = true;

            if (saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
            {
                directory = context->marshal_as<const char*>(saveFileDialog1->FileName);
                int result = rename("compressed.huf", directory);
            }
            else
                remove("compressed.huf");

            delete context;
            delete saveFileDialog1;
        }

        delete openFileDialog1;
    }
    
    private: System::Void button_to_decompress_Click(System::Object^ sender, System::EventArgs^ e)
    {
        OpenFileDialog^ openFileDialog2 = gcnew OpenFileDialog;

        openFileDialog2->InitialDirectory = "c:\\";
        openFileDialog2->Filter = "huf files (*.huf)|*.huf";
        openFileDialog2->FilterIndex = 1;
        openFileDialog2->RestoreDirectory = true;

        if (openFileDialog2->ShowDialog() == System::Windows::Forms::DialogResult::OK)
        {
            Tree tree;
            const char* directory;
            marshal_context^ context = gcnew marshal_context();
            directory = context->marshal_as<const char*>(openFileDialog2->FileName);
            tree.decompress_file(directory);
            tree.delete_tree(tree.root);

            SaveFileDialog^ saveFileDialog2 = gcnew SaveFileDialog;

            saveFileDialog2->InitialDirectory = "c:\\";
            saveFileDialog2->Filter = "txt files (*.txt)|*.txt";
            saveFileDialog2->FilterIndex = 1;
            saveFileDialog2->RestoreDirectory = true;

            if (saveFileDialog2->ShowDialog() == System::Windows::Forms::DialogResult::OK)
            {
                directory = context->marshal_as<const char*>(saveFileDialog2->FileName);
                int result = rename("decompressed.txt", directory);
            }
            else
                remove("decompressed.txt");

            delete context;
            delete saveFileDialog2;
        }

        delete openFileDialog2;
    }
};
}

If you have any suggestions on how to improve my code I would be very grateful!



from Recent Questions - Stack Overflow https://ift.tt/3iaxdZv
https://ift.tt/eA8V8J

How to refer with a Foreign Key to a Primary key that has a specific value in some columns?

Let's say I have a site user table and they have an account type (client, master, and so on).

Create table user_info(
userId int not null,
userPassword varchar(60),
userEmail varchar(30),
userLogin varchar(25),
userType enum ('client','master','administrator'),
Constraint Pk_userId Primary Key(userId));

And there is a table that describes the masters, in which the identifier refers only to those identifiers in the users table that are of the master type.

Create table masters(
masterId int not null,
serviceId int,
Constraint Fk_masterId Foreign Key(masterId)references user_info(userId));

How can I do this and is it possible?



from Recent Questions - Stack Overflow https://ift.tt/3hZudyW
https://ift.tt/eA8V8J

Access the second item in Collection [Map]

I'm making a discord bot, and fetching some messages. I got this object

//This parameters changue every time i fetch
Collection(3) [Map] {
  '848689862764789770' => Message {...
  }
  '848689552410804234' => Message {...
  }
  '848689534485004319' => Message {...
  }

I can access the first and third entry using .first() and .last().

I've been trying to use Object.keys() but it returns undefined.

const mensajes = await message.channel.messages.fetch({ limit: 3 });
                
console.log(mensajes[Object.keys(mensajes)[1]])


from Recent Questions - Stack Overflow https://ift.tt/34xbGCg
https://ift.tt/eA8V8J

Parse Android Room Generated Schema to Actual SQLite Script

I want to create a .db file to pre populate my Android Room database but the database/schema is huge so I am trying to find a way not to do it manually. Basically I want to do the following:

  1. Generate the database schema for Room (done!)
  2. Generate the SQLite commands from the schema without needing to be reading the schema and copying and pasting all the scripts found in it
  3. Create the database on some SQL client
  4. Populate the database with the default data and generate a .db file from it to add into my app to be used by Room.

I need help on step 2. Thanks a lot!



from Recent Questions - Stack Overflow https://ift.tt/3wOWQmF
https://ift.tt/eA8V8J

Late Binding: Expecting error but not getting it

I wrote the below code to understand Late Binding with Option Strict ON. With OPTION STRICT ON, I was expecting an error in the statement: o = New Car(). But not getting any error. Isn't that strange? Its clearly mentioned in the MSDN documentation on Option Strict that when ON it prevents late binding - gives a compile time error. So what is happening here....can someone pls help?

Option Strict On
Module Module1
    Sub Main()
        Dim o As Object
        o = New Car() 'Expecting error here but not getting
        Console.ReadLine()
    End Sub
End Module

Class Car
    Public Property Make As String
    Public Property price As Integer
End Class


from Recent Questions - Stack Overflow https://ift.tt/2SBiSud
https://ift.tt/eA8V8J

Axios - Prevent sending JWT token on external api calls

I'm building a fullstack app with nuxt + express and I have finally managed to include an authentication between my frontend/backend with passport and jwt.

I want to make additional api requests to my own github repo for fetching the latest releases (so a user gets a information that an update exists). This requets failed with a "Bad credentials" messages. I think this happens because my jwt token is sent with it (I can see my token in the request header).

My question is, is it possible to prevent axios from sending my JWT token in only this call? First, to make my request work and second, I don't want the token to be sent in external requests.

Example:

const url = 'https://api.github.com/repos/xxx/releases/latest'
this.$axios.get(url)
    .then((res) => {
        this.latestRelease = res.data
    }).catch((error) => {
        console.error(error)
    })


from Recent Questions - Stack Overflow https://ift.tt/3uAJ5qa
https://ift.tt/eA8V8J

Are amazon workspaces connected to the same network?

Any one knows if two stations created with the same amazon aws workspaces account share the same network ? Are they linked in any way ? Should I use vpn on each one if I want that they stay independent ?

Thanks



from Recent Questions - Stack Overflow https://ift.tt/3vDRrOZ
https://ift.tt/eA8V8J

2021-05-30

Handle "Slice Struct" properly? (golang)

I have created a Slice Struct. But why can't I append or output values?

package main

import "fmt"

type Slicestruct []struct {
    num      []int
    emptynum []int
}

func main() {
    slicestruct := &Slicestruct{
        {[]int{1, 2, 3}, []int{}},
        {[]int{4, 5, 6}, []int{}},
    }

    // is working:
    fmt.Println(slicestruct)

    // isn't working:
    fmt.Println(slicestruct[0].num[0])

    // isn't working:
    slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99)
}

The error message is: "invalid operation: slicestruct[0] (type *Slicestruct does not support indexing)"



from Recent Questions - Stack Overflow https://ift.tt/3yYjR8C
https://ift.tt/eA8V8J

multiple images to one byte array? Array of byte arrays?

I have many images in a folder , I want to make one byte array for all of the images (array of byte arrays),but I only managed to make an array for one image .

    File file = new File("D:\\swim\\swim99.png");
    //init array with file length
    byte[] bytesArray = new byte[(int) file.length()]; 

    FileInputStream fis = new FileInputStream(file);
    fis.read(bytesArray); //read file into bytes[]
    fis.close();
    System.out.print(Arrays.toString(bytesArray));

So can I access multiple of images in a folder at once and get each one's byte array then put them into a 2D array of arrays array where the [Number of image[byte array image one]]?



from Recent Questions - Stack Overflow https://ift.tt/3fvUz9V
https://ift.tt/eA8V8J

How to intercept network calls in android and ios apps?

I have a chrome extension that works on a specific website by intercepting its network calls (xhr calls) performing some background processing and autofills the form for them and saves its users time.

Doing it on a chrome extension is pretty easy as we have XMLHttpRequest https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

The website that my extension works has also launched a mobile app, and a lot of customers have migrated to the app instead of the desktop site.

I am interested in building an android/ios app that could do the same things.

  • Intercept the network calls made by the app.
  • And overlay the information on the that app.

I have tried to look into android/ios development docs for approaching this but couldn't get anything concrete. I believe my usecase is similar to what a VPN app does and I also know that drawing over other apps is also possible in mobile.

Just want to get some of input from mobile developers how can I go about building this, my primary background is in web and I am still quite new to mobile frameworks So, any pointers/documentations/suggestions would be appreciated.



from Recent Questions - Stack Overflow https://ift.tt/2TufxO4
https://ift.tt/eA8V8J

Yii2 adding an extra field to the form to add to database

On an existing project where there is a table with 3 fields (ID, name, label)

  `id` int(11) NOT NULL,
  `name` varchar(32) DEFAULT NULL,
  `label` varchar(1) DEFAULT 'A'

Currently on the page where to add new record to the above table there is the form with only one field for the 'name', and works fine, and I need to add another field for the 'label' field; so I go to the related model (models/Products.php) and I have:

    public function attributeLabels()
class Products extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'products';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], 'string', 'max' => 32],
            [['name'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Name'),
        ];
    }

I add the following to the above file, but no new input field is added to the form on the page

public function attributeLabels()
{
    return [
        'id' => Yii::t('app', 'ID'),
        'name' => Yii::t('app', 'Name'),
        'label' => Yii::t('app', 'Prefix'),
    ];
}

I also tried adding to the rules like this, but no joy

public function rules()
{
    return [
        [['name', 'label'], 'string', 'max' => 32],
        [['name', 'label'], 'unique'],
    ];
}

Appreciate if you can point me to what I am missing.



from Recent Questions - Stack Overflow https://ift.tt/3p6aLlI
https://ift.tt/eA8V8J

js canvas ctx clip not working with forEach

In the beginning, there is for loop to generate colors and push them to an array. after that I want to print 50 circles with colors but when I use the ctx clip it did not print only one of them when I don't use ctx clip its print 50 of them

var arr= []
  for (var i = 1; i < 50; i++) {
   var color =  "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join("");
  arr.push({
color:color,
name:i
})  
  }
var canvas = document.getElementById("canvas");
          var ctx = canvas.getContext("2d");
canvas.width  = 35 * 10;
canvas.height = (arr.length /10) *35;
            var x = 0,y = 10;
            arr.filter(role => !isNaN(role.name)).sort((b1, b2) => b1.name - b2.name).forEach(role => {
                x += 30;
                if (x > 40 * 8) {
                    x = 30;
                    y += 30;
                }
              ctx.arc(x+12.5, y+12.5, 12, 0, Math.PI* 2 , false);
              ctx.stroke();
              ctx.clip();
            })

          var x = 0, y = 10;
            arr.filter(role => !isNaN(role.name)).sort((b1, b2) => b1.name - b2.name).forEach(role => {
                x += 30;
                if (x > 40 * 8) {
                    x = 30;
                    y += 30;
                }
                   ctx.font = "bold 19px Fjalla One, sans-serif";
                   ctx.fillStyle = role.color;
                   ctx.fillRect(x,y, 25, 25)
                   ctx.fillStyle = 'white';
                if (`${role.name}`.length > 2) {
                   ctx.font = "bold 14px Fjalla One, sans-serif";
                   ctx.fillText(role.name, x + 0, y + 18);
                } else if (`${role.name}`.length > 1) {
                   ctx.fillText(role.name, x + 2, y + 20);
                } else {
                   ctx.fillText(role.name, x + 7, y + 20);
                }
            });
<canvas id="canvas"></canvas>


from Recent Questions - Stack Overflow https://ift.tt/3furAU6
https://ift.tt/eA8V8J

how to get data using google sheets?

Sorry I'm a beginner
I tried to get data from a web with google sheets

Title and Pricing were successful
but for Image Url, Description and highlights didn't work ( Imported content is blank. )

any idea ?
this is the url

https://www.lazada.co.id/products/gp-mall-penggaruk-punggung-alat-garuk-dan-pijat-punggung-garukan-energy-i1612070759-s3106188545.html?mp=1



from Recent Questions - Stack Overflow https://ift.tt/2TtC1yL
https://ift.tt/eA8V8J

How do I access the onTextLayout event within a React Native Text component?

I have a React Native Text component that contains a user profile's information and has a max NumberOfLines at 2. I also have a TouchableOppacity button that says "Read More.." on it that clears the max NumberOfLines of the component. I don't want the "Read More" button to show if there the NumberOfLine is already 2 or less.

In the documentation it says that the onTextLayout event would return an array with a TextLayout objects for each line but when I try to access it I never have anything returned. I've tried to access the onLayout event and I can get info from that event but it doesn't have the info that I need. Has anyone had this problem?

<Text numberOfLines={2} onTextLayout={onInfoLayout}>
            test text test text test text test text
            test text test text test text test text
</Text> }


const onInfoLayout = React.useCallback((e:any) =>{
   console.log("this is how long the text is", e);
}, []);

The code above displays nothing in the console but if I were to change onTextLayout to just onLayout it would log the object.. but again that event doesn't have the info I need.

Any help is super appreciated!



from Recent Questions - Stack Overflow https://ift.tt/3wMYQfd
https://ift.tt/eA8V8J

C++ static creator function that returns a null pointer if the parameter is invalid [closed]

I'm writing a class that doesn't provide a public constructor. Instead the user must create object through a creator function that takes some arguments. The creator function returns a pointer to the object if the passed arguments are valid and 'new' works, and a null pointer if the passed arguments are invalid or 'new' doesn't work.

I know I can use a static creator function, but this way I wouldn't be able to initialize the fields from the passed arguments.

What are some possible ways?



from Recent Questions - Stack Overflow https://ift.tt/3hXUnlE
https://ift.tt/eA8V8J

How to work with continious overdispered data

I have troubles with analysis of my data. I analyze cross-sectional data about users activities and spendings from mobile game . I have paying and non-paying users, I need to explain what independent varibles (such as time spend in the game, session lenght, clan (binary), number of messages in chat and etc.) can explain higher spendings in group of paying users. The data was pre-transformed, so instead of spendings in $ I can analyze only variables from 0 to 1 (1 is max spendings for sample, other variables vere divided by max value). I filtered dataset and got 12k observations with paying users. But, the data is overdispersed, and generally looks like negative exponential. I`ve tried to apply log transformation for my dependent variable (spendings) and for indepenent(time spend, session lenght and chat messages because they were skewd) and run linear regression, but R2 was only 0.09, which is quite low. Also, I tried to rond my data and multiply in order to use negative binomial regression. Could I do it because initially data was count? What else could I try?

Thank you in advance!

P.S I also tried to devide users by fix % of overall spendings (10% and got groups with 6000 user, 1000 user, 500 user and so on), and it seemed resonable because each group had higher time spend in the game, session lenght, number of messages and etc.



from Recent Questions - Stack Overflow https://ift.tt/3p19ZpQ
https://ift.tt/eA8V8J

How could I fs.unlink() a file that caused the error?

So, I'm working with files that all send POST requests to different URLs. However, if a POST request receives a 404 response it will error the entire network instead of just that file. Is there a way I would be able to fs.unlink() the file that caused the error?

If not, is there another solution to this? As I don't want the entire server network to go offline just because of a 404 error on just one of the POST requests.

onShoutEvent.on('data', async shout => {
    let embed = embedMaker(`New Shout!`, `\n"${shout.body}"`);
    embed.setAuthor(`${shout.poster.username}`);
    embed.setThumbnail(`http://www.roblox.com/Thumbs/Avatar.ashx?x=150&y=150&Format=Png&username=${shout.poster.username}`);
    embed.setURL(`https://www.roblox.com/groups/${group}`)
    embed.setFooter(`${customFooter}`)
    WebHookClient.send(embed);
    saveData(shout.body);
});

It will check for new "shouts" and will send a request to that Webhook by POST, however if the Webhook is deleted it'll throw a 404 error thus erroring all other code that is being run in the directory.



from Recent Questions - Stack Overflow https://ift.tt/2SIRuKE
https://ift.tt/eA8V8J

Python built-in assert

What is the main difference between assertEqual() and assertLogs()? I am using assertLogs() in a unittest and it works fine as I am using strings, but when I use assertEqual(), it fails the unittest. Unsure why. Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3c5NfzN
https://ift.tt/eA8V8J

Calculation from a column from a dataframe to another dataframe based on matching index

I have 2 sets of stock data, I want to do a simple calculation to find the ratio between the close price of them. Here is my current code. The problem with this code is that the holidays are different and there for they don't always match so the dataset become desynchronized. How do I do this calculation using their index instead?

australia['SP500_ratio'] = australia["Close"]/SP500["Close"]

Example of data:

SPY:

Date    Open    High    Low Close   Adj Close   Volume
4/22/2021   4170.459961 4179.569824 4123.689941 4134.97998  4134.97998  4235040000
4/26/2021   4185.029785 4194.189941 4182.359863 4187.620117 4187.620117 3738920000
4/27/2021   4188.25 4193.350098 4176.220215 4186.720215 4186.720215 3703240000
4/28/2021   4185.140137 4201.529785 4181.779785 4183.180176 4183.180176 3772390000
4/29/2021   4206.140137 4218.779785 4176.810059 4211.470215 4211.470215 4288940000
4/30/2021   4198.100098 4198.100098 4174.850098 4181.169922 4181.169922 4273680000
5/3/2021    4191.97998  4209.390137 4188.029785 4192.660156 4192.660156 4061170000
5/4/2021    4179.040039 4179.040039 4128.589844 4164.660156 4164.660156 4441080000
5/5/2021    4177.060059 4187.720215 4160.939941 4167.589844 4167.589844 4029050000
5/6/2021    4169.140137 4202.700195 4147.330078 4201.620117 4201.620117 4504860000
5/7/2021    4210.339844 4238.040039 4201.640137 4232.600098 4232.600098 4013060000
5/11/2021   4150.339844 4162.040039 4111.529785 4152.100098 4152.100098 3593110000
5/12/2021   4130.549805 4134.72998  4056.879883 4063.040039 4063.040039 3735080000
5/13/2021   4074.98999  4131.580078 4074.98999  4112.5  4112.5  3687780000
5/14/2021   4129.580078 4183.129883 4129.580078 4173.850098 4173.850098 3251920000

Australia:

Date    Open    High    Low Close   Adj Close   Volume
4/22/2021   7258.899902 7312    7253.200195 7312    7312    990647800
4/23/2021   7312    7320.700195 7293.100098 7320.700195 7320.700195 814150000
4/27/2021   7307.799805 7316.5  7270.100098 7295.5  7295.5  908293800
4/28/2021   7295.600098 7334.5  7291.600098 7320    7320    962912000
4/29/2021   7320    7358.200195 7320    7346    7346    965968300
4/30/2021   7346    7346    7278.100098 7290.700195 7290.700195 966526800
5/3/2021    7290.700195 7329.600098 7280.200195 7286.799805 7286.799805 761029700
5/4/2021    7286.799805 7323.5  7286.799805 7323.5  7323.5  836158500
5/5/2021    7323.5  7371    7303.899902 7344.200195 7344.200195 853994500
5/6/2021    7344.200195 7359.799805 7287    7306    7306    1010012900
5/7/2021    7306    7345.200195 7299.700195 7325.200195 7325.200195 855567600
5/10/2021   7325.200195 7419.799805 7321    7419.799805 7419.799805 954823100
5/11/2021   7419.799805 7419.799805 7311.899902 7331.600098 7331.600098 887298800
5/13/2021   7281.100098 7281.100098 7193.200195 7209    7209    937712500
5/14/2021   7209    7281.399902 7209    7239.399902 7239.399902 825354000

I deleted a random row from both sample dataset to illustrate the desync nature of the data. Note that the row count is the same.



from Recent Questions - Stack Overflow https://ift.tt/3fynKcI
https://ift.tt/eA8V8J

Is there a reason for why I am getting the output as 0, 0, 0, 0?

I have the following code, which is suppose to print out roach values after the respective functions have been executed (roach.breed & roach.spray). However, I am getting values of zero.

code for constructor:

public class Roach {
    private int roach;
    /**@param roaches variables for number of roaches

     */
    public void RoachPopulation(int roaches) {
        roach = roaches;

    }

    /** The population of roach doubles

     */
    public void breed() {
        roach = roach * 2;
    }
    /** The population of the roach decreases by a percentage


     */
    public void spray(double percent) {
        roach = roach -(int)(roach * (percent/100));
    }
    /**@return Gets the population of the roach


     */
    public int getRoaches() {

        return roach;
    }

}

The constructor:

public class HelloWorld {
    public static void main(String[] args) {
        Roach roach = new Roach();
        roach.breed();
        roach.spray(10);;
        System.out.println(roach.getRoaches());
        roach.breed();
        roach.spray(10);;
        System.out.println(roach.getRoaches());
        roach.breed();
        roach.spray(10);;
        System.out.println(roach.getRoaches());
        roach.breed();
        roach.spray(10);;
        System.out.println(roach.getRoaches());


    }
}

Output:

0
0
0
0


from Recent Questions - Stack Overflow https://ift.tt/3fynIS8
https://ift.tt/eA8V8J

How to map observable object with inner observables?

How to map observable object with inner observables?

Following is how I fetch details of an item. I want to map the received object with a property unwrapped.

              this.fetchData.getItemData().pipe(
                mergeMap((item: any) => {
                    return {
                        ...item,
                        images: item.images.map(id => this.http.get(baseUrl + link)) -->> I want to unwrap here. (it is an observable; that's why!)
                    }
                })
              )

Here I'm mapping the inner property images which is an array to an array of observables!!!

This is what I've tried:


              this.fetchData.getItemData().pipe(
                forkJoin((item: any) => {
                    return {
                        ...item,
                        images: item.images.map(id => this.http.get(baseUrl + link)) 
                    }
                })
              )


              this.fetchData.getItemData().pipe(
                mergeMap((item: any) => {
                    return {
                      ...item,
                      images: item.images.map((id) =>
                        flatMap(() => this.http.get(baseUrl + link))
                      ),
                    };
                })
              )



from Recent Questions - Stack Overflow https://ift.tt/2R5nEjl
https://ift.tt/eA8V8J

RIP register doesn't change

Why stack and instruction pointer register dont change when i keep printing them using c and inline assembly , because logically others programs are running at the same time so they should keep changing while im printing



from Recent Questions - Stack Overflow https://ift.tt/3wGYw1f
https://ift.tt/eA8V8J

Accessing a JS variable from a different

I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.

        <script>
    $(function() {
      var term = new Terminal('#input-line .cmdline', '#container output');
      term.init();
      });
    </script>
  

   <script>
   term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
   </script>

Thanks in advance



from Recent Questions - Stack Overflow https://ift.tt/3yRp8Pk
https://ift.tt/eA8V8J

How to get the updated entry string from a toplevel window before the tkinter main loop ends?

I have a toplevel window that pops up and asks you for your name. When you enter your name and click ok it should put the name in the entry1_value and close itself. Then I print the variable while keeping the empty (in this snippet of code) main window running. The problem is that it prints the 'Empty String' on the first print and then only the input on the second one.

Here I'm just printing the information so I see if it registers it but I will use it somewhere later.

Also, in reality I just need the updated information placed outside in any way without the main window closing.

Here is the code:

import tkinter as tk
from tkinter import ttk

BUTTON_FONT = ('Lato', 16)

class NameInputBox:
    entry1_value = 'Empty String'
    def __init__(self, text):
        
        self.window = tk.Toplevel()
        self.window.wm_title("Input Name.")

        self.label_message = tk.Label(self.window, text = text, font = (BUTTON_FONT, 20))

        self.frame1 = ttk.Frame(self.window)
        self.entry1 = ttk.Entry(self.frame1, font = BUTTON_FONT, width = 10)
        self.button_message = ttk.Button(self.frame1, text="Ok", command = lambda: self.name_input_box_exit(self.window))
        
        self.entry1.pack(side = 'left', padx = 5, pady = 5)
        self.button_message.pack(side = 'left', pady = 5, padx = 5)

        self.label_message.pack(side = 'top', pady = 10, padx = 10)
        self.frame1.pack(side = 'bottom', pady = 10, padx = 10)


    def name_input_box_exit(self, window):
        self.entry1_value = self.entry1.get()
        self.entry1.delete(0,tk.END)

        self.window.destroy()    

box1 = NameInputBox('Input the Name:')

print(box1.entry1_value)
tk.mainloop()
print(box1.entry1_value)

Thank you for your help!



from Recent Questions - Stack Overflow https://ift.tt/2RNUrda
https://ift.tt/eA8V8J

JS use video frame as canvas background

I'm attempting to use a the first frame of a video as the background of a canvas, as you probably guessed from the title of the question. I can set a background, I can get a frame from a video, but I can't make the frame be the background. It looks like I need a url for the frame to set as the background in the CSS style. For that, I need a blob on which I can call createObjURL() (although I'm discovering now that that method may be deprecated/ing).

Here's some code:

    <!DOCTYPE html>
<html lang="en">
<canvas id="back" style="background-image: url('path/to/.png')";></canvas>
<input type="file" accept="video/*" />


<script>

  document.querySelector('input').addEventListener('change', extractFrame, false);

  var canvas = document.getElementById('back');
  var context = canvas.getContext('2d');
  var imageObj = new Image();
  var image;
  imageObj.onload = function() {
          var height = imageObj.height;
          var width = imageObj.width;
          canvas.height = height;
          canvas.width = width;
          context.drawImage(imageObj, 0, 0, back.width, back.height);
  };
  imageObj.src = "path/to/.png";



  var draw_canvas = document.getElementById('back');
  var draw_context = draw_canvas.getContext('2d');
  var corners = [];
  draw_canvas.addEventListener('mousedown',startDrawing,false);

  function startDrawing(e){
    corners.length=0;
    corners.push([e.layerX, e.layerY]);
    corners.push([e.layerX+1, e.layerY+1]);
    draw_canvas.addEventListener('mousemove', updateCorners,false);
    draw_canvas.addEventListener('mouseup',function(){
        draw_canvas.removeEventListener('mousemove', updateCorners,false);
    },false);
  }

  function updateCorners(e){
    corners[1] = [e.layerX, e.layerY]
    redraw();
  }

  function redraw(){
    draw_context.clearRect(0, 0, canvas.width, canvas.height);
    draw_context.beginPath()
    draw_context.lineWidth = "2";
    draw_context.strokeStyle = "red";
    draw_context.rect(corners[0][0], corners[0][1], corners[1][0] - corners[0][0], corners[1][1] - corners[0][1]);
    draw_context.stroke();
  }

  function extractFrame(){
    var video = document.createElement('video');
    var array = [];

    function initCanvas(){
        canvas.width = this.videoWidth;
        canvas.height = this.videoHeight;
    }

    function drawFrame(e) {
        this.pause();
        context.drawImage(this, 0, 0);
        var blob = canvas.toBlob(saveFrame, 'image/png');
        var dataUrl = URL.createObjectURL(array[0]);
        document.getElementById('back').style.background = "url('${dataUrl}')";
        URL.revokeObjectURL(dataUrl);
    }

    function saveFrame(blob) {
        console.log(array);
        array.push(blob);
        console.log(array);
    }

    video.muted = true;
    video.addEventListener('loadedmetadata', initCanvas, false);
    video.addEventListener('timeupdate', drawFrame, false);
    video.src = URL.createObjectURL(this.files[0]);
    video.play();
  }

</script>

I've been messing with the ordering of the code, the objects I'm passing, etc. all day now and I have no idea what's keeping this from working. If it helps, one of the errors I get most often is

Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

Which a different question said may be because the object in the array is undefined or None or however JS describes it, but the logged array says that it is populated with blobs.

Any suggestions are appreciated. Happy to provide more code or specs if I can. Thanks!

EDIT: I've added more code so that it can be reproduced (I hope). I'm not hosting it anywhere but locally, so I hope this works for y'all.



from Recent Questions - Stack Overflow https://ift.tt/3c3g3ZA
https://ift.tt/eA8V8J

Rails refactoring a method

im a new developer and i need some help to refactor this code

So, I have a Rails App with a controller called subscription_signups. There i have a New method, that helps me create a Subscription, and it executes a private method called add_plan_to_cookies.

This is my controller

  def new
    @subscription_signup = SubscriptionSignup.new(account_id: current_account.id)
    add_plan_to_cookies
  end

  private 
  
   def add_plan_to_cookies
    plan = current_account.base_plans.find_by(id: params[:base_plan])&.current_plan
    remember_plan(plan.id) if plan.present?
    @plan = current_account.base_plans.find_by(id: cookies.signed[:plan])&.current_plan
  end

def remember_plan(plan)
  cookies.signed[:plan] = plan
end 

In the add_plan_to_cookies method, the plan is obtained through the base_plan_id and then another method called remember_plan is executed and saves the plan in a cookie. What i have to do is using the plan that was saved in the cookie. & I can obtain that with the second query, but there has to be a better way.

So first I get the ID of the params, look for the plan and add its id to the cookies. Then i have to use that id to search for the plan that you already got before.

MY problem is that the im doing too queries for something that is kind of the same, and i dont now have to refactor it. anyone has a suggestion?

In the view i have something like this.

<% if @plan.present? %>
  <%= @plan.name %>
  <%= image_tag @plan.base_plan.cover(:medium), class: "img-responsive "%>
<% end %>


from Recent Questions - Stack Overflow https://ift.tt/3uxsRhv
https://ift.tt/eA8V8J

How do I "sharpen" the edge of the path in the image with Stroke Path?

I'm trying to use the stroke path function on a jagged path as shown in the image. I'd prefer to keep the line width, cap style, join style the same. I've tried adjusting the miter limit, going all the way to 100, but i'm still getting that rounded edge at the bottom left corner of the path. Compared to the right side, it is noticeably different.

I've already tried adjusting all the settings in the stroke path section, even changing my path, increasing the angle of the corner, etc but nothing works. Any ideas?

Rounded edges from Stroke path on the right corner



from Recent Questions - Stack Overflow https://ift.tt/2RXSqen
https://ift.tt/2SCVFbc

Terraform split subnets between 2 route tables

I have created a large amount of azure subnets with terraform, but i need to split them all between 2 route tables.

Currently i have my code like this, but of course the output from the resource is not a list, but objects.

resource "azurerm_subnet_route_table_association" "subnet-to-rt1" {
  for_each       = tolist(chunklist(azurerm_subnet.subnets, 255)[0])
  subnet_id      = (chunklist(azurerm_subnet.subnets, 20)[0])[each.key].id
  route_table_id = module.spoke.route_table_1
}

resource "azurerm_subnet_route_table_association" "subnet-to-rt2" {
  for_each       = tolist(chunklist(azurerm_subnet.subnets, 20)[1])
  subnet_id      = (chunklist(azurerm_subnet.subnets, 20)[1])[each.key].id
  route_table_id = module.spoke.route_table_2
}

Edit: Code to generate the subnets for clarity of the problem. I provide the var.spoke_cidr in an slash /18 range to get /27's

resource "azurerm_subnet" "subnets" {
  for_each             = toset(slice(cidrsubnets(var.spoke_cidr, [for v in range(20) : 9]...), 2, length(cidrsubnets(var.spoke_cidr, [for v in range(20) : 9]...))))
  name                 = "az-subnet-${index(slice(cidrsubnets(var.spoke_cidr, [for v in range(20) : 9]...), 2, length(cidrsubnets(var.spoke_cidr, [for v in range(20) : 9]...))), each.key)}"
  resource_group_name  = module.spoke.azure_rg.name
  virtual_network_name = module.spoke.vnet.name
  address_prefixes     = [each.value]
}

The error code im getting for each route table association resource is

Invalid value for "list" parameter: list of any single type required.

Does anyone know how i can fix this route table associations Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3c2PVOH
https://ift.tt/eA8V8J

SQL unpivot of multiple columns

I would like the following wide table to be unpivotted but only where a user has a true value against the field, along with the appropriate date (please see image for a cleaner version: https://i.stack.imgur.com/9utkN.png).

Current State:


CUSTOMER_ID First_Party_Email Third_Party_Email First_Party_Email_Date Third_Party_Email_Date
40011111 1 1 2021-01-22 04:38:00.000 2021-01-17 06:38:00.000
50022222 NULL 1 NULL 2021-01-18 04:38:00.000
80066666 1 NULL 2021-01-24 05:38:00.000 NULL
_______________ _______________________ _______________________ _______________________________ _______________________________

Required State:


Customer_ID Type Value Date
40011111 First_Party_Email 1 22/01/2021 04:38
40011111 Third_Party_Email 1 17/01/2021 06:38
50022222 Third_Party_Email 1 18/01/2021 04:38
80066666 First_Party_Email 1 24/01/2021 05:38
_______________________________________________________________________

Associated query to create table and my attempt that doesn't work:

create table Permissions_Obtained
(Customer_ID bigint
,First_Party_Email  bit
,Third_Party_Email  bit
,First_Party_Email_Date datetime    
,Third_Party_Email_Date datetime
)

insert into Permissions_Obtained
(Customer_ID
,First_Party_Email
,Third_Party_Email
,First_Party_Email_Date
,Third_Party_Email_Date
)
VALUES
(40011111,  1,      1,      '2021-01-22 04:38', '2021-01-17 06:38'),
(50022222,  NULL,   1,      NULL,               '2021-01-18 04:38'),
(80066666,  1,      NULL,   '2021-01-24 05:38', null)

select * 
from Permissions_Obtained

select 
customer_id, Permission
from Permissions_Obtained
unpivot
(
  GivenPermission
  for Permission in (
First_Party_Email, Third_Party_Email
)
) unpiv1, 
unpivot
(
  GivenPermissionDate
  for PermissionDate in (
First_Party_Email_Date, Third_Party_Email_Date
)
) unpiv2
where GivenPermission = 1

--drop table Permissions_Obtained

Any help would be massively appreciated. TIA



from Recent Questions - Stack Overflow https://ift.tt/3fxxl3x
https://ift.tt/eA8V8J

Edit and save shared preferences in Android Studio

I can access shared preferences in Android Studio from Device file explorer, but after editing the file, the changed values aren't saved. How can I save the changes?



from Recent Questions - Stack Overflow https://ift.tt/3wLBTsu
https://ift.tt/eA8V8J

2021-05-29

Power BI - Prior Month Values and % Change for a existing measure which aggregates from daily to monthly

I have a table with daily observations. I have an existing measure (Total_Visits_Sum) that provides the data on a monthly or quarterly basis based on the date I use for the axis. If I use a custom column in the calendar for MMM-YY the data automatically gets aggregated.

SUMMARIZE (
    'Data',
    'Data'[Date]),
    CALCULATE (
    SUM ( 'Data'[Visits])))

My question is how do I get the prior month's value to compare, so I could do a month-over-month change? I have seen the examples that do this but only when the underlying frequency of the data is monthly, not aggregated like I am doing.



from Recent Questions - Stack Overflow https://ift.tt/3oYxhN8
https://ift.tt/eA8V8J

How to select using CONTAINS instead of LIKE with JPA

I'm developing small java applications to school projects with PostgreSQL.

Using the JDBC driver I could select a field using the ~ operator to act as CONTAINING instead of concatenating the filter using LIKE.

Let me give you an example:

SELECT * FROM USERS WHERE NAME ~ ? ORDER BY NAME

Since we started using the JPA framework to ease the development, I noticed that the same sample using JPA throws an error when I use the ~ operator...

Error thrown:

An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing [select u from Users u where u.name ~ ?1 order by u.name]. 
[30, 41] The expression is not a valid conditional expression.

All code samples I could find on google are made using LIKE instead of CONTAINING.

My question is, does JPA support the containing operator when working with PostgreSQL?

Some info:

JDK 15
Netbeans 12.3
JPA 2.1
PostgreSQL 13.2


from Recent Questions - Stack Overflow https://ift.tt/3fTLtTx
https://ift.tt/eA8V8J

Using Content-Security-Policy to allow ws connections on https website

I have a HTTPS website which needs to communicate with a backend securely. I also need it to be able to interface with some hardware that only accepts ws connections (NOT wss). I am wondering whether it is possible (and if so, exactly how) to connect with this hardware. I read here that setting the Content-Security-Policy header to certain values can help enable this. I was wondering if anyone knows whether this approach will work, or if they have suggestions for any other approaches.



from Recent Questions - Stack Overflow https://ift.tt/3p0xJKJ
https://ift.tt/eA8V8J

Forcing bandwidth from one router to another

So I have an two internet providers in two different locations. One is much better than the other with unlimited data and lightning fast speed while the other has unlimited data until it hits a wall at 15GB where the bandwidth is severely throttled back. It got me thinking... is it possible to force bandwidth from one router to another, and to be more specific, from one router to another not in the same location as each other. I know it’s possible to do when hardwired and a little knowhow as well as removing the throttle put in place on one that is throttled, but has anyone ever tried something like this?



from Recent Questions - Stack Overflow https://ift.tt/3wFpFBR
https://ift.tt/eA8V8J

Can I allow users to delete my Slack bot messages?

I created a Slack bot that allows coworkers to report issues to certain channels, but occasionally someone misclicks or wants their report (reported in Slack by the bot via chat.postmessage) deleted. As far as I can tell, this can only be done by the bot itself through a message shortcut or an interactive message with chat.delete. I would like it to be deletable by users in the same way they would delete their own messages, by clicking the ellipses on the post and choosing delete message in the context menu. Is there a way, either by OAuth scopes or maybe Slack/Workspace/Channel admin permissions this can be done?



from Recent Questions - Stack Overflow https://ift.tt/3c1X3dY
https://ift.tt/eA8V8J

Undefined references when linking libpng

I'm compiling a planet map generator that requires libpng. While I successfully fixed other errors, this was impossible to remove:

png_utils.o:png_utils.c:(.text+0x91): undefined reference to `png_create_write_struct'
png_utils.o:png_utils.c:(.text+0xa4): undefined reference to `png_create_info_struct'
png_utils.o:png_utils.c:(.text+0xca): undefined reference to `png_set_longjmp_fn'
png_utils.o:png_utils.c:(.text+0x135): undefined reference to `png_set_IHDR'
png_utils.o:png_utils.c:(.text+0x14e): undefined reference to `png_malloc'
png_utils.o:png_utils.c:(.text+0x19e): undefined reference to `png_malloc'
png_utils.o:png_utils.c:(.text+0x217): undefined reference to `png_init_io'
png_utils.o:png_utils.c:(.text+0x230): undefined reference to `png_set_rows'
png_utils.o:png_utils.c:(.text+0x252): undefined reference to `png_write_png'
png_utils.o:png_utils.c:(.text+0x281): undefined reference to `png_free'
png_utils.o:png_utils.c:(.text+0x297): undefined reference to `png_free'
png_utils.o:png_utils.c:(.text+0x2af): undefined reference to `png_destroy_write_struct'
png_utils.o:png_utils.c:(.text+0x35e): undefined reference to `png_malloc'
png_utils.o:png_utils.c:(.text+0x47c): undefined reference to `png_destroy_read_struct'
png_utils.o:png_utils.c:(.text+0x4b4): undefined reference to `png_sig_cmp'
png_utils.o:png_utils.c:(.text+0x4e0): undefined reference to `png_create_read_struct'
png_utils.o:png_utils.c:(.text+0x4f3): undefined reference to `png_create_info_struct'
png_utils.o:png_utils.c:(.text+0x509): undefined reference to `png_create_info_struct'
png_utils.o:png_utils.c:(.text+0x52f): undefined reference to `png_set_longjmp_fn'
png_utils.o:png_utils.c:(.text+0x60e): undefined reference to `png_init_io'
png_utils.o:png_utils.c:(.text+0x621): undefined reference to `png_set_sig_bytes'
png_utils.o:png_utils.c:(.text+0x643): undefined reference to `png_read_png'
png_utils.o:png_utils.c:(.text+0x689): undefined reference to `png_get_IHDR'
png_utils.o:png_utils.c:(.text+0x6f2): undefined reference to `png_get_rowbytes'
png_utils.o:png_utils.c:(.text+0x718): undefined reference to `png_get_rows'
png_utils.o:png_utils.c:(.text+0x941): undefined reference to `png_destroy_read_struct'

I use MinGW-x64 and mingw32-make without msys2 installed. libpng 1.6.37-4 is installed in both folders and I used -lpng and -lpng16 but it still didn't work.



from Recent Questions - Stack Overflow https://ift.tt/2SEfFdu
https://ift.tt/eA8V8J

RHEL 8.3: Toggle Top Icons Plus Gnome extension in Tweak Tool with script

Is there a way to toggle the Gnome Extension Top Icons Plus in Tweak Tool in a script?

Currently I am unable to find any APIs provided by Tweak Tool or Top Icons Plus.



from Recent Questions - Stack Overflow https://ift.tt/3fw1L5X
https://ift.tt/eA8V8J

Nginx URL rewrite for language parameters

I have recently localized my php webpage with Gettext in a VPS running LEMP Debian 10 (PHP 7.3.27-1~deb10u1). The localized versions of the pages have the following URLs:

example.com/index.php?lang=es_ES

and

example.com/index.php?lang=en_GB

and so on.

I am trying get Nginx to rewrite the URL requests to fake folders in the following way:

example.com/en/index.php to=> example.com/index.php?lang=en_GB

example.com/es/index.php to=> example.com/index.php?lang=es_ES

and

example.com/en/manage/index.php to=> example.com/manage/index.php?lang=en_EN

example.com/es/manage/index.php to=> example.com/manage/index.php?lang=es_ES

And so on. I have tried other solutions with no success. My Nginx server block configuration is as follows:

server {

    root /var/www/example.com;
    index index.html index.htm index.php;

    server_name example.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

    location ~ /(.*)$ {
        try_files $uri $uri/ /profiles.php?user-id=$1; #pretty urls for user profiles
    }

    listen 443 ssl;
}

There is already a rewrite in place: example.com/123 => example.com/profiles.php?user-id=123. I'd appreciate some insight on making the desired rewrites to work, without affecting the one already in place. Thanks



from Recent Questions - Stack Overflow https://ift.tt/3uvRj2E
https://ift.tt/eA8V8J

SQL Finding Order ID and Total Price of Each Order

I have a database where I have to determine the OrderID and total price of each order. The issue is finding the price on the specific day of the order. Every product has a price on a particular day using the "from" attribute. I need to get only the price of the product where the "from" attribute is less than the current "date" attribute.

This is what I have been trying.

SELECT
    O.orderId,
    (P.price + S.price) AS total_price
FROM Price P
    INNER JOIN PO ON PO.prodId = P.prodId
    INNER JOIN [Order] O ON PO.orderId = O.orderId
    INNER JOIN Shipping S ON S.shipId = O.shipId
GROUP BY
    O.orderId,
    O.[date],
    P.price,
    S.price
HAVING O.[date] IN (
        SELECT
            O.[date]
        FROM
            [Order]
        WHERE
            MAX(P.[from]) <= O.date
    )
ORDER BY  orderId;

I still get some duplicates from this and it is not giving me every orderId.



from Recent Questions - Stack Overflow https://ift.tt/3wH5nYJ
https://ift.tt/eA8V8J

Return true if the array contains duplicate elements (which need not be adjacent)

When I execute this, even if there are no duplicates, it displays true. Basically, it displays true for every array that I put in. I have no idea why it's showing me that. I would appreciate some help in this problem! Thanks!

public static boolean Duplicate()
{
 int [] duplicateArray = new int[5];
 System.out.print("Enter your array numbers:");
 System.out.println();
 for(int i = 0; i < duplicateArray.length; i++)
 {
 Scanner in = new Scanner(System.in);
 duplicateArray[i] = in.nextInt();
 }
 boolean same = false;
 for(int i = 0; i < duplicateArray.length-1; i++)
 {
  for(int j = 0; j < duplicateArray.length; j++)
  {
  
   if(i==j)
   {
    same = true;
   }
  }
 }
 return same;
}


from Recent Questions - Stack Overflow https://ift.tt/3yOmBFx
https://ift.tt/eA8V8J

three.js, How do I get a CSS3DObject to show up? (what am I doing wrong)

I set up a CSS3DRenderer, a scene, a camera, in my HTML document I have an element that I am trying to turn into a CSS3DObject, and I have my CSS3DRenderer using .render in a game loop. I created a CSS3D object, put the HTML element as the argument, added it to my scene, and nothing happened. I must add that I do have a WebGL renderer using the same camera and a different scene, that renderer is working just fine. Here are my import statements:

import * as THREE from 'https://threejs.org/build/three.module.js';
import { GLTFLoader } from 'https://threejs.org/examples/jsm/loaders/GLTFLoader.js';
import { CSS3DRenderer } from 'https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js';
import { CSS3DObject } from 'https://threejs.org/examples/jsm/renderers/CSS3DRenderer.js';

Here is how I initialized the renderers:

const renderer = new THREE.WebGLRenderer({canvas: document.querySelector('#bg')});
const cssRenderer = new CSS3DRenderer();

this is me trying to put the CSS renderer infront of the WEBGL one:

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth,window.innerHeight);
cssRenderer.setSize(window.innerWidth,window.innerHeight);
cssRenderer.domElement.style.position = 'fixed';
cssRenderer.domElement.style.top = 0;
renderer.domElement.style.zIndex = 0;
cssRenderer.domElement.style.zIndex = 1;
renderer.domElement.style.position = 'fixed';
renderer.domElement.style.top = 0;

And finally, this is how I initialized the CSS3DObject (planeMesh is just a mesh I'm trying to put the CSS3Dobject on):

var embed = document.querySelector(".embed");
var embed3D = new CSS3DObject(embed);
embed3D.position.set(planeMesh.position);
embed3D.rotation.set(planeMesh.rotation);
cssScene.add(embed3D);

I have confirmed that my program is reading the HTML element correctly, but everything beyond that has me stumped, any help would be greatly appreciated. (sorry about any bad practices that may be apparent, I am pretty new to javascript)



from Recent Questions - Stack Overflow https://ift.tt/3fWuEHo
https://ift.tt/eA8V8J

How do I write this in SQL view?

create a view called StudentListByCourse. The view should contain these columns from the following ER model and the output should be sorted by the course name:

Course name
Student name
Student age

enter image description here

This is what I have but im not sure if this is correct

CREATE VIEW StudentListByCourse
SELECT *
FROM student AS s
WHERE courses AS c
SORT BY c.coursename, s.studentname, s.studentage


from Recent Questions - Stack Overflow https://ift.tt/34sH5Wi
https://ift.tt/34sH6tk

Registering a “typed” gRPC client with the ASP.NET Core DI container

I have a GrpcService class the takes in gRPC client in its constructor, like so:

public class GrpcService : IService 
{
    private readonly GrpcClient grpcClient;
 
    public GrpcService(GrpcClient grpcClient)
    {
        this.grpcClient = grpcClient;
    }
    
    //...
}

I have registered the gRPC client in the Startup class by using the generic AddGrpcClient extension method:

services.AddGrpcClient<GrpcClient>(o =>
{
    o.Address = new Uri("https://localhost:5001");
});

Now I want to inject the GrpcService class into a API controller. My question is; what's is the correct way to register the GrpcService in the Startup class?

I did try the following, which did not work:

services.AddGrpcClient<GrpcService>(); 

At the moment I have the following code, which works fine:

services.AddSingleton<IService, GrpcService>();

However, I'm not certain using a singleton is the correct lifetime to use, in particular as the gRPC client uses HttpClient internally?



from Recent Questions - Stack Overflow https://ift.tt/3g8PmUX
https://ift.tt/eA8V8J

How to read a file in utf8 encoding and output in Windows 10?

What is proper procedure to read and output utf8 encoded data in Windows 10?

My attempt to read utf8 encoded file in Windows 10 and output lines into terminal does not reproduce symbols of some languages.

  • OS: Windows 10
  • Native codepage: 437
  • Switched codepage: 65001

In cmd window issued command chcp 65001. Following ruby code reads utf8 encoded file and outputs lines with puts.

fname = 'hello_world.dat'

File.open(fname,'r:UTF-8') do |f|
    puts f.read
end

hello_world.dat content

Afrikaans:    Hello Wêreld!
Albanian:     Përshendetje Botë!
Amharic:      ሰላም ልዑል!
Arabic:       مرحبا بالعالم!
Armenian:     Բարեւ աշխարհ!
Basque:       Kaixo Mundua!
Belarussian:  Прывітанне Сусвет!
Bengali:      ওহে বিশ্ব!
Bulgarian:    Здравей свят!
Catalan:      Hola món!
Chichewa:     Moni Dziko Lapansi!
Chinese:      你好世界!
Croatian:     Pozdrav svijete!
Czech:        Ahoj světe!
Danish:       Hej Verden!
Dutch:        Hallo Wereld!
English:      Hello World!
Estonian:     Tere maailm!
Finnish:      Hei maailma!
French:       Bonjour monde!
Frisian:      Hallo wrâld!
Georgian:     გამარჯობა მსოფლიო!
German:       Hallo Welt!
Greek:        Γειά σου Κόσμε!
Hausa:        Sannu Duniya!
Hebrew:       שלום עולם!
Hindi:        नमस्ते दुनिया!
Hungarian:    Helló Világ!
Icelandic:    Halló heimur!
Igbo:         Ndewo Ụwa!
Indonesian:   Halo Dunia!
Italian:      Ciao mondo!
Japanese:     こんにちは世界!
Kazakh:       Сәлем Әлем!
Khmer:        សួស្តី​ពិភពលោក!
Kyrgyz:       Салам дүйнө!
Lao:          ສະ​ບາຍ​ດີ​ຊາວ​ໂລກ!
Latvian:      Sveika pasaule!
Lithuanian:   Labas pasauli!
Luxemburgish: Moien Welt!
Macedonian:   Здраво свету!
Malay:        Hai dunia!
Malayalam:    ഹലോ വേൾഡ്!
Mongolian:    Сайн уу дэлхий!
Myanmar:      မင်္ဂလာပါကမ္ဘာလောက!
Nepali:       नमस्कार संसार!
Norwegian:    Hei Verden!
Pashto:       سلام نړی!
Persian:      سلام دنیا!
Polish:       Witaj świecie!
Portuguese:   Olá Mundo!
Punjabi:      ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ!
Romanian:     Salut Lume!
Russian:      Привет мир!
Scots Gaelic: Hàlo a Shaoghail!
Serbian:      Здраво Свете!
Sesotho:      Lefatše Lumela!
Sinhala:      හෙලෝ වර්ල්ඩ්!
Slovenian:    Pozdravljen svet!
Spanish:      ¡Hola Mundo!
Sundanese:    Halo Dunya!
Swahili:      Salamu Dunia!
Swedish:      Hej världen!
Tajik:        Салом Ҷаҳон!
Thai:         สวัสดีชาวโลก!
Turkish:      Selam Dünya!
Ukrainian:    Привіт Світ!
Uzbek:        Salom Dunyo!
Vietnamese:   Chào thế giới!
Welsh:        Helo Byd!
Xhosa:        Molo Lizwe!
Yiddish:      העלא וועלט!
Yoruba:       Mo ki O Ile Aiye!
Zulu:         Sawubona Mhlaba!

image_1 image_2



from Recent Questions - Stack Overflow https://ift.tt/3wykPX4
https://ift.tt/3oXiKRW

Show / hide element based on which option was selected [closed]

What would be the JavaScript code to display the input field if I choose the second <option> tag and reverse (do not display input) if I choose the first <option>?

<div id="bmi">
  <p id="head">
    BMI Calculator
  </p>
  <p><b>Select the Measure
    <select id="method" onchange="standard()">
      <option id="metric">Metric</option>
      <option id="standard">Standard</option>
    </select>
  </b></p>
  <p><b>Input your Height Below:</b></p>
  <br>
  <input type="text" id="height" />
  <p><b>Input your Weight Below:</b></p>
  <input type="text" id="weight" />
  <br>
  <button id="onSubmit">Calculate</button>
  <br>
  <h1 id="result"></h1>
</div>


from Recent Questions - Stack Overflow https://ift.tt/3c1Emr2
https://ift.tt/eA8V8J

Quick search for an object in an array

The task is to quickly find an object in the array.

There is an array containing data about users. During the course of the program, the data of individual users will change. What is the most efficient way to search for a user in an array?

I've read about hash functions and hash tables, but I don't fully understand how I need to use them. I should create a dictionary like:

{'name of user': index}


from Recent Questions - Stack Overflow https://ift.tt/3wLDZsF
https://ift.tt/eA8V8J

how to open all links in a file and ignore comments using firefox?

so the file contains data like

# entertainment
youtube.com
twitch.tv

# research
google.com
wikipedia.com
...

and I would like to pass that file as an argument in a script that would open all lines if they doesn't start with an #. Any clues on how to ?

so far what i have:

for Line in $Lines
do
case "# " in $Line start firefox $Line;; esac
done

some code that could be useful (?):

while read line; do chmod 755 "$line"; done < file.txt


from Recent Questions - Stack Overflow https://ift.tt/3wHULIW
https://ift.tt/eA8V8J

How do I pass the value of a variable in C to an argument of an instruction in inline assembly? [duplicate]

I am trying to use the value of a variable I've declared in C as the argument of a mov instruction in assembly. I've tried using a conversion character like this (where ptr is the variable):

asm("mov x9, %p\n\t" : : "r"(ptr));

But it doesn't compile and outputs an error of:

error: invalid % escape in inline assembly string
            asm("mov x9, %p\n\t" : : "r"(ptr));
                ~~~~~~~~~~~^~~~~

I've also tried it without the \n\t and it gives the same error. It's not really specific as to what's wrong with it so I'm not sure how to deal with this. How can I get it to compile or achieve the same outcome in a different way?



from Recent Questions - Stack Overflow https://ift.tt/34pA88m
https://ift.tt/eA8V8J

Is it even possible to filter a JsonField tuple or list? (Filtering only works for dictionaries?)

The documentation has info on querying JsonFields for dictionaries but not for lists or tuples.

# models.py
class Item(model):
    numbers = JSONField()

# tests.py
a = Item.objects.create(numbers=(1, 2, 3))
b = Item.objects.create(numbers=(4, 5, 6))

Item.objects.filter(numbers=a.numbers).count() # returns 0
Item.objects.filter(numbers__0=a.numbers[0]).count() # returns 0

Item.objects.all().count() # correctly returns 2
a.numbers # correctly returns (1, 2, 3)
a.numbers[0] # correctly returns 1

How can I query or filter by a JsonField if that field is a tuple or list?



from Recent Questions - Stack Overflow https://ift.tt/3vwiOut
https://ift.tt/eA8V8J

How to use both MFRC522 and RDM6300 using a NODEMCU

I want to use both MFRC522 and RDM6300 readers on a single NodeMCU, the two separate codes for each readers are respectively :

/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 * 
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 * 
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 * 
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 * 
 * @license Released into the public domain.
 * 
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = D3;     // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = D4;     // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(230400);       // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    delay(4);               // Optional delay. Some board do need more time after init to be ready, see Readme
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

and

/*
 * A simple example to interface with rdm6300 rfid reader using esp8266.
 * We use hardware uart "Serial" instead of the default software uart driver.
 *
 * Note:
 *     The esp8266 let us use 1.5 uarts:
 *     Serial=uart0=rx+tx, Serial1=uart1=tx only (rx pin is used as flash io).
 *     Here we sawp the uart pins so uart0_rx goes to the rdm6300_tx,
 *     and uart1_tx goes to what used to be uart0_tx-
 *     so debug message goes from Serial1.print(...) to the pc debug terminal.
 *     https://github.com/esp8266/Arduino/blob/master/doc/reference.rst#serial
 *
 * Connections:
 *     | esp8266 | nodemcu | rdm6300 | notes                               |
 *     |---------+---------+---------|-------------------------------------|
 *     | GPIO-01 | TX      |         | This is TXD0, connect it to GPIO-02 |
 *     | GPIO-02 | D4      |         | This is TXD1, connect it to GPIO-01 |
 *     | GPIO-03 | RX      |         | Leave it unconnected for flashing   |
 *     | GPIO-13 | D7      | TX      | TX level is same 3.3V as esp8266    |
 *     |         | VU (5V) | VCC     | The rdm6300 must be powered with 5V |
 *     | GND     | GND     | GND     |                                     |
 *
 *     * GPIO-01 to GPIO-02 is for debug terminal output.
 *
 * Arad Eizen (https://github.com/arduino12).
 */
#include <rdm6300.h>

#define RDM6300_RX_PIN 13 // can be only 13 - on esp8266 force hardware uart!
#define READ_LED_PIN 16

Rdm6300 rdm6300;

void setup()
{
  /* Serial1 is the debug! remember to bridge GPIO-01 to GPIO-02 */
    Serial1.begin(230400);

  pinMode(READ_LED_PIN, OUTPUT);
  digitalWrite(READ_LED_PIN, LOW);

  rdm6300.begin(RDM6300_RX_PIN);

  Serial1.println("\nPlace RFID tag near the rdm6300...");
}

void loop()
{
  /* if non-zero tag_id, update() returns true- a new tag is near! */
  if (rdm6300.update())
    Serial1.println(rdm6300.get_tag_id(), DEC);

  digitalWrite(READ_LED_PIN, rdm6300.is_tag_near());

  delay(10);
}

I tried merging the code but had no good results. Does anyone know how to get it to use the 2 readers at the same time? There is little to no information on doing that on Google. Thanks in advance



from Recent Questions - Stack Overflow https://ift.tt/3vzxtF3
https://ift.tt/eA8V8J