2021-06-30

How to reuse function attribute?

I want to do something like the following:

function StatusBox() {
    this.connectionStatus = $("#connectionStatus");
}

StatusBox.nosupport = function(type) {
    StatusBox.connectionStatus.html('<span style="color: red;">' + NO_SUPPORT + '</span>');
};

StatusBox.error = function(type) {
    StatusBox.connectionStatus.html('<span style="color: red;">' + ERROR + '</span>');
};

But I get Uncaught TypeError: Cannot read property 'html' of undefined

How do I reuse $("#connectionStatus") in the child functions?



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

Autoencoder not learning well when have deeper layers

I am building a deep CNN autoencoder on time series data. When I experiment with different layers, I found something that I can not explain:

  1. when I have more layers, i.e. the encoder bottleneck layer will have smaller dimensions of the kernel and more layers for the decoder layers (because it is symmetric), I found the test performance (MSE) is increasing, the training error increasing as well. I was thinking more layers will have better encoding capability and should decrease the error, but the results are opposite.
  2. Also, when I decrease the dimension of the bottleneck to a certain level (say adding 5 layers to the encoder), the model seems not to learn at all, the validation loss basically is the same from the very first few epoch (only change slightly at the beginning). No matter how many kernels I use, the results are the same. But if I reduce the encoder layers, and make it shallower, it learns without any problem.

My structure of autoencoder is similar to this CNN autoencoder on tensorflow tutorial, with only the difference of adding more layers. Also, I am increasing the number of kernels with deeper layers instead of decreasing as the one shown on their website. Because I was thinking that the deeper the layers, your features are more high-level and specific that you need more kernels to capture them. Does this sound right?

Really hope I can get some suggestions here. Thanks in advance.



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

I have a numerical question related to TD(0) algorithm. I tried to solve it in many different ways but my answers don't match

enter image description here

Q7 here. Link to the original file is https://nptel.ac.in/content/storage2/courses/downloads_new/106106143/noc20_cs51_assigment_7.pdf



from Recent Questions - Stack Overflow https://ift.tt/3xj8KG9
https://ift.tt/3h4KIst

How can I use uTLS with resty?

I'm working on an application that makes API requests to a server. Both GET and POST. The API server that I am attempting to communicate with uses TLS 1.3 and my requests are currently getting 403 error due to my lack of TLS implementation.

My application currently uses the go-resty library to make requests. I would like to implement TLS 1.3 support with the uTLS library. I'm using resty due to its simplicity and uTLS because it offers parrots of browsers such as utls.HelloChrome_58 which I need to get passed the 403 error.

How can I implement uTLS into resty?



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

SQL - Sum of wages group by other columns

Need help with the query

