Friday, July 9, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Is there an easy way to migrate database data from SQLite to Postgres table by table in Python?

Posted: 09 Jul 2021 09:03 AM PDT

Is there an easy way in Python to migrate from SQLite to Postgres table by table? I am using Peewee, can generate SQLite dumps but don't have psql available to import into Postgres. Is there a package in Python for that? I am also using Peewee as ORM and the generate schema bit is covered, the issue is the data.

The database is somewhat big at 1.3gb

Missing (required) ID Token in Token Response for Client Registration: google

Posted: 09 Jul 2021 09:03 AM PDT

I am currently working an an authentication portal using spring-security for educational purposes. So far I have been able to succesfully retrieve access tokens and refresh tokens from both Google and Discord. However, in the authorization flow from google, I am getting the following error:

[invalid_id_token] Missing (required) ID Token in Token Response for Client Registration: google

The odd thing here is that the Token response in Discord's auth flow has the same properties as Google's Token Response, but the Discord flow does not require the ID token (for what reason?) and hence does not produce the above error.

This is my (part of) application.properties file:

spring.security.oauth2.client.registration.google.client-secret=<secret>  spring.security.oauth2.client.registration.google.redirectUri=http://localhost:4200/callback  spring.security.oauth2.client.registration.google.client-authentication-method=post  spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code  spring.security.oauth2.client.registration.google.provider=google      spring.security.oauth2.client.registration.discord.client-id=<id>  spring.security.oauth2.client.registration.discord.client-secret=<secret>  spring.security.oauth2.client.registration.discord.client-authentication-method=post  spring.security.oauth2.client.registration.discord.authorization-grant-type=authorization_code  spring.security.oauth2.client.registration.discord.redirect-uri=http://localhost:4200/callback  spring.security.oauth2.client.registration.discord.scope=identify  spring.security.oauth2.client.registration.discord.provider=discord  spring.security.oauth2.client.provider.discord.authorization-uri=https://discord.com/api/oauth2/authorize  spring.security.oauth2.client.provider.discord.token-uri=https://discord.com/api/oauth2/token  

And my SecurityConfigurer file:

@Override      protected void configure(HttpSecurity http) throws Exception {          // Enable CORS and disable CSRF          http                  .csrf()                  .disable()                  .cors()                  .and()                  .authorizeRequests()                  .antMatchers("/login/oauth2/**", "/login**").permitAll()                  .anyRequest().authenticated()                  .and()                  .oauth2Login()                  .authorizationEndpoint()                  .authorizationRequestResolver(new CustomAuthorizationRequestResolver(clientRegistrationRepository, "/oauth2/authorization/"))                  .authorizationRequestRepository(new InMemoryRequestRepository())                  .and()                  .successHandler(this::onAuthenticationSuccess)                  .failureHandler(this::onAuthenticationFailure)                  .tokenEndpoint().accessTokenResponseClient(new RestOAuth2AccessTokenResponseClient(restOperations()))  

As mentioned, both Discord and Google's Token response look like this:

{    "access_token": "<access_token>",    "expires_in": <duration in seconds>,    "token_type": "Bearer",    "scope": "",    "refresh_token": "<refresh_token>"  }  

Yet Discord's auth flow goes through onAuthenticationSuccess, but Google's auth flow goes straight into onAuthenticationFailure with the mentioned exception.

My question is: why and what am I doing wrong?

Part of the stack trace:

org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_id_token] Missing (required) ID Token in Token Response for Client Registration: google      at org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider.authenticate(OidcAuthorizationCodeAuthenticationProvider.java:152) ~[spring-security-oauth2-client-5.5.1.jar:5.5.1]      at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182) ~[spring-security-core-5.5.1.jar:5.5.1]      at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:192) ~[spring-security-oauth2-client-5.5.1.jar:5.5.1]  ...  

Invoke-Command for initiating Windows to update remotely is very slow, it is possible to make it run faster?

Posted: 09 Jul 2021 09:02 AM PDT

I have a series of script blocks I use for general PC maintenance and management. Everything I use runs fine, until I reach to this specific point in the script, which uses the Invoke-Command Script-Block {code here} Everything comes to a crawl, as it checks each PC for pending Windows updates, and then initiates said machine to update.

Script code:

ForEach($Session in $Sessions){      Write-host "Checking for updates on $Session {          $Pending = Invoke-Command -Session $Session {          Return (Test-Path "HKLM:\SOFTWARE\Micrososft\Windows\CurrentVersion\windowsupdate\Auto                   Update\ Reboot Required")          }          if($pending ne 'True') {              $CheckForUpdate = Invoke-Command -Session $Session -ScriptBlock {                  $UpdateSession = New-Object -ComObject "Microsoft.Update.Session"                  $Updates = $UpdatesSession.createupdatesearcher().search("IsInstalled=0 and                              Type='Software'").Updates                  $Updates              } -ErrorAction SilentlyContinue -AsJob                If ($Checkforupdate.count -gt 0)              {                  $UpdatestoInstall.Add($Session.ComputerName)                  Write-Host $Session.ComputerName "has updates to install."                  }              else              {                  $UpdatesInstalled.Add($Session.ComputerName)                  Write-Host $Session.ComputerName "has installed all available updates"          }  }  

I put in -AsJob to see if it would make the Invoke-Command run any faster, and it indeed does! Not without giving more inaccurate results, sadly.

Is there any way to make the Invoke-Command Script-block run more efficiently for checking, and initiating Windows updates remotely?

Failure when decompressing gzip file with Python

Posted: 09 Jul 2021 09:02 AM PDT

I've downloaded a "myfile.tsv.gz" file from Azure (with azcopy). I want to open it in Python.

import gzip  f = gzip.open('myfile.tsv.gz', 'rb')  file_content = f.read()  

But with both Python 2.7.16 and Python 3.9.5 on macOs, I got the error message:

Traceback (most recent call last):    File "<stdin>", line 1, in <module>    File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/gzip.py", line 300, in read      return self._buffer.read(size)    File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/gzip.py", line 495, in read      uncompress = self._decompressor.decompress(buf, size)  zlib.error: Error -3 while decompressing data: invalid block type  

I really don't have idea how I could fix it.

FYI, on my terminal this command yields:

>gunzip -t myfile.tsv.gz    gunzip: data stream error   gunzip: myfile.tsv.gz: uncompress failed  

Nevertheless this command seems to print correctly the file content:

>gunzip -c myfile.tsv.gz    [correct file content]  

I've also tried to re-download this file, same issue...

Thanks!

Jenkinsfile - How to pass parameter to send emails

Posted: 09 Jul 2021 09:02 AM PDT

My Question:

I want to send email if an enduser ever wants to receive emails on a regular basis with the attached csv file, we can change the pipeline to set the "isSendEmail" to "true" and populate the default value with that user's email address and the job will automatically send emails from that point on.

but while configuring the jenkisnfile, job runs fine but there is no email notification received? what is the correct way to configure parameter for Email Id's in jenkinsfile to send email so that doing it this way also allows me to easily run the job manually and sends the email to other people on an adhoc basis.

Jenkinsfile

   pipeline {    agent any    options {      buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')    }    stages {         stage('Use AWS CLI to detect untagged resources') { steps {          script {              def awsUtil = new AwsUtil()              sh """#!/bin/bash              set              aws resourcegroupstaggingapi get-resources --tags-per-page 100 --tag-filters Key=SysName,Values=KickMe --tag-filters Key="SysName in ServiceNow",Values=False > tag-filter.json              jq '.ResourceTagMappingList[].Tags |= map(select(.Key|IN("ManagedBy","SysName","Owner","SysName in ServiceNow","Name","TSM")))' tag-filter.json > untagged-resources.json              ls              echo "un tag resource.json file data"              cat untagged-resources.json              echo "--------------"              cat tag-filter.json              python untag_resources_convert_csv.py              ls              """          }}}         stage('Setup parameters') { steps {         script {             properties([                  parameters([                      booleanParam(                         defaultValue: true,                          description: '',                          name: 'isSendEmail'                        ),                      string(                         defaultValue: '',                          description: '',                          name: 'def@xxx.com,abc@xxx.com,ghi@xxx.com',                          trim: true                      )                  ])              ])          }}}                                   }      post {          always {              archiveArtifacts artifacts: 'unTagResources_Details.csv', onlyIfSuccessful: true              emailext (          attachmentsPattern: 'unTagResources_Details.csv', body: '''${SCRIPT, template="groovy-html.template"}''',                  subject: '$DEFAULT_SUBJECT',                  mimeType: 'text/html',to: "email id"              );          }          }  }  

Generate Embeddings with Keras

Posted: 09 Jul 2021 09:02 AM PDT

I am trying to generate embeddings with keras using LSTM autencoder. I got my hand on the model, but I am not sure how to get embeddings for my data. Embeddings are supposed to be latent representation of original input data which has shape in my case of (847, 147).

model = keras.Sequential(name="LSTMAE")    #Encoder  model.add(keras.layers.LSTM(128, activation='tanh',                                input_shape=(847, 147),                                kernel_regularizer=keras.regularizers.l2(0.0000001),                                return_sequences=True))  model.add(keras.layers.LSTM(64,                                activation='tanh',                               return_sequences=False))    model.add(keras.layers.RepeatVector(train_copy.shape[0]))    #Decoder  model.add(keras.layers.LSTM(64,                                activation='tanh',                               return_sequences=True))  model.add(keras.layers.LSTM(128,                                activation='tanh',                               return_sequences=True))    model.add(keras.layers.TimeDistributed(keras.layers.Dense(train_copy.shape[1])))  model.compile(optimizer=keras.optimizers.Adam(lr=0.0001, clipnorm=1.0, clipvalue=0.5), loss='mse')  model.summary()  

Please let me know if you need more details in case anything is vague about my que

Why would my dynamo queries occasionally not return a message

Posted: 09 Jul 2021 09:02 AM PDT

Every so often my queries to dynamo are never returned. My node code will make the request but the data is never returned. This what my query looks, surrounded with log statements. The dynamo table does have auto-scaling enabled. It has not logs of throttling or latency corresponding with these messages.

console.log(params);  results = await docClient.query(params).promise();  console.log(params, results);  

This is the metrics over 12 hours, so it isn't happening much.

enter image description here

enter image description here

enter image description here

Overloading operator<< in C++ for tmeplate classes

Posted: 09 Jul 2021 09:02 AM PDT

my dear StackOverflow friends. Today ,I am here to ask all of you for help in the following C++ program.

Currently, I am using Microsoft Visual Studio platform for source code editor and when I try to compile this code I got an linker error.

Severity Code Description Project File Line Suppression State

Error LNK2019 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits > &,class X &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$X@H@@@Z) referenced in function _main Zadatak7.19.04.2021 C:\Users\AT95\Desktop\Zadatak7.19.04.2021\Zadatak7.19.04.2021\main.obj 1 Severity Code Description Project File Line Suppression State Error LNK1120 1 unresolved externals Zadatak7.19.04.2021 C:\Users\AT95\Desktop\Zadatak7.19.04.2021\Debug\Zadatak7.19.04.2021.exe 1

My question is the following, What I must do to make this program work right ? I wan't you to look at the definition of the overloading operator<< because that method is causing error's.

Thank you all.

#include <iostream>            template <class T>      class X      {            private:                int index, capacity;                T* collection{};            public:                X(const int nmb, const T* array)          {              index = 0;                    capacity = nmb;                    collection = new(T[nmb]);                    for (int i = 0; i < nmb; i++)                  collection[index++] = array[i];          }                X(const X& other)          {              index = other.index;              capacity = other.capacity;                    collection = new(T[other.capacity]);                    if(other.index < other.capacity)              for (int i = 0; i < other.index; i++)                  collection[i] = other.collection[i];          }                ~X() { delete[] collection; }                          friend std::ostream& operator<<(std::ostream&, X<T>&);                };            template <class T>      std::ostream& operator<<(std::ostream& out, X<T>& other)      {          for (int i = 0; i < other.index; i++)              out << i + 1 << ". " << other.collection[i];                return out;      }            int main()      {          int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, n = sizeof(array)/sizeof(int);                X<int> x(n, array), b(x);                std::cout << x;                return 0;      }  

DATASET OBJECT IS NOT GETTING CREATED, HELP ME OUT

Posted: 09 Jul 2021 09:02 AM PDT

class education extends Thread  {  public void run()  {      String filename="Educational_loan.txt";      String path_Training_DataSet="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/"+filename;      String path_Attribute_Information="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/Attribute_information.data";      String dlimiter=",";      Dataset training_DataSet= new Dataset(path_Training_DataSet,dlimiter,path_Attribute_Information,dlimiter,"training");      //String path_Test_DataSet="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/"+filename;      //Dataset test_DataSet= new Dataset(path_Test_DataSet,dlimiter,path_Attribute_Information,dlimiter,"test");  }  

}

 public static void main(String args[])  {      long start=System.currentTimeMillis();      try      {    filename="Educational_loan.txt";        path_Training_DataSet="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/"+filename;      //String path_Attribute_Information="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/Attribute_information3.data";      //String dlimiter=",";      Dataset Educational_loan_DataSet= new Dataset(path_Training_DataSet,dlimiter,path_Attribute_Information,dlimiter,"training");      //String path_Test_DataSet="C:/Users/Soumy/OneDrive/Documents/thread/src/Datasets/"+filename;      //Dataset test_DataSet= new Dataset(path_Test_DataSet,dlimiter,path_Attribute_Information,dlimiter,"test");  

Dataset is not getting created in the above code, what to do ? help me out ! It is showing numerous errors while build

SQL Finding codes

Posted: 09 Jul 2021 09:03 AM PDT

I want to see all my customers who have received a document code Eg. [RF001], however I also want to see that they haven't received a number of document codes E.G [RF002, RF005, RF006, RF009]. All the document codes sit in 1 column, and the customer references are repeated. Table

Customer_Ref | Doc_Code CS001 | RF001 CS002 | RF003 CS001 | RF002

ag-grid row drag feature overrides cellstyle feature

Posted: 09 Jul 2021 09:03 AM PDT

implementing Text-aling style for some of rows. It works well but when I enabled "rowDrag" feature for related column then it overrides "cellStyle" property feature and style does not implements into column.

note,using enterprise version of ag-grid.

  columnDefs.push({                  headerName: "Metric Name",                  field: "metric_definition",                  width: 320,                    filter: 'agSetColumnFilter', filterParams: { excelMode: 'windows' },                  pinned: 'left',                   rowDrag: true,                  cellStyle: params => {                      var value = params.data.metric_id;                         if ([74,75,76,77,93].includes(value)) {                           return { textAlign: "right" };                      }                      return null;                  }              }              );

Writing a Program to store data in a txt file [closed]

Posted: 09 Jul 2021 09:03 AM PDT

So I am trying to grab the dates from the file (the dates are on line 104 of the file) and then collect all of the rest of the news data in the file and then store date and news data as a single json object in a new file. I want to be able to store the data like so: News_data = {"Date": "1/1/2020", "News": some news data, another news data.}. My problem is with the News data, for some reason it keeps collecting the data over and over again in an infinite loop that keeps crashing my computer, I have tried string concatenation, but that doesn't seem to work either. I am very new to programming, and I would appreciate any insight!!

# Excluding unnecessary data from the texts.  counter = 0  str_accum = ""  with open('data/1.txt', 'r', encoding = "utf8",) as fin:  # Open   file for read      lines = fin.readlines()      for line in lines: # Read line-by-line          counter += 1          date = ""          news_data = ""          line = line.strip("\n") # Strip the carrage return.          line = line.strip("|")          #if counter > 104:              #print(counter)              #print(line)          if counter == 103:             date = line             #print(line)          if counter >= 104:              news_data = " ".join(line.strip() for line in lines)               print(news_data)          my_tuple = {"Date": date, "News": news_data}          print(my_tuple)    # File closed automatically upon exit of with-statement  

javascript string contains \u0027 after concat strings with '

Posted: 09 Jul 2021 09:02 AM PDT

I am trying to create a string, containing ('). When I send an AJAX post to consume a web service, the string sent, contains \u0027 .Any help?

var SearchCriteria = "1=1";           if (tblSYS_SubscribersSearch.value.length > 0) {              SearchCriteria = "FirstName LIKE N'%" + Criteria + "%' OR LastName LIKE N'%" + Criteria + "%'";          }          var settings = {              "url": "<%=ConfigurationManager.AppSettings["EndPoint"].ToString()%>" + "/api/SYS_Subscriber/GetListPaged",              "method": "POST",              "timeout": 0,              "headers": {                  "Content-Type": "application/json"              },              "data": JSON.stringify({                  "ApiKey": Apikey,                  "Fields": Fields,                  "Criteria": SearchCriteria,                  "SortOrder": SortOrder,                  "SortDirection": SortDirection,                  "PageIndex": PageIndex,                  "PageSize": PageSize              }),          };  

WooCommerce Double Add to Cart Redirect with JQuery

Posted: 09 Jul 2021 09:02 AM PDT

I would like to use the double add to cart button on the single product page. And want to redirect after product add to cart.

For example, after adding the Continue button to the cart, I want to redirect to the checkout page. And I want to redirect the Add & Continue button to another page after adding to cart.

woocommerce_add_to_cart_redirect When redirected with this filter, both buttons are redirected to the same page. Tried with Jquery. Properly it didn't work. Any solution please ..?

enter image description here

<div class="double__cart">    <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt product_left_cart"><?php echo esc_html( 'Continue' ); ?></button>    <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>    </div>

Add to cart redirect filter...

function habooktheme_add_to_cart_redirect( $url ) {  $url = get_permalink( 943 );  return $url;}  add_filter( 'woocommerce_add_to_cart_redirect', 'habooktheme_add_to_cart_redirect' );  

$(".product_left_cart").click(function(){  if ( requiredVal !== '' ) {    var delay = 2000;     var url = '//abc.com'    setTimeout(function(){ window.location = url; }, delay);  }  });

how to make a heading always stay horizontal inplace of overflow

Posted: 09 Jul 2021 09:02 AM PDT

I am working on a portfolio project and I am creating the projects section. The width of the projects section is around 350px so only some of the title could be visible but if the text is not able to fit in 350 px it is making the text overflow vertically but I want it to overflow horizontally.

here is my HTML&CSS:

.project-container {      display: grid;      height: 350px;      width: 350px;      background: #c4c4c4;      margin-bottom: 3%;  }    .project-title{      height: 45px;      width: 100%;      background-color: red;      margin: 0;      display: flex;      align-items: center;      justify-content: center;      overflow: auto;  }
<div class="project-container">      <h1 class="project-title">Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores dignissimos praesentium dolorem saepe velit at libero a consectetur atque molestias.</h1>  </div>

and here is my result when the text can't fit in 350px:

enter image description here

but I want the overflow to be horizontal

Foreign Keys and importing data in MySQL workbench issues

Posted: 09 Jul 2021 09:03 AM PDT

I have looked everywhere and seen most of the threads pertaining to this issue but still can't get it to work for me.

This is what I made using Workbench. It's a real estate database:

DROP DATABASE IF EXISTS projet3;  CREATE DATABASE projet3;  USE projet3;    CREATE TABLE Localite (  Localite_ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,  Commune VARCHAR(50) NOT NULL,  Departement SMALLINT NOT NULL,  PRIMARY KEY (Localite_ID)  )ENGINE=InnoDB DEFAULT CHARSET=utf8;    CREATE TABLE Bien (  Bien_ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,  SurCar1 DOUBLE NOT NULL,  TypeLoc VARCHAR(15) NOT NULL,  NoPP SMALLINT NOT NULL,  Localite_ID SMALLINT UNSIGNED NOT NULL DEFAULT 0,  PRIMARY KEY (Bien_ID),  CONSTRAINT FK_Localite FOREIGN KEY (localite_ID) REFERENCES localite (Localite_ID) ON DELETE RESTRICT ON UPDATE CASCADE  )ENGINE=InnoDB DEFAULT CHARSET=utf8;    CREATE TABLE Mutation (  Mutation_ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,  DateMutation DATETIME NOT NULL,  ValeurFonciere INT NOT NULL,  Bien_ID SMALLINT UNSIGNED NOT NULL DEFAULT 0,  PRIMARY KEY (Mutation_ID),  CONSTRAINT FK_Bien FOREIGN KEY (Bien_ID) REFERENCES bien (Bien_ID) ON DELETE RESTRICT ON UPDATE CASCADE  )ENGINE=InnoDB DEFAULT CHARSET=utf8;    DROP TABLE IF EXISTS Adresse;  CREATE TABLE Adresse (  Adresse_ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,  NoVoie SMALLINT NOT NULL,  TypeVoie VARCHAR(10) NOT NULL,  NomVoie VARCHAR(50) NOT NULL,  CodePostal INT NOT NULL,  Bien_ID SMALLINT UNSIGNED NOT NULL DEFAULT 0,  PRIMARY KEY (Adresse_ID),  CONSTRAINT FK_Bien FOREIGN KEY (Bien_ID) REFERENCES bien (Bien_ID) ON DELETE RESTRICT ON UPDATE CASCADE  )ENGINE=InnoDB DEFAULT CHARSET=utf8;`  

The corresponding model looks like this: EER model I had to change the relationship between Bien and Adresse to a 1 on 1, which I then forward engineered. I understand I could integrate the Adresse attributes into the Bien table but for the sake of the tasks I have to perform on it I have kept them separate.

However, when I then try to import data into any table with a foreign key the workbench refuses giving me this: Cannot add or update child row

I have also tried to simply create the tables, import the data and then create the foreign keys but I get the same result.

Any help would be appreciated!

Angular NGRX Added EntityState, EntityAdapter, only returning 1 record instead of all

Posted: 09 Jul 2021 09:03 AM PDT

I got a working Angular NGRX UI Table loaded with all the record (Over 100) and just added the following import to work with NGRX EntityState, EntityAdapter etc.

import { createFeatureSelector, createSelector} from "@ngrx/store";  import { EntityState, EntityAdapter, createEntityAdapter } from "@ngrx/entity";  

After I added the entityAdapter, I just got 1 record back. I placed a breakpoint in the loadSuccess and VS Code shows over 100 records added with the .AddMany method but I can't figure out why only 1 record is returning to the UI.

If I use .AddMany with over 100 records returning from the api, shouldn't the selector return all of them?

Here is my code so far with my comments. Any help is greatly appreciated.

export interface MyRecordViewModel{      records: MyRecord[];      columns: string[];  }        export interface MyFormState extends EntityState<MyRecordViewModel> {      selectedRecordId: number | null;      columns: string[];      loading: boolean;      loaded: boolean;      error: string;  }    export interface AppState extends fromRoot.AppState {      myForms: MyFormState  }    export const myAdapter: EntityAdapter<MyRecordViewModel> = createEntityAdapter<MyRecordViewModel>();    export const defaultFdForm: MyStateState = {      ids: [],      entities: {}, //this will contain/manage MyRecordViewModel array of records      columns: [],      selectedRecordId: null,      loaded: false,      loading: false,      error: ""  }    export const initialState = adapter.getInitialState(defaultFdForm);    export function myReducer(      state = initialState,      action: myActions.Actions  ) : MyFormState {        switch(action.type) {          case myActions.myActionTypes.LOAD_RECORDS: {              return {                  ...state,                  loading: true              }          }          case myActions.myActionTypes.LOAD_RECORDS_SUCCESS: {              return myAdapter.addMany( // use the addMany to add the api data                  action.payload.records, { // place a breakpoint here and VS Code clearly shows over 100 records                      ...state,                      columns: action.payload.columns,                      loading: false,                      loaded: true                  }              )              // return { // this was the old code without entityadapter that works              //     ...state,              //     loading: false,              //     loaded: true,              //     //viewModel: action.payload,              //     columns: action.payload.columns,              //     records: action.payload.records,              // }          }          default : {              return state;          }      }  }      const getMyRecordsFeatureState = createFeatureSelector<myFormState>(      "myForms"  );     export const getRecords = createSelector(      getMyRecordsFeatureState,      myAdapter.getSelectors().selectAll // this is the new code and it returns 1 record, not sure why or how to troubleshoot this.      //(state: MyFormState) => state.records // old code that works  );  

Can't generate build after implementing facebook sdk due to paytm allinOne sdk

Posted: 09 Jul 2021 09:02 AM PDT

<uses-sdk android:minSdkVersion="18" />  

This is my android sdk minimum version I installed both facebook and paytm sdk in my app. While generating the build, I'm getting error code 1.

This is the error I'm getting while generating build

If I generate build with faceboook sdk alone, i can generate the build.if both facebook and allinone paytm sdk exist, error occurs. Is there any way to generate build without removing allinOne sdk??

c# dependency injection singleton can i use it in two different classes [duplicate]

Posted: 09 Jul 2021 09:03 AM PDT

i have an interface :

 public interface Irepos       {        string somefunction();      }  

then the class i want to use :

public class repos : Irepos      {        string somefunction()         {           return "function called";         }      }  

registered as singleton in startup.cs:

services.AddSingleton<Irepos, repos>();  

now i can use it like this in my controller class:

public class controller   {      private readonly Irepos interfaceRepos;                    public ValuesController(Irepos reposInerface)              {                  interfaceRepos = reposInerface;              }                interfaceRepos.somefunction();  }  

now my question is : can i use the same instance of the same "repos " class in a different class or different controller say :

public class AnotherController  {    private readonly Irepos interfaceRepos;                            public ValuesController(Irepos reposInerface)                  {                      interfaceRepos = reposInerface;                  }                        interfaceRepos.somefunction();  }  

How do I navigate to a new View but remove its connection to the NavigationView?

Posted: 09 Jul 2021 09:03 AM PDT

I have a Login Flow that is embedded into a NavigationView, but once it's successful the new view is a TabView. However, I do not need this TabView to be a part of the Navigation Stack. All the views within the tabs have their own NavigationViews. So I need to somehow get rid of the original NavigationView once a user has logged in. I have attached the unwanted behavior, which is a an empty Nav bar in each tab view, and the wanted behavior, which works when I quit the app and start on this view with no NavigationView.

TD;LR Unwanted:

NavigationView -> LoginView -> (if Successful) TabView  

Wanted:

NavigationView -> LoginView -> if Successful then  TabView - >  

Unwanted behavior: Unwanted behavior

Correct Behavior: Correct Behavior

Golang: Attempt to parallelize not fast enough

Posted: 09 Jul 2021 09:03 AM PDT

I am new to learning Golang. I read about Go's concurrency model and also saw about the difference between concurrency and parallelism. In order to test parallel execution, I wrote the following program.

package main    import (      "fmt"      "runtime"      "time"  )    const count = 1e8    var buffer [count]int    func main() {        fmt.Println("GOMAXPROCS: ", runtime.GOMAXPROCS(0))        // Initialise with dummy value      for i := 0; i < count; i++ {          buffer[i] = 3      }        // Sequential operation      now := time.Now()      worker(0, count-1)      fmt.Println("sequential operation: ", time.Since(now))        // Attempt to parallelize      ch := make(chan int, 1)      now = time.Now()      go func() {          worker(0, (count/2)-1)          ch <- 1      }()      worker(count/2, count-1)      <-ch      fmt.Println("parallel operation: ", time.Since(now))  }    func worker(start int, end int) {        for i := start; i <= end; i++ {          task(i)      }  }    func task(index int) {        buffer[index] = 2 * buffer[index]  }  

But the problem is: the results are not very pleasing.

GOMAXPROCS:  8  sequential operation:  206.85ms  parallel operation:  169.028ms  

Using a goroutine does fasten things up but not enough. I expected it to be closer to being twice as fast. What is wrong with my code and/or understanding? And how can I get closer to being twice as fast?

Why does my SQL code in IB Expert return some nulls

Posted: 09 Jul 2021 09:03 AM PDT

I have written this script:

SELECT id_pass, max(dt) FROM parking_pass_move  WHERE type_error is null and id_pass = 1784  GROUP BY id_pass  HAVING max(dt) < '2021-07-02'   

And it returns:
result

OK! But when I change my having row to:

HAVING max(dt) < '2021-07-01'  

Or even:

HAVING max(dt) < '2021-06-27'  

I have this:
result

Such data definitely exists, so I don't understand what to do:
result

Structure of the table:
table types

I tried to change 'dt' to date and timestamp, tried to do same with date in having row. It didn't help.

My aim with this code is to take last move for selected pass and date.

Fragment popbackstack trigger lifecyclescope collect

Posted: 09 Jul 2021 09:03 AM PDT

Situation

I submit data setTripDeliver, the collect works fine (trigger LOADING and then SUCCESS). I pressed a button go to next fragment B (using replace). After that, I press back button (using popbackstack). the collect SUCCESS triggered.

Codes Related

These codes at the FragmentA.kt inside onViewCreated.

private fun startLifeCycle() {      viewLifecycleOwner.lifecycleScope.launch {          viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {              launch {                  collectTripDeliver()              }              launch {                  collectTripReattempt()              }          }      }  }  

These codes when to submit data at a button setOnClickListener.

viewLifecycleOwner.lifecycleScope.launchWhenStarted {      viewModel.setTripDeliver(           verificationCode,           remark      )  }  

Method to collect flow collectTripReattempt()

private suspend fun collectTripReattempt() {          viewModel.tripReattempt.collect {              when (it) {                  is Resource.Initialize -> {                }              is Resource.Loading -> {                  Log.i("???","collectTripReattempt loading")                  handleSaveEarly()              }              is Resource.Success -> {                  val error = it.data?.error                  if (error == null) {                      Tools.showToast(requireContext(), "Success Reattempt")                      Log.i("???","collectTripReattempt Success")                                 } else {                      Tools.showToast(requireContext(), "$error")                  }                  handleSaveEnding()              }              is Resource.Error -> {                  handleSaveEnding()              }          }      }  }  

Logcat

2021-07-09 19:56:10.946 7446-7446/com.package.app I/???: collectTripReattempt loading  2021-07-09 19:56:11.172 7446-7446/com.package.app I/???: collectTripReattempt Success  2021-07-09 19:56:17.703 7446-7446/com.package.app I/???: collectTripReattempt Success  

As you can see, the last Success is called again AFTER I pressed back button (popbackstack)

Question

How to make it trigger once only? Is it the way I implement it is wrong? Thank you in advance.

How to access the data in multi nested document in mongodb?

Posted: 09 Jul 2021 09:03 AM PDT

I need to access the data from the multi nested subdocument by omitting some fields of the nested document. The schema is shown below and the output expected is also shown below. Since projections cannot be used at the nested level so how can I do that?

given below is the database schema which is having nested entries as shown.

[{    "_id": {      "$oid": "60e519db4e0f140328adc7c7"    },    "subcategories": [      {        "trans": {          "en": {            "name": "LOGO DESIGN",            "description": "LOGO DESIGN"          },          "fr": {            "name": "LOGO DESIGN",            "description": "LOGO DESIGN"          }          },        "counts": 0,        "slug": "logo-design",        "is_visible": true,        "image": "",        "_id": {          "$oid": "60e51a116678530e84ee2e61"        },        "created_at": 1625627153535,        "service_type": [          {             //languages available for translation            "trans": {              "en": {                "name": "null",                "description": "null"              },              "fr": {                "name": "null",                "description": "null"              }              },            "counts": 0,            "is_visible": true,            "_id": {              "$oid": "60e51a116678530e8460"            },            "image": "",            "slug": "null",            "created_at": 1625627153535,                     }        ]      },  }  ]  

Code I have tried so far:

const r = await client              .collection("categories")            .aggregate([               { $addFields: { temp: `$trans.${lang}` } },              { $project: { trans: 0 } },              { $addFields: { trans: "$temp" } },              { $project: { temp: 0 } },              { $addFields: { temp: `$subcategories.$[].trans.${lang}` } },              { $project: { "subcategories.trans": 0 } },              { $addFields: { "subcategories.$.trans": "$temp" } },              { $project: { temp: 0 } },                      ])            .toArray();  console.log(r);  

Response of console.log(r):

:: FieldPath field names may not start with '$'  

Expected output:

[{    "_id": {      "$oid": "60e519db4e0f140328adc7c7"    },    "subcategories": [      {        "trans": {              "name": "LOGO DESIGN",            "description": "LOGO DESIGN"                  },        "counts": 0,        "slug": "logo-design",        "is_visible": true,        "image": "",        "_id": {          "$oid": "60e51a116678530e84ee2e61"        },        "created_at": 1625627153535,        "service_type": [          {            "trans": {                             "name": "null",                "description": "null"                          },            "counts": 0,            "is_visible": true,            "_id": {              "$oid": "60e51a116678530e8460"            },            "image": "",            "slug": "null",            "created_at": 1625627153535,          }        ]      },  }  ]  

please help in resolving this issue with any good and valid approaches.

Vertical RecyclerView nested inside vertical RecyclerView

Posted: 09 Jul 2021 09:03 AM PDT

I have spent hours/days reading around this subject but still can't find something that works. I'm trying to put a fixed-height vertically-scrolling RecyclerView in the row of another vertically-scrolling RecyclerView.

Much of the advice is along the lines of "it's a crime to put a vertically-scrolling RecyclerView inside another vertically-scrolling RecyclerView"... but I can't figure out why this is so bad.

In fact, the behavior would be almost exactly the same as many pages on StackOverflow (e.g. this one... and indeed this very question, at least when viewed on a mobile device), where the code sections are of a fixed (or max) height, and scroll vertically, and are contained within a page that itself scrolls vertically. What happens is that when the focus is on the code section, scrolling happens within that section, and when it reaches the upper/lower end of the scroll range of the section, then scrolling happens within the outer page. It's quite natural, not evil.

This is my recycler_view_row_outer.xml (a row within the outer RecyclerView):

<com.google.android.material.card.MaterialCardView      xmlns:card_view="http://schemas.android.com/apk/res-auto"      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      style="@style/MyCardView"      app:cardElevation="4dp"      app:strokeColor="?attr/myCardBorderColor"      app:strokeWidth="0.7dp"      card_view:cardCornerRadius="8dp" >        <RelativeLayout          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:orientation="vertical" >            <TextView              style="@style/MyTextView.Section"              android:id="@+id/list_title" />            <LinearLayout              style="@style/MyLinearLayoutContainer"              android:id="@+id/list_container"              android:layout_below="@+id/list_title" >          </LinearLayout>        </RelativeLayout>    </com.google.android.material.card.MaterialCardView>  

And this is my recycler_view_row_inner.xml (a row within the inner RecyclerView):

<?xml version="1.0" encoding="utf-8"?>  <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      android:id="@+id/my_constraint_layout"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:layout_below="@+id/list_container" >        <androidx.recyclerview.widget.RecyclerView          android:id="@+id/recycler_view_inner"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:scrollbarStyle="outsideOverlay"          android:scrollbars="vertical"          app:layout_constrainedHeight="true"          app:layout_constraintBottom_toBottomOf="@+id/my_constraint_layout"          app:layout_constraintEnd_toEndOf="@+id/my_constraint_layout"          app:layout_constraintHeight_max="750dp"          app:layout_constraintHeight_min="0dp"          app:layout_constraintStart_toStartOf="@+id/my_constraint_layout"          app:layout_constraintTop_toTopOf="@+id/my_constraint_layout" >      </androidx.recyclerview.widget.RecyclerView>    </androidx.constraintlayout.widget.ConstraintLayout>  

With the above inner layout, I've tried to follow the approach set out in this post, to create an inner RecyclerView having a fixed/max height... but it isn't working.

I inflate the inner layout (added to list_container/containerView in the outer layout) and set up my inner recyclerView as follows:

View inflatedView = getLayoutInflater().inflate(R.layout.recycler_view_row_inner, containerView, false);  RecyclerView recyclerView = inflatedView.findViewById(R.id.recycler_view_inner);  // set adapter, row data, etc  

But all this does is create a fixed-height inner row that does not scroll within the outer row... overflow content of the inner row is just cut off and I can't reach the lower part of it because it just scrolls the outer row.

Any idea how to make this work?

Playing audio in Safari using .play()

Posted: 09 Jul 2021 09:02 AM PDT

I'm looking to play an audio file using custom controls to trigger the .play() method on a custom button. To be clear, I'm not trying to have the audio auto-play. Everything works perfectly in Chrome, but in Safari I get the error:

Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

The project is built using React and React Router, so I'm wondering if it's possibly fixable in my useEffect() hook. I've tried enabling controls on the audio element and using CSS to remove them from the DOM, but no luck.

import React, { useState, useRef, useEffect } from "react";  import { BrowserRouter as Router, Switch, Route } from "react-router-dom";  import { gsap } from "gsap";    function RadioPlayerNav(props) {      const audioEl = useRef(null);      const [isPlaying, setIsPlaying] = useState(false);        const playingTitle = document.querySelector(".radio-player-nav .title p");        const toPX = (value) => {          return (parseFloat(value) / 100) * (/vh/gi.test(value) ? window.innerHeight : window.innerWidth);      };        const radioPlayerGSAP = gsap.to(".radio-player-nav .title p", {          x: toPX("-5vw"),          duration: 4,          ease: "none",          yoyo: true,          repeat: -1,          delay: 1,          repeatDelay: 1,          paused: true,      });        useEffect(() => {          if (isPlaying) {              audioEl.current.play();              radioPlayerGSAP.play();              // radioPlayerGSAP.reversed(4, false);          } else {              audioEl.current.pause();          }      }, [isPlaying]);        return (          <div className="radio-player-nav">              <div className="radio-player-controls">                  <audio src="src/current-radio-mix.mp3" ref={audioEl} preload="auto"></audio>                  <i                      className={isPlaying ? "fas fa-pause cursor-hover" : "fas fa-play cursor-hover"}                      onClick={() => {                          setIsPlaying(!isPlaying);                      }}                  ></i>                  <div className="title">                      <p>MIXED FEELINGS M0001</p>                  </div>                  <a href="src/current-radio-mix.mp3" download="Mixed Feelings M0001">                      <i className="fas fa-download cursor-hover"></i>                  </a>              </div>          </div>      );  }    export default RadioPlayerNav;  

You can find the full github repo for the project here: https://github.com/nallstott/mixed-feelings/tree/master

Apache Atlas server not running,for check the reason 'zookeeper always send error message'

Posted: 09 Jul 2021 09:02 AM PDT

I am new for Atlas and had try to install it for 3 days.It's to hard for to install. So can anyone help me solve this question,thanks all.

    WARN  - 2021-02-02 07:49:29.543; [   ] org.apache.zookeeper.ClientCnxn$SendThread; Session 0x200ad9fa8f00005 for server null, unexpected error, closing socket connection and attempting reconnect  java.net.ConnectException: Connection refused          at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)          at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:714)          at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:361)          at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1081)         ERROR - 2021-02-02 07:54:26.835; [   ] org.apache.zookeeper.ClientCnxn$EventThread; Error while calling watcher  java.util.concurrent.RejectedExecutionException: Task org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor$1@5527a145 rejected from org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor@10ea4804[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 21]          at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)          at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)          at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)          at org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor.execute(ExecutorUtil.java:135)          at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)          at org.apache.solr.common.cloud.SolrZkClient$3.process(SolrZkClient.java:261)          at org.apache.zookeeper.ClientCnxn$EventThread.processEvent(ClientCnxn.java:522)          at org.apache.zookeeper.ClientCnxn$EventThread.run(ClientCnxn.java:498)  

Atlas docReturned 1 for paginated queries

Posted: 09 Jul 2021 09:03 AM PDT

we are using spring with mongoDB (atlas) and recently got alerts about the ratio of scanned documents/docs returned.

on the profiler all of our queries ends with docReturned=1 while we defintly get more then 1 document, we prints it in the logs. any chance on paginated queries where we use PageRequest(0,X) Atlas refers to 1 as the page and not the documents?

should we just quite this alert?

Connect to MongoDB atlas cluster with flask-mongoengine

Posted: 09 Jul 2021 09:03 AM PDT

I am trying to connect with mongodb atlas from my flask app using flask-mongoengine.

DB_URI =  "mongodb+srv://flask_app_user:flask_app_user@cluster0.6jwadcx5g.mongodb.net/flask_app?retryWrites=true&w=majority"    def create_app():      app = Flask(__name__)      app.secret_key = os.environ.get('SECRET_KEY', 'replace_me_32437264278642')      app.config['MONGODB_SETTINGS'] = {          'host': os.environ.get('MONGODB_URI', DB_URI)      }      MongoEngine(app)      socketio.init_app(app)      SSLify(app)        return app  

But I am getting an error,

pymongo.errors.InvalidURI: Invalid URI scheme: URI must begin with 'mongodb://'  

How can I use mongo atlas with flask_mongoengine? I don't want to stick with flask_mongoengine. I don't want to change that.

The meaning of ?retryWrites=true&w=majority when you connect Node.js app to Cluster on MongoDB Atlas

Posted: 09 Jul 2021 09:03 AM PDT

When we connect a Node.js application to a cluster on the mongoDB Atlas, we need to add the following URI instead of adding "mongodb://localhost:27017/<dbname>" as you can see at the step 2 in the image.

"mongodb+srv://<username>:<password>@cluster1.tv7cp.mongodb.net/<dbname>?retryWrites=true&w=majority"  

Now, what exactly the meaning of ?retryWrites=true&w=majority in it after <dbname>? Why do we need to add it?

I tried and ran the app with mongoose without ?retryWrites=true&w=majority, and it worked fine.

enter image description here

No comments:

Post a Comment