I have a table like below (This is trimmed version, this table contains 11-12 Billion rows with 25 years worth of data. Need to sum gw based on pType as category and separated by combination of eid and cid

eid cid ID      pDate   pFreq   gw      PHrs    pType
637 163 2037    1/8/21  1       8.13    NULL    S
637 163 2037    1/8/21  1       162.5   NULL    V
228 787 2037    1/8/21  1       8.13    NULL    S
228 787 2037    1/8/21  1       162.5   NULL    V
637 163 2037    1/8/21  1       474.5   NULL    R
228 787 2037    1/8/21  1       474.5   NULL    R
637 163 2037    1/8/21  1       130     NULL    H
228 787 2037    1/8/21  1       130     NULL    H
637 163 2037    1/15/21 1       602.88  NULL    R
228 787 2037    1/15/21 1       602.88  NULL    R
637 163 2037    1/22/21 1       32.5    NULL    V
228 787 2037    1/22/21 1       619.13  NULL    R
637 163 2037    1/22/21 1       619.13  NULL    R
228 787 2037    1/22/21 1       32.5    NULL    V
228 787 2037    1/27/21 1       300     NULL    B
637 163 2037    1/27/21 1       300     NULL    B
637 163 2037    1/29/21 1       48.75   NULL    V
228 787 2037    1/29/21 1       48.75   NULL    V
637 163 2037    1/29/21 1       248.14  NULL    O
637 163 2037    1/29/21 1       425.26  NULL    R
228 787 2037    1/29/21 1       248.14  NULL    O
228 787 2037    1/29/21 1       425.26  NULL    R
637 163 2037    1/29/21 1       130     NULL    H
228 787 2037    1/29/21 1       130     NULL    H
637 163 2037    2/5/21  1       65      NULL    S
228 787 2037    2/5/21  1       65      NULL    S
637 163 2037    2/5/21  1       587.11  NULL    R
228 787 2037    2/5/21  1       587.11  NULL    R
228 787 2037    2/12/21 1       617.99  NULL    R
637 163 2037    2/12/21 1       617.99  NULL    R
637 163 2037    2/19/21 1       635.7   NULL    R
228 787 2037    2/19/21 1       635.7   NULL    R
637 163 2037    2/26/21 1       654.06  NULL    R
228 787 2037    2/26/21 1       654.06  NULL    R
637 163 2037    3/5/21  1       162.5   NULL    V
228 787 2037    3/5/21  1       489.45  NULL    R
637 163 2037    3/5/21  1       489.45  NULL    R
228 787 2037    3/5/21  1       162.5   NULL    V
637 163 2037    3/12/21 1       24.38   NULL    O
637 163 2037    3/12/21 1       650     NULL    R
228 787 2037    3/12/21 1       24.38   NULL    O
228 787 2037    3/12/21 1       650     NULL    R
637 163 2037    3/19/21 1       614.74  NULL    R
228 787 2037    3/19/21 1       614.74  NULL    R
637 163 2037    3/19/21 1       48.75   NULL    S
228 787 2037    3/19/21 1       48.75   NULL    S
228 787 2037    3/26/21 1       100.43  NULL    O
228 787 2037    3/26/21 1       650     NULL    R
637 163 2037    3/26/21 1       100.43  NULL    O
637 163 2037    3/26/21 1       650     NULL    R

when i run the below query,

> SELECT m.eid,m.cid,m.id,p.pDate,p.pFreq,p.PHrs, SUM(CASE WHEN p.pType
> IN ('H','N','R','S','V') THEN p.gw ELSE 0 END) AS gw_r, SUM(CASE WHEN
> p.pType IN ('B','I','') THEN p.gw ELSE 0 END) AS gw_b, SUM(CASE WHEN
> p.pType IN ('O') THEN p.gw ELSE 0 END) AS gw_ot, SUM(CASE WHEN p.pType
> IN ('C','D','E','K','M','P','T','UP','US','UV','W') THEN p.gross_wages
> ELSE 0 END) AS gw_o  FROM [dbo].[mup] m   JOIN ccc.dbo.ppart p on
> m.id=p.id     JOIN ccc.dbo.cli cli on m.cid=cli.cid   JOIN CCC.dbo.cldt
> cd on m.cid=cd.cid
>     where p.pDate BETWEEN '01/01/2021' AND '06/30/2021'   and p.id=2037 GROUP BY m.eid,m.cid,m.location,m.id,p.pDate,p.pFreq,p.PHrs ORDER BY
> p.pDate

Output returning as

eid cid ID      pDate   pFreq   PHrs    gw_r    gw_b    gw_ot   gw_o
637 163 2037    1/8/21  1       NULL    775.13  0       0       0
228 787 2037    1/8/21  1       NULL    775.13  0       0       0
228 787 2037    1/15/21 1       NULL    602.88  0       0       0
637 163 2037    1/15/21 1       NULL    602.88  0       0       0
228 787 2037    1/22/21 1       NULL    651.63  0       0       0
637 163 2037    1/22/21 1       NULL    651.63  0       0       0
228 787 2037    1/27/21 1       NULL    0       300     0       0
637 163 2037    1/27/21 1       NULL    0       300     0       0
637 163 2037    1/29/21 1       NULL    604.01  0       248.14  0
228 787 2037    1/29/21 1       NULL    604.01  0       248.14  0
637 163 2037    2/5/21  1       NULL    652.11  0       0       0
228 787 2037    2/5/21  1       NULL    652.11  0       0       0
637 163 2037    2/12/21 1       NULL    617.99  0       0       0
228 787 2037    2/12/21 1       NULL    617.99  0       0       0
637 163 2037    2/19/21 1       NULL    635.7   0       0       0
228 787 2037    2/19/21 1       NULL    635.7   0       0       0
228 787 2037    2/26/21 1       NULL    654.06  0       0       0
637 163 2037    2/26/21 1       NULL    654.06  0       0       0
228 787 2037    3/5/21  1       NULL    651.95  0       0       0
637 163 2037    3/5/21  1       NULL    651.95  0       0       0
637 163 2037    3/12/21 1       NULL    650     0       24.38   0
228 787 2037    3/12/21 1       NULL    650     0       24.38   0
637 163 2037    3/19/21 1       NULL    663.49  0       0       0
228 787 2037    3/19/21 1       NULL    663.49  0       0       0
637 163 2037    3/26/21 1       NULL    650     0       100.43  0
228 787 2037    3/26/21 1       NULL    650     0       100.43  0

Issue is: gw_r, gw_b, gw_ot, gw_o is giving me duplicate results. How do i fix this? Couldn't figure-out a way to fix this

Appreciate all the help/suggestions

Thank you, Yum Vee



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

Best way to iterate through an argument of a userfunction which is representing a data variable

Good evening,

I would like to save some time in the future and automate the application of a user function in the future.

The data contains different observations (rows) which consist of a grouping and multiple other variables. It looks something like this df:

df <- data.frame(obs=c(1,2,3,4,5,6,7,8),
                 group=c("a","a","b","a","b","c","a","b"),
                 var1=c(1,1,2,1,3,1,1,2),
                 var2=c(1,2,3,3,2,1,4,5),
                 var3=c(5,4,3,1,2,3,2,5),
                 var4=c(4,5,4,2,3,4,5,3))

I wrote a user function foo_1 to evaluate the occurrence of attributes in each variable with optional grouping. The function also allows to just return the result or to write it to a file.

library(tidyverse)

foo_1 <- function(DF,VAR,grouping=FALSE,char=c(1,2,3,4,5),save=FALSE,name=NULL){
  tostring<-function (some_variable, name=deparse(substitute(some_variable))) {
    return(str_remove(name,"~"))}
    
    Obj <- DF %>% 
      select(group,) %>% 
      {if (grouping) group_by(.,group) else .} %>% 
      count() %>% 
      rename("Variable"=) %>% 
      complete(Variable=char,fill=list(n=0)) # can't use `complete(=char,fill=list(n=0))` for whatever reason
    
    if (save & !is.null(name)){
      message(paste0("Writing file to ","./",name))
      #write.csv2(Obj,paste0("./",name)) #deactivated since it is not really necessary for the mwe I guess
      message("File has been saved.")
    }
    
    else if (save & is.null(name)) {
      message("Showing preview of file..:")
      print(Obj)
      message("What name should be used to save the file? (incl. file format)")
      name <- scan(n=1,what="character")
      message(paste0("Writing file to ","./",name))
      #write.csv2(Obj,paste0("./",name)) #deactivated since it is not really necessary for the mwe I guess
      message("File has been saved.")
    }
    
    else {
      return(Obj)
    }
    
}

The function itselfs works:

> df %>% 
+   foo_1(VAR=var1,save=TRUE,name="test_var1.csv")
Writing file to ./test_var1.csv
File has been saved.

I now would like to iterate though the variables of the df as argument VAR to function foo_1. My approach with a for loop just returns an error message:

> for (i in paste0("var",1:4)){
+   df %>% 
+     foo_1(,save=TRUE,name=paste0("test_",,".csv"))
+ }
 Fehler: Can't rename columns that don't exist.
x Column `var1` doesn't exist.

Probably the way I'am referencing to the data variable is not the best for this purpose?



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

How can I resolve various warnings during compilation of my React app?

I got these warnings in my react project: (The packages in the node_module folder are up-to-date.)

How can I solve these warnings?

/src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Warning

(309:5) start value has mixed support, consider using flex-start instead printWarnings @ webpackHotDevClient.js:138

./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Warning

(457:5) Gradient has outdated direction syntax. New syntax is like to left instead of right.

./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Warning

(477:5) Gradient has outdated direction syntax. New syntax is like to left instead of right.

./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Warning

(497:5) Gradient has outdated direction syntax. New syntax is like to left instead of right.



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

Refused to set unsafe header "User-Agent"

I want to change the header's User-Agent to something like {"User-Agent":"someCustomValue"} but I get this error:

Refused to set unsafe header "User-Agent"

How to solve this? The problem only appears in flutter-web, it's ok in android and ios.



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

Replace line in file using re

Why is my code not working properly? I'm trying to replace one line in file using the re module:

import re

file = open("php.ini", "r+")

pattern = r'post_max_size = [0-9]'
result = re.search(pattern, file.read())

for line in file:        
    re.sub(pattern, "post_max_size = 1G", file.read())

file.close()
print(result)

I have done this by using the fileimport library, but this is not the way. Why can't it run properly while pattern is printing good result and re.sub() should replace it in this place in file?



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

Soap Web service return null value

I want to use a web service for my project and I'm sure web service work properly(I tested in Boomerang - SOAP & REST Client). Web service link is https://api.n11.com/ws/ProductService.wsdl. But when I try get datas from service, service returns null, empty or 0 values. I think VS add web service reference doesn't work correctly, But couldn't find where the problem is.

  static async Task<String> GetProductAsyncN11()
    {

        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var port = new N11ProductServiceReference.ProductServicePortClient();
        var requ = new GetProductListRequest();
        requ.auth = new N11ProductServiceReference.Authentication();         
        requ.auth.appKey = "*****";
        requ.auth.appSecret = "*****";
        requ.pagingData = new N11ProductServiceReference.RequestPagingData();
        requ.pagingData.pageSize = 100;
        requ.pagingData.currentPage = 0;
        var list =await port.GetProductListAsync(requ);
        Console.WriteLine(list.GetProductListResponse.products.Rank);
        Console.WriteLine("xx" + list.GetProductListResponse.result.status);
        Console.WriteLine("xx" + list.GetProductListResponse.products.Length);
        foreach (var item in list.GetProductListResponse.products)
        {
            Console.WriteLine(item.productSellerCode+item.price+item.saleStatus);
        }
        return "n11";
    } 

Response is here

enter image description here

Also When I use Boomerang - SOAP & REST Client, here is the response

enter image description here



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

I need to make a dictionary from a list of lists

I have this:

A = [[0, 3, 6, 11], [0, 5, 7, 11], [0, 1, 2, 4, 8, 9, 10, 11]]

I want to make a diccionary from A like this:

dic_A = { 0: [0, 3, 6, 11], 1: [0, 5, 7, 11], 2: [0, 1, 2, 4, 8, 9, 10, 11]}

I have tried different ways and I can only use a for in range to solve the problem I think this can be reduced to a line somehow but I can't find the way

I tried this:

    dic_A = {}
    for i in range(3):
         dict_A[i] = A[i]
        
          


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

Start Django development server on AWS EC2 Amazon Linux

This tutorial here shows how to start the development server on AWS EC2:

ALLOWED_HOSTS=['EC2_DNS_NAME']

...

python manage.py runserver 0.0.0.0:8000
In a browser, navigate to public DNS of the instance, make sure to append port “8000” at the end and if everything was properly configured, it will show the index page of the application.
For example: www.ec2dnsname.com:8000

My public IPv4 DNS is of this form:

ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com

So, in my settings.py

ALLOWED_HOSTS=['ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com']

And run this in the EC2 terminal:

python manage.py runserver 0.0.0.0:8000

However, when I try to reach this address:

www.ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com:8000

nothing is showing up (The page took too long to respond).

Is this the complete and correct way to just try run a development server on AWS EC2?



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

Union vs Inheritance in python implementation

Let's say we have this class.

class MyConfig():
   config_type : SomeEnum 
   retries: int
   context: Context

This Context depends on the value of type meaning the context is dependent on its value. Which implementation of Context is best? why one is better than the other.


class MySpecificContext:
   value: int
   name: str

class OtherUnrelatedContext:
   length:int
    position: int

Contex = Union[MySpecificContex,OtherUnrelatedContext]

or

class Context:
   pass

class MySpecificContext(Context):
   value: int
   name: str

class OtherUnrelatedContext(Context):
   length:int
    position: int

To be more specific. Let say you have a configuration class, this configuration will hold data that will be used to configure a process. This process will contain a few things that relate to all configurations, like retries value. However, it is expected that based on config_type there is an additional context that is required. This is highly related to the particular configuration type. Note that these classes only hold data and they are not expected to implement any behaviors in the future. However, it is expected that the SomeEnum enumeration will be extended and more "contexts" will be added at some point. Think of my config as immutable.



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

Selecting the ID from the 3th table

I will explain what I have in the first section and then what I want to get.

I have those 3 tables:

first: users

protected $fillable = [
   'name', 'email', 'password',
];

the pivot table: user_to_role

protected $fillable = [
   'id', 'user_id', 'role_id'
];

and the third one: roles

protected $fillable = [
    'id', 'role_name', 
];

role_name is admin and client

When I login/register I want to show the view for the specific role of the user

but I don't really know how to do that in the controller, I have something like this but I know it's not good

public function index()
{
    if (Auth::user()->role_id==1) {
        // and something here which I don't know
        return view('homeadmin');
    }
}

I know I have to take the role id from the 3th table, make the connection with the pivot and then with the user but I don't really know how.



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

mmap virtual memory (HDD) and main memory (RAM) allocation

I'm working with mmap() function. I Confiused about something in mmap flags.

MAP_SHARED with fd → Usage To allocated virtual memory which uses Hard Drive (HDD) and physical memory (RAM) will not be used. I allocated 2 GB using this flag with fd and my RAM remained unused (what I expected).

MAP_PRIVATE|MAP_ANONYMOUS with (fd = -1) → Usage To allocated main memory, which is RAM. I allocated 2 GB using this flag and I filled it with something then I checked my RAM usage and yes, 2 GB in use ...

Now my point, first method (MAP_SHARED) uses virtual memory (HDD) and second method (MAP_PRIVATE|MAP_ANONYMOUS) uses main memory (RAM) so 100% the second method MUST be different in performance since RAM is too much faster than HDD ... am I right ? If I'm right, so why mmap function is called as a 'virtual memory allocation' function !!!??? By flag MAP_PRIVATE|MAP_ANONYMOUS allocates main memory (RAM) too !!!!!!!

If MAP_PRIVATE|MAP_ANONYMOUS does not guarantee to provide 'main memory (RAM)', what should I do to allocated memory from main memory (RAM) ?!

What I got from mmap, mmap checks if a private flag (MAP_PRIVATE|MAP_ANONYMOUS) is provided, checks for unused RAM space and provides memory from RAM (main memory), if there is available space on RAM and if there isn't, it uses virtual memory (HDD). Right !?

Update

I decide to put 2 tests. one with MAP_SHARED and one with MAP_PRIVATE|MAP_ANONYMOUS

test 1 Memory allocation based on a file (MAP_SHARED)

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>

int
main() {
    double time_spent = 0.0;
    int fd = open("/home/alireza/Documents/mem", O_CREAT|O_RDWR);
    ftruncate(fd, (4294967296));
    char * memory = mmap(NULL, (4294967296), PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
    if(memory == MAP_FAILED) {
        printf("(%d)", errno);
        exit(0);
    }
    write(0, "started ...\n", sizeof("started ...\n")-1);
    clock_t begin = clock();
    for (long i = 0; i < (4294967296); i++) {
        memory[i] = 'c';
    }
    clock_t end = clock();
    write(0, "done\n", sizeof("done\n")-1);
    time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
    printf("time (%f)\n", time_spent);
    exit(0);
}

Result (9 seconds (since it uses virtual memory (HDD)) !!!)

started ...
done
time (9.087634)

test 2 Memory allocation using RAM (MAP_PRIVATE|MAP_ANONYMOUS)

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>

int
main() {
    double time_spent = 0.0;
    char * memory = mmap(NULL, (4294967296), PROT_WRITE|PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
    if(memory == MAP_FAILED) {
        printf("(%d)", errno);
        exit(0);
    }
    write(0, "started ...\n", sizeof("started ...\n")-1);
    clock_t begin = clock();
    for (long i = 0; i < (4294967296); i++) {
        memory[i] = 'c';
    }
    clock_t end = clock();
    write(0, "done\n", sizeof("done\n")-1);
    time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
    printf("time (%f)\n", time_spent);
    exit(0);
}

Result (1 second)

started ...
done
time (1.405220)

So mmap is not just virtual memory allocation (HDD). it's main memory allocation too and it's decide it based on the flag ! so using MAP_PRIVATE|MAP_ANONYMOUS flag to use real memory (RAM) is completely different from using SHARED flag !



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

What's the proper syntax for calling a function with a string parameter in an HTML attribute?

I have a few buttons generated in this Javascript method, and one of them has onclick() handler where I need to pass a string as an input parameter.

function ShowButtons() {
  let $previewDiv = $("#ServicesPreview");
  $previewDiv.html("<button id='myBtn' onclick='CheckID('MYID')'></button>")
}

I can't enclose the string in single quotes because it produces this on the website, and I get the error "Unexpected end of input":

<button id="myBtn" onclick="CheckID(" MYID')'></button>

I've also tried no quotes, and I can't use double-quotes because that terminates the string being passed into the jQuery.html method. What's the proper syntax here?



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

Programming a feature on YouTube for class project

I'm currently enrolled at Flatiron School in New York in the data science bootcamp, which goes from June to September. Bootcamp culminates in a large capstone project of our choosing. I am an avid YouTube user and I like to think the AI that chooses songs based on past choices 'gets me'. I noticed a feature I wish existed and thought it might make a good final project for class.

I'm deep into a My Mix on my phone and I'm jamming out big time, when I suddenly think of a song I've gotta hear. I go to search for A Whole New World from Aladdin, find the perfect version, and select the video. Now My Mix that I was so far into, working and refining has been abandoned after listening to the hit classic from Aladdin. I have to start again at the beginning.

My proposed feature is: While listening to a My Mix a person can swipe down and search for a song they'd love to hear. They tap and hold on the version they want and the option screen appears with a new prompt asking –

Merge with current mix

simulation of screen with new option The user taps on this option and now A Whole New World is either placed next in the queue of My Mix or played instantaneously in place of the current My Mix song.

I'm not even sure if something like this is within the realm of possibilities, being that I don't work for google. I just thought it would make for a cool capstone project. Let me know either way when you get a moment.

Thanks, nate



from Recent Questions - Stack Overflow https://ift.tt/3y3rdWY
https://ift.tt/362XXUd

Minimum time to reach from city 1 to city N

There are a lot of graph problems that require some modification of the BFS algorithm. I just come across this problem. I thought of this question with just an extension of the standard BFS algorithm. The question states that:

We are given a country, having N cities and M bidirectional roads. Each city has a traffic light, showing only 2 colors i.e Green and Red. All the traffic lights switch their color from Green to Red or vice versa after every T seconds. We can cross a city only when the traffic light is green. Initially, all traffic light is green. In any city, if the traffic light is Red then we have to wait for its light to turn green. Time taken to travel any road is C. We have to find minimum time to reach City N from 1.

Note: graph doesn't contain a self-loop or multiple edges.

For example:

N=5,M=5,T=3,C=5

Edges are:

1 2,

1 3,

2 4,

1 4,

2 5.

Here minimum time to go from 1 to 5 is 11 through path 1 2 5.WE can reach city 2 in 5 secs. then wait for 1 second for the light to turn green and then 5 seconds to go to 5.

Can anyone share his approach toward this problem? whether it is a BFS problem or some other graph algorithm required too? Better to unsderstand if psedoucode will be there along with algorithm?



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

Add/remove users to/from AAD group in batches

What is the code to add users to AAD group or remove users from AAD group in batches in C#? (first find batch size and then add or remove users). Any sample code would be great.

UPDATE:

I added the following code:

        private HttpRequestMessage MakeRequest(AzureADUser user, Guid targetGroup)
        {
            return new HttpRequestMessage(HttpMethod.Patch, $"https://graph.microsoft.com/v1.0/groups/{targetGroup}")
            {
                Content = new StringContent(MakeAddRequestBody(user), System.Text.Encoding.UTF8, "application/json"),
            };
        }

        private static string MakeAddRequestBody(AzureADUser user)
        {
            JObject body = new JObject
            {
                ["members@odata.bind"] = JArray.FromObject($"https://graph.microsoft.com/v1.0/users/{user.ObjectId}")
            };
            return body.ToString(Newtonsoft.Json.Formatting.None);
        }

        public async Task AddUsersToGroup1(IEnumerable<AzureADUser> users, AzureADGroup targetGroup)
        {           
            try
            {                
                var batches = GetBatchRequest(users, targetGroup.ObjectId);
                foreach (var batchRequestContent in batches)
                {
                    var response = await _graphServiceClient
                        .Batch
                        .Request()
                        .WithMaxRetry(10)
                        .PostAsync(batchRequestContent);
                    var responses = await response.GetResponsesAsync();
                }
            }
            catch (Exception ex)
            {
            }
        }

On running this I get the following exception: Object serialized to String. JArray instance expected. What am I missing? Also, once I get the responses, I need to check if all of the response returned an 'OK' response or not similar to:

return responses.Any(x => x == ResponseCode.Error) ? ResponseCode.Error : ResponseCode.Ok;

How would I do that?



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

Is it Possible in python, to Pass Variables Within a List, by Reference, in an Argument? [duplicate]

I am trying to create a Neural Network class made up of Neuron objects wired together.

My Neuron class has

  1. Dendrites
    The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite. eg: neuron1.dendrites[2]=0.12 volts.
  2. Activation (Threshold) Potential The sum of all the dendrite potentials provides the neuron potential. If this potential exceeds the Threshold Potential, my Neuron will fire. There are other neurons connected to the axon of my neuron. The Axon of my Neuron connects to the Dendrites of other Neuron objects. Several Dendrites from other Neurons may connect to the Axon of my Neuron. They will all receive a fixed voltage (outputVoltage) when my Neuron fires. It fires in an All-or-Nothing manner.
  3. Firing state
    When the the Activation Potential is reached, the firing state = on (True)
  4. My Neuron class also has a setConnections() method. This method receives a python list of Dendrites. In this method, I wish to iterate through my internal list of external Dendrites and reset their voltage values. This is not working. I cannot figure out why and so seek assistance here.

I provide a stripped down version of my code below:

import threading

 
 class Neuron:
      def __init__(self, dendrites, activation_Pot=0.24):
      """
      Create a dendrites[] array.
      Each element of this array represents the voltage of that dendrite.
      We can then loop through the array to sum up the signal strength.  

      If the signal strength exceeds the Activation potential, then the all-or-nothing threshold has been breached and
      we can transmit our signal along the axon.
      """
      self.dendrites = [0]*dendrites
      self.InputPotential = 0  # This variable will store the sum of all the dendrite voltages.  It is being initialised here.
      self.activation_Pot = activation_Pot
      self.on = True
      self.off = False
      self.voltsOut = 0.12      # This constant dictates the potential of the axon when the neuron is firing.
      self.outputPotential = 0  # This variable  SETS the potential of the single axon when the threshold activation potential of the  neuron has been reached and the neuron is firing.
      self.firing = self.off
      self.axonConnections = []
      
      # Launch a thread to check on a timer the sum of all dendrite inputs and fire when output > Activation Potential.
      t1 = threading.Thread(target = self.start, args=[])
      t1.start()
      
      
      def fire(self):
          self.outputPotential = self.voltsOut
          self.firing = self.on
          print("Neuron is firing!")
          
          for outputDendrites in self.axonConnections:
              outputDendrites = self.outputPotential
              
      def stopFiring(self):
          self.outputPotential = 0
          self.firing = self.off
          print("Neuron has STOPPED firing!")
          
          
      def setActivation_Pot(self, activation_Pot):
          if (activation_Pot >= 0) and (activation_Pot <=1):
              self.activation_Pot = activation_Pot
          else:
              print("activation_Pot value needs to be between 0 and 1")
              print("activation_Pot has not been reset.")
              print("Please consider re-inputting a valid value.")        
              
              
      def getActivation_Pot(self):
          return self.activation_Pot
          
          
      def setAxonConnections(self, axonConnections):
          self.axonConnections = axonConnections
          
      def getAxonConnections(self):
          return self.axonConnections
      
      
      def start(self):
          while True:
              while True:
                  self.InputPotential = 0  
                  for dendrite in self.dendrites:
                      self.InputPotential+=dendrite
                      
                  if self.InputPotential >= self.activation_Pot:
                      self.fire()
                      break
              while True:
                  self.InputPotential = 0
                  for dendrite in self.dendrites:
                      self.InputPotential+=dendrite
                  
                  if self.InputPotential < self.activation_Pot:
                      self.stopFiring()
                      break

Here is the relevant code from the from the main.py script which is testing the Neuron class:

from neuron import Neuron

# Instantiate transmitting neurone...
n0 = Neuron(3, 0.36)

# Instantiate receiving neurones...
n1 = Neuron(3, 0.36)
n2 = Neuron(3, 0.36)
n3 = Neuron(3, 0.36)

# Make the connections: I do this by creating storing my external Dendrites into a list 
# and passing that list to the transmitting neuron for it to update the voltages 
# of each of these neurons.  BUT THESE LIST VARIABLES ARE NOT GETTING UPDATED...
axonConns = [n1.dendrites[0], n2.dendrites[1], n3.dendrites[2]]
n0.setAxonConnections(axonConns) # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED!!

n0.fire()  # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED by this fire() method!!

I hope that makes sense. In summary: I am passing a list of variables from my main.py script at the line n0.setAxonConnections(axonConns). The variables in this list are not getting updated by the neuron.fire() method of my Neuron class. Can someone please explain why? Forgive me, I am a python newbe!



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

Writing single SQL query satisfying two cases

After the comments received, I am rephrasing this question with required data.

Reference: SQL query to exclude some records from the output

Vertica analytical functions: https://www.vertica.com/blog/analytic-queries-vertica/

Table 1:

create table etl_group_membership
(
    group_item_id int not null,
    member_item_id int not null
);

INSERT INTO etl_group_membership (group_item_id, member_item_id) VALUES (335640, 117722);
INSERT INTO etl_group_membership (group_item_id, member_item_id) VALUES (335640, 104151);
INSERT INTO etl_group_membership (group_item_id, member_item_id) VALUES (335640, 5316);

Table 2:

create table v_poll_item
(
    device_item_id int not null,
    item_id int not null
    
);

INSERT INTO v_poll_item (device_item_id, item_id) VALUES (117722, 273215);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (117722, 117936);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (117722, 117873);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (117722, 123305);

INSERT INTO v_poll_item (device_item_id, item_id) VALUES (104151, 240006);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (104151, 240005);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (104151, 239415);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (104151, 239414);

INSERT INTO v_poll_item (device_item_id, item_id) VALUES (5316, 118310);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (5316, 130627);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (5316, 298564);
INSERT INTO v_poll_item (device_item_id, item_id) VALUES (5316, 118311);

Table 3: Note that im_utilization can be NULL as well

create table nrm_cpustats_rate
(
    item_id int not null,
    tstamp datetime not null,
    im_utilization float,
);

INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (273215, '2021-06-28 19:55:00.000000', 2);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (273215, '2021-06-27 23:35:00.000000', 24);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (273215, '2021-06-26 14:05:00.000000', 27);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (273215, '2021-06-25 09:05:00.000000', 29);

INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-28 19:30:00.000000', 17);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-28 19:15:00.000000', 35);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-28 19:05:00.000000', 50);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-27 05:45:00.000000', 89);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-25 09:20:00.000000', 37);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-25 09:10:00.000000', 51);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (117936, '2021-06-25 08:50:00.000000', 90);

INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118310, '2021-06-23 04:10:00.000000', 51);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118310, '2021-06-23 03:15:00.000000', 48);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118310, '2021-06-22 22:20:00.000000', 19);

INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-22 17:10:00.000000', 11);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-22 16:30:00.000000', 37);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-22 16:35:00.000000', 38);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-28 18:45:00.000000', 74);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-28 18:48:00.000000', 76);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (239414, '2021-06-28 18:50:00.000000', 77);

INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118311, '2021-06-28 00:40:00.000000', 29);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118311, '2021-06-23 22:30:00.000000', 37);
INSERT INTO nrm_cpustats_rate (item_id, tstamp, im_utilization) VALUES (118311, '2021-06-23 22:25:00.000000', 92);

To get the device items ids in a group:

SELECT member_item_id FROM etl_group_membership WHERE group_item_id = 335640;

From the list of device item ids retrieved, to get the list of item_ids:

SELECT item_id FROM v_poll_item WHERE device_item_id IN (<devices retrieved from previous query>);

Inputs:

  1. Two time ranges: yesterday until 7 days back (AND tstamp > '2021-06-22 00:00:00.000000'AND tstamp <= '2021-06-28 23:59:59.000000')
  2. Group id: 335640
  3. breach_threshold: 25
  4. Minimum number of breaches each day: 2

Expected output:

breached means im_utilization is >= 25

Pick only those records where count_of_breached in a given day >= 2 That is, records with item_id 273215 are excluded because even though the number of breaches (>= 25) are 2, there's only one each day

device_item_id  |  item_id  |  count_of_breach  |  date_when_breached  |  max_utilization  |  max_utilization_tstamp
=====================================================================================================================
117722          |  117936   |  2                |  2021-06-28          | 90                |  2021-06-25 08:50:00.000000
117722          |  117936   |  3                |  2021-06-25          | 90                |  2021-06-25 08:50:00.000000
5316            |  118310   |  2                |  2021-06-23          | 51                |  2021-06-23 04:10:00.000000
5316            |  118311   |  2                |  2021-06-23          | 92                |  2021-06-23 22:25:00.000000
104151          |  239414   |  2                |  2021-06-22          | 77                |  2021-06-28 18:50:00.000000
104151          |  239414   |  3                |  2021-06-28          | 77                |  2021-06-28 18:50:00.000000

Even if a single SQL query cannot be written to produce this output, can two optimized queries be suggested. @marcothesane pointed that even the query to get daily breaches can be written in a better way.



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

Typescript index error: looping through keys of typed object

I have an interface that's created as an extension of a couple of other interfaces from an external library:

interface LabeledProps extends TextProps, ComponentProps {
    id: string;
    count: number;
    ...
}

In another place in the code, I have an object of type LabeledProps and I would like to loop through all its properties:

function myFunc(props: LabeledProps):void {
    for (let key in props) {
        const val = props[key];  // <-- ERROR IS HERE
        // do other stuff
    }
}

The line const val = props[key] throws a typescript error (though the compiled code actually runs just fine):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'.

What is the right way (or ways) to accomplish this? Thanks!

(Note: I know I could add [key: string]: any to the interface definition and that will remove the error message, but I would like an actual fix, not just a hiding-the-error fix.)



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

Xamarin.iOS app crashing with error DYLD Library not loaded, mapped file has no cdhash, Code has to be at least ad-hoc signed

I am using Windows VS 2019 paired to my Mac. My Xamarin.iOS app has started crashing with this error in the Xcode device logs: DYLD Library not loaded mapped file has no cdhash, Code has to be at least ad-hoc signed.

Visual Studio reports that the app deployed successfully on the iPhone and it starts to open then crashes. This only happens when deploying the app in debug mode. I can deploy in release mode to my iPhone and app store connect and the app runs fine. But I need to be able to debug.

Also, after the app crashes on the phone Visual Studio is still running in debug. But when I stop it a dialog box error pops up that says "The debugger was unable to terminate one or more processes: Mono: The debugger is still attaching to the process or the process is not currently executing the type of code selected for debugging."

I contacted Apple developer technical support but they say they can't help because I'm using 3rd party tools (Visual Studio). This is all they would tell me, "The immediate cause of this error is very clear: Some part of your program is not signed and thus iOS refuses to load it... Because the third-party tool is creating the project that you’re asking Xcode to sign. Specifically, this message: DYLD Library not loaded mapped file has no cdhash means that the code simply wasn’t signed. If you were working with a normal Xcode project you’d never get into this situation."

I have uninstalled and reinstalled all of my Apple certificates in Keychain and made sure the trust setting is set to Use System Defaults. I have revoked and removed all my certificates, identities, and profile in Apple Developer and re-created them. sand I have upgraded Xcode to 12.5 and Visual Studio to 16.10.1.

Here is the error from the Xcode device log:

Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Description: DYLD, Library not loaded: @rpath/libGT.Partners.Phone_Order_Entry.iOS.exe.dylib | Referenced from: /private/var/containers/Bundle/Application/2F1480CA-1262-4922-B33E-91E0DFC6DFDC/GT.Partners.Phone_Order_Entry.iOS.app/GT.Partners.Phone_Order_Entry.iOS | Reason: no suitable image found. Did find: | /private/var/containers/Bundle/Application/2F1480CA-1262-4922-B33E-91E0DFC6DFDC/GT.Partners.Phone_Order_Entry.iOS.app/libGT.Partners.Phone_Order_Entry.iOS.exe.dylib: code signature in (/private/var/containers/Bundle/Application/2F1480CA-1262-4922-B33E-91E0DFC6DFDC/GT.Partners.Phone_Order_Entry.iOS.app/libGT.Partners.Phone_Order_Entry.iOS.exe.dylib) not valid for use in process using Library Validation: mapped file has no cdhash, completely unsigned? Code has to be at least ad-hoc signed. | /private/var/containers/Bundle/Application/2F1480CA-1262-4922-B33E-91E0DFC6DFDC/GT.Partners.Phone_Order_Entry.iOS.app/libGT.Partners.Phone_Order_Entry.iOS.exe.dylib: stat() failed with errno=1

Has anyone encountered and fixed this? Please help!



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

2021-06-29

Combining multiple rows into one based on timestamps with varying number of rows

I am using a barcode scanner to input data for production runs and downtime. The idea is to scan the job number in, start the job, and scan the job number out when finished. Within some of the jobs there may be downtime such as equipment malfunction or a scheduled break. These will also have barcodes for the operator to scan.

I want there to be a single row where the part number is scanned in, any downtime codes scanned before the end of the current job are captured in the row as well, and the scan out completes the entire process and drops to the next row to await the start of the next job.

So far I am able to scan the barcode to show the job number or downtime code and the time it is scanned. Scan code is shown in column A, Time is shown in Column B.



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

SQL Server Alert System: 'Severity 023' and 'Severity 020' with Transactional Replication

This is not so much a question just a post about the resolution I came to since and I was unable to find anything online about it.

I had a SQL Server host failure, had to migrate to a new host and bring over the SQL Server VM from backups. Once the SQL Server was back online, I restored each database from a backup drive that was still working properly. Shortly after it was all brought back online, I started receiving the errors below:

SQL Server Alert System: 'Severity 023' DESCRIPTION: "An error occurred while processing the log for database 'DBName'. If possible, restore from backup. If a backup is not available, it might be necessary to rebuild the log."

SQL Server Alert System: 'Severity 020' DESCRIPTION: A system assertion check has failed. Check the SQL Server error log for details. Typically, an assertion failure is caused by a software bug or data corruption. To check for database corruption, consider running DBCC CHECKDB. If you agreed to send dumps to Microsoft during setup, a mini dump will be sent to Microsoft. An update might be available from Microsoft in the latest Service Pack or in a QFE from Technical Support.

I found all sorts of posts online saying to rebuild my log after setting my DB to emergency mode or restoring from backup. The odd thing was the DB was still up and running properly with no issues on our website.

Come to find out that all I had to do was fix my replication publications. Since the replication was not working, the Log file was increasing in size and SQL Server could not access the log file for whatever it was trying to do.

So I just right clicked on each publication that was failing > Generate Scripts > click on Drop and then Create so I have both sets of scripts. Now my errors are gone. Wish it was something I would have looked at to begin with!



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

Connection refused by iOS when using UnityWebRequest

It works fine in the Unity Editor but in iOS the app gives errors in the logs by saying what I post below. It can't find the file. I have a Json file in StreamingAssets in Unity and then it is copied to persistentDataPath.

In Xcode for the info.plist I added "App Transport Security Settings" & "Allows Arbitrary Loads" and "Allow Local Networking". If not it blocks the connection.

This is the error I get in Xcode.

2021-06-28 11:50:47.655068-0400 Jumper[39664:10886549] [connection] nw_socket_handle_socket_event [C2.1:2] Socket SO_ERROR [61: Connection refused] 2021-06-28 11:50:47.664973-0400 Jumper[39664:10886549] [connection] nw_socket_handle_socket_event [C2.2:2] Socket SO_ERROR [61: Connection refused] 2021-06-28 11:50:47.665697-0400 Jumper[39664:10886549] Connection 2: received failure notification 2021-06-28 11:50:47.665793-0400 Jumper[39664:10886549] Connection 2: failed to connect 1:61, reason -1 2021-06-28 11:50:47.666259-0400 Jumper[39664:10886549] Connection 2: encountered error(1:61) 2021-06-28 11:50:47.668734-0400 Jumper[39664:10886548] Task <23601751-EACC-40FF-81CC-C5F6B6CDC4F6>.<2> HTTP load failed, 0/0 bytes (error code: -1004 [1:61]) 2021-06-28 11:50:47.677576-0400 Jumper[39664:10886545] Task <23601751-EACC-40FF-81CC-C5F6B6CDC4F6>.<2> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x2811a8f00 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <23601751-EACC-40FF-81CC-C5F6B6CDC4F6>.<2>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <23601751-EACC-40FF-81CC-C5F6B6CDC4F6>.<2>" ), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=http://localhost/private/var/containers/Bundle/Application/3C4E9065-AC69-46EA-98E6-0265B0963F23/Jumper.app/Data/Raw/language_data.json, NSErrorFailingURLKey=http://localhost/private/var/containers/Bundle/Application/3C4E9065-AC69-46EA-98E6-0265B0963F23/Jumper.app/Data/Raw/language_data.json, _kCFStreamErrorDomainKey=1} Uploading Crash Report FileNotFoundException: Could not find file "/var/mobile/Containers/Data/Application/455E9171-A4AD-48C8-9400-0BF577E39324/Documents/language_data.json" at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x00000] in <00000000000000000000000000000000>:0 at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize, System.Boolean checkHost) [0x00000] in <00000000000000000000000000000000>:0 at SimpleLocalizationSystem.Language.HasValue (System.String key) [0x00000] in <00000000000000000000000000000000>:0

Here is the code that I use.

private static void Request(string file)
{
    var loadingRequest = UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath, file));
    loadingRequest.SendWebRequest();
    while (!loadingRequest.isDone)
    {
        if (loadingRequest.isNetworkError || loadingRequest.isHttpError)
        {
            break;
        }
    }
    if (loadingRequest.isNetworkError || loadingRequest.isHttpError)
    {
        // Some error happened.
    }
    else
    {
        File.WriteAllBytes(Path.Combine(Application.persistentDataPath, file), loadingRequest.downloadHandler.data);
    }
}

// Loads key from "StreamingAssets/language_data.json" file.
public static string LoadJson(string key)
{
    Request(jsonFileName);
    var jsonPath = Path.Combine(Application.persistentDataPath, jsonFileName);
    using (StreamReader r = new StreamReader(jsonPath))
    {
        var N = JSON.Parse(r.ReadToEnd());
        string result = N[GetLanguage()][key];
        return result;
    }
}


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

change opacity and animated that with react js

i started a simple project with react.in my project i have a paragraph and when mouse hover on paragraph (mouse enter event) a square appears under the paragraph and when hover out from paragraph(mouse leave event) that square disapear.but this occure so fast so i want changing this smoothly and i want use opacity and change that from 0 to 1 and reverse when my events occure.but I do not know what to do to change the opacity with animation in react.

this is my appjs

import './index.css';
import React, {useState} from "react";

function App() {
    const [isShowSquare, setIsShowSquare] = useState(false);
    const showSquare = () => {
        setIsShowSquare(true);
    }
    const hideSquare = () => {
        setIsShowSquare(false);
    }
    return (
        <div>
            <p onMouseEnter={showSquare} onMouseLeave={hideSquare} style=>Hover Me</p>

            {isShowSquare ?
                <div className='square'>
                </div>
                : null
            }

        </div>

    );
}

export default App;

and this is my index.css

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.square{
  width: 50px;
  height: 50px;
  background-color: #61dafb;
}


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

Typescript union types working like intersection types

I am having trouble distinguishing the difference between union and intersection types in TS even tho the difference should be very clear. Take this example:

   type CustomType1 = {
      customProp1: number;
    };
    
    type CustomType2 = {
      customProp2: number;
    };
    
    type UnionType = CustomType1 | CustomType2;
    
    const e1:  UnionType = {
      customProp1: 4,
      customProp2: 5,
    };

Note on how I created a union type which in theory should make a object that can only have one or the other type. This is not the case because the compiler nor my ide display any errors even tho the object I define has both of the properties from the two types which should be possible only after you merge the two types with the intersection & symbol. Is this the case?



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

pip broken, can't use most of pip commands (on windows)

So I was working with python, coding and installing packages, everything was going ok, but then everything with pip stoped working, and every times the cmd prompt me :

Traceback (most recent call last):
  File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Python39\Scripts\pip.exe\__main__.py", line 7, in <module>
  File "c:\python39\lib\site-packages\pip\_internal\cli\main.py", line 69, in main
    command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  File "c:\python39\lib\site-packages\pip\_internal\commands\__init__.py", line 91, in create_command
    module = importlib.import_module(module_path)
  File "c:\python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 855, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "c:\python39\lib\site-packages\pip\_internal\commands\list.py", line 9, in <module>
    from pip._internal.cli.req_command import IndexGroupCommand
  File "c:\python39\lib\site-packages\pip\_internal\cli\req_command.py", line 20, in <module>
    from pip._internal.index.collector import LinkCollector
  File "c:\python39\lib\site-packages\pip\_internal\index\collector.py", line 5, in <module>
    import cgi
  File "c:\python39\lib\cgi.py", line 41, in <module>
    import html
ModuleNotFoundError: No module named 'html'

I never run into those kind of errors. BTW pip -V is working, and when I try to run a programme using python with the already installed package and it still works fine.

I tried to reinstall python partially after restarting my pc, and nothing with pip has changed



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

React Rollup build with styled-components namespace issue

I created an "UI Lib" to use in other projects with ReactJS + TS + styled-components and Rollup and I'm facing some problems with conflicted classNames. I know that styled-components provides a plugin to create namespace to classNames hashes, but its not working as they should. If I run Storybook in my project, the namespace works, but when I build this UI and use in other projects, don't. Its the first time I use Rollup, so I don't know if I'm missing something here. My files:

Package.json

  "name": "@team/ds-react-ui-lib",
  "version": "0.1.11",
  "description": "React UI library of B2W Design System",
  "repository": "git@gitlab.internal.b2w.io:team/fluxo/websupply/ds-react-ui-lib.git",
  "author": "Lucas Cardoso<lucas.casantos@b2wdigital.com>, Felipe Jardim<felipe.evangelista@b2wdigital.com>",
  "license": "MIT",
  "main": "dist/index.js",
  "module": "dist/index.esm.js",
  "types": "dist/index.d.ts",
  "devDependencies": {
    "@babel/cli": "^7.14.5",
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "@rollup/plugin-babel": "^5.3.0",
    "@rollup/plugin-commonjs": "^19.0.0",
    "@rollup/plugin-image": "^2.0.6",
    "@rollup/plugin-node-resolve": "^13.0.0",
    "@storybook/addon-essentials": "6.2.3",
    "@storybook/addon-info": "^5.3.19",
    "@storybook/addons": "^6.0.12",
    "@storybook/react": "^6.0.12",
    "@storybook/theming": "^6.0.12",
    "@types/react": "^17.0.9",
    "@types/react-icons": "^3.0.0",
    "@types/styled-components": "^5.1.10",
    "babel-loader": "^8.2.2",
    "babel-plugin-styled-components": "^1.12.0",
    "postcss": "^8.3.0",
    "rollup": "^2.51.1",
    "rollup-plugin-babel": "^4.4.0",
    "rollup-plugin-image-files": "^1.4.2",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-postcss": "^4.0.0",
    "rollup-plugin-typescript2": "^0.30.0",
    "storybook-addon-styled-component-theme": "^2.0.0",
    "typescript": "^4.2.4"
  },
  "dependencies": {
    "react-icons": "^4.2.0",
    "styled-components": "^5.3.0"
  },
  "peerDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "scripts": {
    "build": "rollup -c",
    "build-storybook": "build-storybook",
    "serve": "node server.js",
    "storybook": "start-storybook"
  },
  "publishConfig": {
    "team:registry": "http://gitlab.internal.b2w.io/api/v4/projects/7093/packages/npm/",
    "directory": "dist"
  },
  "files": [
    "dist"
  ]
}

Babel.config.js

  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "namespace": "ds"
      }
    ]
  ]
}

Rollup.config.js

import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import image from '@rollup/plugin-image';
import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import postcss from 'rollup-plugin-postcss';
const packageJson = require('./package.json');

export default {
  input: 'src/index.ts',
  output: [
    {
      file: packageJson.main,
      format: 'cjs',
      sourcemap: true,
    },
    {
      file: packageJson.module,
      format: 'esm',
      sourcemap: true,
    },
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    commonjs(),
    image(),
    typescript({ useTsconfigDeclarationDir: true }),
    postcss({
      extensions: ['.css'],
    }),
    babel({
      exclude: 'node_modules/**',
      plugins: ['babel-plugin-styled-components'],
    }),
  ],
};


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

How can I have check constraint in django which check two fields of related models?

from django.db import models
from djago.db.models import F, Q

class(models.Model):
    order_date = models.DateField()
    
class OrderLine(models.Model):
    order = models.ForeignKeyField(Order)
    loading_date = models.DateField()
    
    class Meta:

        constraints = [
        models.CheckConstraint(check=Q(loading_date__gte=F("order__order_date")), name="disallow_backdated_loading")

I want to make sure always orderline loading_date is higher than orderdate



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

Selenium Colab of Google

I got this in Colab. I did the installation:

# !pip install selenium
# !apt-get update # to update ubuntu to correctly run apt install
# !apt install chromium-chromedriver
# !cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
wd.get("https://ca.yahoo.com")

And I got the error below :

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:12: DeprecationWarning: use options instead of chrome_options
  if sys.path[0] == '':

So I changed the code by removing the chrome from chrome_options:

# !pip install selenium
# !apt-get update # to update ubuntu to correctly run apt install
# !apt install chromium-chromedriver
# !cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',options=options)
wd.get("https://ca.yahoo.com")

Then when I run it again, then I got nothing. I expected a browser will be fired up and load Yahoo. But ... nothing.. 😭

Please help. Thank you so much in advance.

Cheers



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

Android build RP1A.200720.012 T500XXU3BUF2 has wedged @UIThreadTest

Our Samsung Galaxy Tab7 worked for many months. It ran tests from the Android-Studio editor, and from the adb command line. Then right around June 2 it requested a software update, and I absentmindedly acknowledged the button.

After it updated, Espresso tests worked, but tests using @UIThreadTest end prematurely with 'Tests Cancelled\n0 passed.'

So we got a new Samsung Galaxy Tab7, and I configured it for development, and it mostly worked correctly. This time, the adb fails on random assertions, while when the editor invokes the same tests, they pass.

Then I allowed the tablet to update to the latest build, and the @UIThreadTest problem came back. I will now introduce a third tablet, this time NOT allow it to update, and get back to work.

I am aware that real programmers don't write automated tests, but how do I appeal to Android? The AndroidStudio button "Submit Feedback" is apparently for bugs in AndroidStudio, not Android.



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

Oracle APEX: IG error: Uncaught TypeError: Cannot read property 'outerHeight' of null

I have an interactive grid on my page and I need to programmatically change the report from default to a named report. I am using the following javascript code to get report ID by report name and then change the report on my grid:

 try {
    v_array.forEach(function(element) {
        if (element.name == v_report_name) { 
            v_value = element.id; 
            throw BreakException; 
        }
    });
} catch (e) {
    if (e !== BreakException) throw e;
}

 apex.region("MY_IG").call("getActions").set("change-report", v_value);

The report gets changed yet there is an error on the page:

Uncaught TypeError: Cannot read property 'outerHeight' of null

If I comment out this line, error disappears:

     apex.region("MY_IG").call("getActions").set("change-report", v_value);

Can't figure out what is going on. This started happening right after the upgrade



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

Python & Time Series Cleaning - Removing regions/chunks of huge timeseries that contain no useful data

Data: 20 hrs of triaxial accelerometer data. Sampled at 10khz. 3 Billion Points. 40 Gb of CSV spread across 20 files to reduce memory needed to inspect a given chunk of data.

Accelerometer Example

Problem: There are large regions of low/no-activity that I don't care about which make up the greater majority of the data points. There is no reason these regions need to be preserved. This slows down all the processing. Plotting is just the beginning, I need to do signals processing and complex transformations on the data which is very computationally intensive. Also these files are unreasonably large and I will be doing this sort of testing many times.

Data is being stored in a four-column Dask dataframe to be plotted using holoviews with a matplotlib extension (and perhaps an interactive Bokeh dashboard once data size can be reduced). I want to reduce the amount of data without destroying regions of interest. The easiest way to do this is to remove extended periods of random noise between regions of activity.

What I've Tried:

  • Manually editing the data and removing regions by locating their indices on charts. This takes forever and is not something I want to repeat the next time I need to process this sort of data.
  • Filtering using various signal processing methods. This significantly changes the regions of interest and destroys information.

Ideas for Solving:

  • Iterating over the rows and creating boolean columns which indicate if the abs values have exceeded a threshold. Then deleting rows of consecutive 0's (below threshold) which are more rows than some chunk length N up to the next "1". I would make N sufficiently long to prevent destroying points in the regions of interest.
  • Instead of deleting regions implementing something like Ramer–Douglas–Peucker algorithm. But this would take an inordinate amount to time to iterate over the data. I also don't know who I would preserve the timestamp column as (I believe) the data would need to be transformed into series.

I'm most certainly not a computer scientist and I feel as though this must be a solved problem. I'm not aware of a solution and much searching has yielded nothing that would work for tabular time series.

And while it would be great to do this in python and just make it a part of my process before saving the graphs (which take about 5-10 minutes to plot and have a ton of wasted space) I am open to any free solutions, scripts, or programs which would let me edit out the regions automatically or manually with a UI (I'm almost imagining a video editor style UI where I can drag select regions.)



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

Why do the inline-blocks jump to a new line? Is it to do with previous margins?

div {
  width: calc(100vh/6);
  height: calc(100vh/6);
  background: #fdc57b;
  display: inline-block;
}

body {
  background: #62374e;
}

#a {
  margin-left: calc(14vh);
  margin-top: calc(100vh/7.2);
}

#b {
  margin-left: calc(49vw);
}

#c {
  margin-left: calc(14vh);
  margin-top: calc(161vh/5);
}

#d {
  background: #00FF22;
  margin-left: 79.3vh;
  /*This value*/
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>

I have just started learning CSS and was playing around. On CSS battle challenge 1, part 2: Carrom, I noticed something odd: when I change 'This Value' to 79.3 the <div> moves unexpectedly from 4 squares in quadrants with bottom right closer to right edge
to
enter image description here

Why is this? Why doesn't it move off the right edge of the body: there are no div blocks after that define its position?



from Recent Questions - Stack Overflow https://ift.tt/3juOyg2
https://ift.tt/3y5y4iu

Snowflake SQL How to get only values from the last full week

I'm trying to build a query that would get me only the results with a created date from the last full week. So, for example, if today is Monday 2021-06-28, I only want the results from Monday 2021-06-21 to Sunday 2021-06-27.

I tried with this, but this is the last 7 days, without considering week end or start.

WHERE (CREATED_AT::DATE BETWEEN (CURRENT_DATE::DATE - INTERVAL '1 WEEK') AND CURRENT_DATE::DATE)

I also tried working with this function:

last_day(CREATED_AT::DATE, 'week') as "LAST_DAY_OF_WEEK"

and then trying to substract 7 days, but I think my use of these functions is incorrect.



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

'service' is not recognized as an internal or external command, operable program or batch file

I have installed XAMPP 7.4 and defined mysql as Environment Variable on my system, and then tried to run service mysqld restart on CMD but I got this:

F:\xampp\mysql\bin>service mysqld restart
'service' is not recognized as an internal or external command,
operable program or batch file.

So what is going wrong here? How can I run this command properly?

I would really appreciate any idea or suggestion from you guys...

Thanks in advance.



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

Keyboard input with timeout in while-loop [duplicate]

Code:

answer = None

def check():
    time.sleep(2)
    if answer != None:
        return
    print("Too Slow")

while True:
    current_kw = 0
    money = 100000  #100.000
    profit= current_kw * 300
    money += profit
    Thread(target = check).start()
    x = input('x: \n')
    ...

What I would like to achieve and what doesn't work:

Skip only works once instead of always

What I've tried:

See Code and Python 3 Timed Input



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

assembly language program to enter and sort numbers [closed]

i'm writing assembly language program that allows a user to enter 6 numbers in any order then display the largest and smallest entered number, and the order from small to large and then large to small. I've included the initial code I wrote

START: 
mov ax,data
mov ds,ax
mov BX,LEN-1
MOV CX,BX
UP1: MOV BX,CX
LEA SI,X
UP: MOV AX,[SI]
MOV DX,[SI+2]
CMP AX,DX
JB DOWN/JA DOWN
MOV [SI],DX
MOV [SI+2],AX
DOWN: INC SI
INC SI
DEC BX
JNZ UP
DEC CX
JNZ UP1
MOV AH,4CH
INT 21H
CODE ENDS
END START


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

How can I make a LEFT JOIN, but with rows separed from its relations in MySQL?

I need to get all rows that are in the table A, but joining with the table B (basically a LEFT JOIN), but also, I need to get the A table row itself, for example, with these tables:

Table A:

id name
1 Random name
2 Random name #2

Table B:

id parent_id location
1 2 Location #1
2 2 Location #2

With this query:

SELECT * FROM A
LEFT JOIN B
ON A.id = B.parent_id;

I get something like this:

id name id parent_id location
1 Random name NULL NULL NULL
2 Random name #2 1 2 Location #1
2 Random name #2 2 2 Location #2

But I want to get something like this:

id name id parent_id location
1 Random name NULL NULL NULL
2 Random name #2 NULL NULL NULL
2 Random name #2 1 2 Location #1
2 Random name #2 2 2 Location #2

As you can see, there is a row by itself of "Random name #2" separated from its joins, how can I do that?

The main idea is that there are an ads table (the table A), but also, there are a subads table (the table B) with little variations of the ads table, and I need to show all ads and subads in a unique query.

Tanks a lot!



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

How can we store every Object passed through a on-click event in an array after each time the button is clicked?

I am trying to Pass a button in a map function, And then trying to Obtain all the values in an array which I get after every on-click event function. The map function looks like this

  {Data.map((d, i) => {
      return (
       <div key={i} >
  <table>
  <tr>
    <td className="date">{d.Date}</td>
    <td className="time">{d.Time}</td>
    <td className="availability" >{d.Availabilty}</td>
    <td><button value={JSON.stringify(d)} onClick={(e)=>{
      decNum(e);
      }}>Book Now</button></td>
  </tr>

</table>
</div>
      )
})}

The onclick function goes like this

const decNum=(e)=>{
  var i =0
    cartData[i] = e.target.value
    i = i+1
    console.log(cartData)
    console.log( e.target.value)
  }

I am getting the value for the particular button that i am clicking on and nothing else. And I want to get all the previous data That I have clicked on before.

thanks in advance

for reference The data Passes in the map function goes like this

const Data =[
    {
   "Date":"Thu Jul 06 2021" ,
   "Time": "01:00 PM PST -03:00 PM PST",
   "Availabilty":"9 seats available",
  
  },
  {
   "Date":"Fri Jul 07 2021" ,
   "Time":"01:00 PM PST -03:00 PM PST",
   "Availabilty":"7 seats available",
  },
  {
   "Date":"Sat Jul 08 2021" ,
   "Time": "01:00 PM PST -03:00 PM PST",
   "Availabilty":"10 seats available",
  },
  {
   "Date":"Sun Jul 09 2021" ,
   "Time": "01:00 PM PST -03:00 PM PST",
   "Availabilty":"3 seats available",
  },
  {
   "Date":"Mon Jul 10 2021" ,
   "Time": "01:00 PM PST -03:00 PM PST",
   "Availabilty":"14 seats available",
  },
  
  {
   "Date":"Wed Jul 12 2021" ,
   "Time":"01:00 PM PST -03:00 PM PST",
   "Availabilty": "12 seats available",
  },
  {
   "Date":"Thu Jul 13 2021" ,
   "Time":"01:00 PM PST -03:00 PM PST",
   "Availabilty": "15 seats available",
  },
  {
   "Date":"Fri Jul 14 2021" ,
   "Time":"01:00 PM PST -03:00 PM PST",
   "Availabilty":"8 seats available",
  },
  {
   "Date":"Sat Jul 15 2021" ,
   "Time":"01:00 PM PST -03:00 PM PST",
   "Availabilty":"1 seats available"
  } 
  ]


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

Terraform Azure App Service Plan Error - The parameter SKU.Name has an invalid value

Module declaration

resource "azurerm_app_service_plan" "appserviceplan" {
  name                = var.name
  location            = var.location
  resource_group_name = var.resource_group_name
  kind                = var.kind
  reserved            = var.reserved
  is_xenon            = var.is_xenon

  sku {
    # name = var.sku_name
    tier = var.sku_tier
    size = var.sku_tier
  }
}

Calling the above module like so (in main.tf) ...

module "appserviceplan1" {
  source = "../modules/app_service_plan"

  name                = "${var.project_name}-${var.environment}-appserviceplan"
  location            = var.location
  resource_group_name = var.resource_group_name
  kind                = var.asp_kind
  reserved            = var.asp_reserved
  is_xenon            = var.asp_is_xenon
  # sku_name            = var.asp_sku_name
  sku_tier = var.asp_sku_tier
  sku_size = var.asp_sku_tier
}

Input variable assignment (in main.auto.tfvars):

# Variable assignment for App Service Plan
asp_kind = "xenon"
# Recommended value is false
# Ref: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/app_service_plan
asp_reserved = false
asp_is_xenon = true
# asp_sku_name = "P3"
asp_sku_tier = "PremiumV3"
asp_sku_size = "P3v3"

Getting the following error with terraform apply:

Error: Error creating/updating App Service Plan "xyz-sandbox-appserviceplan" (Resource Group "abc-sandbox-xyz-cc-rg"): web.AppServicePlansClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: Code="BadRequest" Message="The parameter SKU.Name has an invalid value." Details=[{"Message":"The parameter SKU.Name has an invalid value."},{"Code":"BadRequest"},{"ErrorEntity":{"Code":"BadRequest","Message":"The parameter SKU.Name has an invalid value.","MessageTemplate":"The parameter {0} has an invalid value.","Parameters":["SKU.Name"]}}]

I have been spinning on this for hours now. Any help would be greatly appreciated!



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

How do I create a closure that takes either u32 or &str and returns u32 or usize respectively?

This is from chapter 13.1 of the Rust book, where we use closures, memoization and generic types. In this example I can already pass two different closures to the struct (Cacher) and get the values accordingly, but they have two be two different instances of the struct in order to handle the types correctly.

Can I build a generic type so the same instance of the struct can handle receiving either type and give me the value accordingly? Either the same u32 I passed, or the length of the &str I passed.

use std::collections::HashMap;
use std::thread;
use std::time::Duration;

fn main() {
    let simulated_user_specified_value = 10;
    let simulated_random_number = 7;

    generate_workout(simulated_user_specified_value, simulated_random_number);
}

fn generate_workout(intensity: u32, random_number: u32) {
    let mut expensive_result = Cacher::new(|num| {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num
    });

    if intensity < 25 {
        println!("Today, do {} pushups!", expensive_result.value(intensity));
        println!("Next, do {} situps!", expensive_result.value(intensity));
    } else {
        if random_number == 3 {
            println!("Take a break today! Remember to stay hydrated!");
        } else {
            println!(
                "Today, run for {} minutes!",
                expensive_result.value(intensity)
            );
        }
    }
}

struct Cacher<T, U, V>
where
    T: Fn(U) -> V,
{
    calculation: T,
    values: HashMap<U, Option<V>>,
}

impl<T, U, V> Cacher<T, U, V>
// Generic T is the function where U and V are the parameter and return value respectively for said function.
where
    T: Fn(U) -> V,
    U: std::cmp::Eq // U must have 3 trait bounds, Eq, Hash, and Copy.
        + std::hash::Hash
        + Copy,
    V: Copy, // V must have trait bound Copy.
{
    fn new(calculation: T) -> Cacher<T, U, V> {
        Cacher {
            calculation,
            values: HashMap::new(),
        }
    }

    fn value(&mut self, arg: U) -> V {
        match self.values.get(&arg) {
            // Get the value for the key in the hashmap.
            Some(v) => v.unwrap(), // get the value in the option stored in the hashmap.
            None => {
                let v = (self.calculation)(arg);
                self.values.insert(arg, Some(v)); // Put the key/value pair into the hashmap.
                v
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Cacher;
    #[test]
    fn call_with_different_values() {
        let mut c = Cacher::new(|a| a);

        let _v1 = c.value(1);
        let v2 = c.value(2);

        assert_eq!(v2, 2);
    }

    #[test]
    fn call_with_string_usize() {
        let mut c = Cacher::new(|a: &str| a.len());

        let v1 = c.value("Three");

        assert_eq!(v1, 5);
    }
}

I tried building structs for the value field of the struct and then implementing a trait of that would group them:

struct CStr<'a> {
    value: &'a str,
}

struct CInt {
    value: u32,
}

trait CValue {
    fn get<W: Copy + Eq>(&self) -> W;
}

impl<'a> CValue for CStr<'a> {
    fn get<W: Copy + Eq>(&self) -> W {
        self.value.len()
    }
}

So this test would pass

#[test]
fn call_with_different_values() {
    let mut c = Cacher::new(|a| a.get());

    let v1 = c.value(1);
    let v2 = c.value("two");

    assert_eq!(v2, 3);
}

but I am stuck here:

impl<'a> CValue for CStr<'a> {
    fn get<W: Copy + Eq>(&self) -> W {
        self.value.len() // here
    }
}

with the error:

[rustc E0308] [E] mismatched types expected type parameter `W` found type `usize`


from Recent Questions - Stack Overflow https://ift.tt/3606NC8
https://ift.tt/eA8V8J

Generating multilevel associative array using php loop

Trying to generate array for json output from a nested php loop, any suggestions on how to accomplish this?

Here is the current code am I using

$v_id=0;
$x=0;
$item[] = array();
foreach ($abc as $vm) {
    foreach ($vm->activity as $record) {

        $item['instruction']              = $record->step;
        $item['id']              = $x;
        $id++;

    } 
    $v_id++;
}

However each loop of the main loop statement is overrating the previous entries

This is the desired output

steps": [
        {
            "v_id": 0,
            "instruction_steps": [
                {
                    "id": 0,
                    "instruction": "<p>Select something </p>",
                  
                   
                {
                    "id": 1,
                    "instruction": "<p>Do something</p>",
                   
                }
            ]
        },


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

Why won't my template update with it being bound to a computed property?

I am facing an issue where I have some template HTML in a component that relies on the computed getter of a Vuex method. As you can see in the template, I am simply trying to show the output of the computed property in a <p> tag with .

As I update the state with the UPDATE_EXERCISE_SETS mutation, I can see in the Vue devtools that the state is updated correctly, but the change is not reflected in the <p> </p> portion.

Template HTML:

<template>
...
<v-text-field
   v-model="getNumSets"
   placeholder="S"
   type="number"
   outlined
   dense
></v-text-field>
<p></p>
...
</template>

Component Logic:

<script>
...
computed: {
   getNumSets: {
      get() {
         var numSets = this.$store.getters['designer/getNumSetsForExercise']({id: this.id, parent: this.parent})
         return numSets
      },
      set(value) {  // This correctly updates the state as seen in the Vue DevTools
        this.$store.commit('designer/UPDATE_EXERCISE_SETS', {
                    id: this.exerciseId,
                    parentName: this.parent,
                    numSets: parseInt(value),
                    date: this.date
                })
      }

}
...
</script>

Vuex Store Logic:

...
state: {
  designerBucket: []
},
getters: {
  getNumSetsForExercise: (state) => (payload) => {
    var numSets = 0
    for (var i = 0; i < state.designerBucket.length; i++) {
      if (state.designerBucket[i].id == payload.id) {
        numSets = state.designerBucket[i].numSets
      }
    }
    return numSets
  }
},
mutations: {
  UPDATE_EXERCISE_SETS(state, payload) {
    state.designerBucket.forEach(exercise => {
       if (exercise.id == payload.id) {
          exercise.numSets = payload.numSets
       }
    })
   }
}

Any insight is very appreciated!

P.S. I have also tried using a for (var i=0...) loop, looping over the indices and then using Vue.set() to set the value. This did update the value in the store as well, but the computed property is still not updating the template.



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

2021-06-28

org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node: main ()V:

i am learning kotlin.

in the following code if give double value to ANOTHER_CONSTANT then i get this error. for other types it works just fine. what could be the reason.

const val ANOTHER_CONSTANT = 833.1 // not compiling
// const val ANOTHER_CONSTANT = 833.1f // float works, and other types also work

fun main() {
    println("ANOTHER_CONSTANT ${ANOTHER_CONSTANT} :: ${ANOTHER_CONSTANT::class}")
}

error:

org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node:
main ()V:
   L0
    LINENUMBER 7 L0
    NOP
    GETSTATIC java/lang/Double.TYPE : Ljava/lang/Class;
    INVOKESTATIC kotlin/jvm/internal/Reflection.getOrCreateKotlinClass (Ljava/lang/Class;)Lkotlin/reflect/KClass;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.stringPlus (Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;
    ASTORE 0
    NOP
   L1
    ICONST_0
    ISTORE 1
   L2
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    ALOAD 0
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
   L3
    NOP
    GOTO L4
   L4
    LINENUMBER 8 L4
    RETURN
   L5
    MAXSTACK = 3
    MAXLOCALS = 2

File is unknown
The root cause org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException was thrown at: org.jetbrains.org.objectweb.asm.tree.analysis.Analyzer.analyze(Analyzer.java:295)
    at org.jetbrains.kotlin.codegen.TransformationMethodVisitor.visitEnd(TransformationMethodVisitor.kt:92)
    at org.jetbrains.org.objectweb.asm.MethodVisitor.visitEnd(MethodVisitor.java:782)
    at org.jetbrains.org.objectweb.asm.tree.MethodNode.accept(MethodNode.java:772)
    at org.jetbrains.kotlin.backend.jvm.codegen.ClassCodegen.generateMethod(ClassCodegen.kt:405)
    at org.jetbrains.kotlin.backend.jvm.codegen.ClassCodegen.generate(ClassCodegen.kt:133)
    at org.jetbrains.kotlin.backend.jvm.JvmLowerKt$codegenPhase$1$1.lower(JvmLower.kt:304)
    at org.jetbrains.kotlin.backend.common.phaser.FileLoweringPhaseAdapter.invoke(PhaseBuilders.kt:120)
    at org.jetbrains.kotlin.backend.common.phaser.FileLoweringPhaseAdapter.invoke(PhaseBuilders.kt:116)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
    at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invokeSequential(performByIrFile.kt:65)
    at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:55)
    at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:41)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:29)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
    at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:29)
    at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
    at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:43)
    at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.doGenerateFilesInternal(JvmIrCodegenFactory.kt:191)
    at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:60)
    at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:618)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:211)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:90)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:386)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:110)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:303)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileImpl(IncrementalCompilerRunner.kt:121)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:74)
    at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:607)
    at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1659)
    at jdk.internal.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException: Error at instruction 5: Cannot pop operand off an empty stack.
    at org.jetbrains.org.objectweb.asm.tree.analysis.Analyzer.analyze(Analyzer.java:295)
    at org.jetbrains.kotlin.codegen.optimization.boxing.PopBackwardPropagationTransformer$Transformer.transform(PopBackwardPropagationTransformer.kt:55)
    at org.jetbrains.kotlin.codegen.optimization.boxing.PopBackwardPropagationTransformer.transform(PopBackwardPropagationTransformer.kt:38)
    at org.jetbrains.kotlin.codegen.optimization.transformer.CompositeMethodTransformer.transform(CompositeMethodTransformer.kt:25)
    at org.jetbrains.kotlin.codegen.optimization.OptimizationMethodVisitor.performTransformations(OptimizationMethodVisitor.kt:66)
    at org.jetbrains.kotlin.codegen.TransformationMethodVisitor.visitEnd(TransformationMethodVisitor.kt:70)
    ... 52 more
Caused by: java.lang.IndexOutOfBoundsException: Cannot pop operand off an empty stack.
    at org.jetbrains.org.objectweb.asm.tree.analysis.Frame.pop(Frame.java:228)
    at org.jetbrains.org.objectweb.asm.tree.analysis.Frame.executeInvokeInsn(Frame.java:640)
    at org.jetbrains.org.objectweb.asm.tree.analysis.Frame.execute(Frame.java:573)
    at org.jetbrains.org.objectweb.asm.tree.analysis.Analyzer.analyze(Analyzer.java:187)
    ... 57 more

It's gradle kotlin console app project, if i need to install any extra dependency pls suggest how.



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