Tuesday, March 1, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Page navigation not working properly after used firebase in flutter flash chat app

Posted: 01 Mar 2022 05:09 AM PST

I am learning flutter from Angela Yu. I am the flash chat app and I just integrated firebase. Before that app was working fine and was navigating to next page properly. But after firebase it is not working. Please help I have been looking for solution from two days.enter image description here

Second image is for the code of main.dart

A single linux shell script executes multiple commands, and the commands are written into multiple shell scripts and executed in sequence. Total time

Posted: 01 Mar 2022 05:09 AM PST

I am a linux beginner , I am trying to import and export data using shell script. The data about 60,000,000 rows. When I execute the import and export commands separately from the command line, I find that perform very well. But I merged commands into a single shell script and the performance slowed down, I tried many times and I don't know why.

The following is the information of my test environment

  • System version information

    Operating System: CentOS Linux 7 (Core)       CPE OS Name: cpe:/o:centos:centos:7            Kernel: Linux 3.10.0-1160.25.1.el7.centos.plus.x86_64      Architecture: x86-64  
  • shell script content

Export_from_POSTGRES_lineitem.sh

psql postgres://postgres:rdpadmin@192.168.120.73/sf10 -c  "\copy lineitem to './Export_from_POSTGRES_lineitem.csv' with DELIMITER '|';" 2>&1  

Load_to_MYSQL_lineitem.sh

mysql -h 127.0.0.1 -P 3306 -uroot -prdpuser --database test_db -e "load data local infile './Export_from_POSTGRES_lineitem.csv' into table lineitem fields terminated by '|';" 2>&1  

What I'm doing is exporting a table on a postgres database on another machine to a local csv file and then importing the csv file into my local mysql database. Before executing the export script, I will manually delete the existing local csv file. The csv file exported each time is about 8.6GB. Before importing to mysql, I will use ** TRUNCATE ** to clear the original data in the table. I make sure it's a clean environment before each test.

When I execute the Export script alone, it takes about 4 minutes.

When I execute the Load script alone, it takes about 5 minutes 30 seconds.

I have tested it many times, and the time is only within 20 seconds.

enter image description here

But when I merged the two scripts and executed them, I found that the time consuming increased.

I don't know what caused this, I hope I have described the problem I encountered in detail, and I hope to get your suggestions. If other information is needed, I will give it in time.

How to create a table in BigQuery from an existing table structure using Java?

Posted: 01 Mar 2022 05:08 AM PST

I would like to know how to create a BigQuery table via Java with a known table structure obtained from an already existing table in my BigQuery. This requirement is similar to the following SQL statement:

create table `deom.hezuo.device_20220301` like `deom.hezuo.device_20220228`;  

That is, create a new table deom.hezuo.device_20220301 according to the structure and index of deom.hezuo.device_20220228. I would like to know how to do it using Java program? The method used in the JDK currently found is like this, but it requires me to manually fill in the fields of the table structure, which is very troublesome.

BigQuery bigQuery = getBigQuery();      String datasetName = "hezuo";      String tableName = "device_20220227";      TableId tableId = TableId.of(datasetName, tableName);      TableDefinition tableDefinition = StandardTableDefinition.newBuilder().build();      TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();      Table table = bigQuery.create(tableInfo);  

Or is there a way to directly execute the SQL statement for creating a table on BigQuery through Java?

Manipulação de arquivos CSV

Posted: 01 Mar 2022 05:08 AM PST

tudo na paz?

Estou tentando há alguns dias resolver um problema, porém, sem sucesso. Eu tenho um arquivo CSV, no qual tem os seguintes campos: (nome, email, cpf, celular, idade, data_nascimento, data_cadastro). Eu consegui usando NodeJS, fazer com que esses campos apareçam pra mim, por meio que deixarei abaixo. Mas o que preciso e não consigo achar em lugar nenhum, pesquisando em tudo que é site, é como eu vou validar esses campos, e pra ser bem específico, vou deixar três exemplos do que eu tento: Nome: No máximo 25 caracteres (passado isso, apresentará uma mensagem de erro ao usuário); E-mail: no estilo a.a@a.a; CPF: formato "(xx) xxxxx-xxxx"; Se alguém puder me ajudar, eu juro que serei eternamente grato. Meu código atualmente:

const csv = require('csv-parser'); const fs = require('fs'); const results = [];

fs.createReadStream('cadastros.csv') .pipe(csv({})) .on('data', (data) => results.push(data)) .on('end', () => { console.log(results); });

Android studio displays error after importing project from other PC

Posted: 01 Mar 2022 05:08 AM PST

recently I've changed my work pc and now I need to import all data from my old pc to the new one. I've encountered problem while trying to export Android Studio project. I exported it as .zip file, transfered to my second pc and oppened it in Android Studio. Now I get error messages in every file, almost everything is marked red. In AndroidManifest.xml :code screenshot errors

In activity_main.xml in Split/Design mode visual representation of layout is infinitely loading and most of the code is marked red: code and layout screenshot

Have I done something wrong or am I missing something? And how to make it work

How to get child text text via script on button?

Posted: 01 Mar 2022 05:08 AM PST

I have a button with a text child object. I have a script on this button. How to get the text of the button's child object through this script?

enter image description here

Here is the script hanging on the button.

using System.Collections;  using System.Collections.Generic;  using UnityEngine;  using UnityEngine.SceneManagement;  using UnityEngine.UI;    public class monumentButtonAppy : MonoBehaviour  {         public void ButtonPressed()      {          // DataHolders.Monument          SceneManager.LoadScene(3);      }  }  

The received text from the button, I need to apply it to the variable "DataHolders.Monument"

How to correclty loop links with Scrapy?

Posted: 01 Mar 2022 05:08 AM PST

I'm using Scrapy and I'm having some problems while loop through a link.

I'm scraping the majority of information from one single page except one which points to another page.

There are 10 articles on each page. For each article I have to get the abstract which is on a second page. The correspondence between articles and abstracts is 1:1.

To do so I have defined the following script

from cgitb import text  import scrapy  import pandas as pd      class QuotesSpider(scrapy.Spider):      name = "jps"        start_urls = ['https://www.tandfonline.com/toc/fjps20/current']              def parse(self, response):          self.logger.info('hello this is my first spider')          Title = response.xpath("//span[@class='hlFld-Title']").extract()          Authors = response.xpath("//span[@class='articleEntryAuthorsLinks']").extract()          License = response.xpath("//span[@class='part-tooltip']").extract()          row_data = zip(Title, Authors, License)                    for quote in row_data:              scraped_info = {                  # key:value                  'Title': quote[0],                  'Authors': quote[1],                  'License': quote[2]              }              # yield/give the scraped info to scrapy              yield scraped_info                        for abstract_url in response.xpath("//a[@class='tocArticleLink']/@href").extract():              yield scrapy.Request(response.urljoin(abstract_url), callback=self.parse_abstract)              #abstract_url = response.xpath('//*[@class="tocDeliverFormatsLinks"]/a/@href').extract_first()              self.logger.info('get abstract page url')              yield response.follow(abstract_url, callback=self.parse_abstract)      def parse_abstract(self, response):          Abstract = response.xpath("//div[@class='hlFld-Abstract']").extract()          row_data = zip(Abstract)          for quote in row_data:              scraped_info = {                  # key:value                  'Abstract': quote[0]              }              # yield/give the scraped info to scrapy              yield scraped_info  

Authors, title and license are correctly scraped, Abstract is not scraper at all.

To check if the path was correct I removed the abstract_url from the loop:

 abstract_url = response.xpath('// [@class="tocDeliverFormatsLinks"]/a/@href').extract_first()   self.logger.info('get abstract page url')   yield response.follow(abstract_url, callback=self.parse_abstract)  

I can correctly reach the abstract corresponding to the first article, but not the others. I think the error is in the loop.

How can I solve this issue?

Thanks

How to hide "Open report in Google Data Studio" URL from website using some JS on IFrame

Posted: 01 Mar 2022 05:08 AM PST

How to hide "Open report in Google Data Studio" URL from wordpress website using some JS on IFrame I have google dashboard Iframe data but I need to hide all URL's and unable to open this report from IFrame dialog Image

Call a function passed in parameter that contains calls to private methods

Posted: 01 Mar 2022 05:08 AM PST

I have a function exported from a library. This function take an other function as parameter.

The function provided in parameter is defined in a class and it calls protected method. The issue I'm facing is that the protected/private methods are not found from the provided context.

Example :

// Exported module  export function SuperFunction(thisArgs: any, myFunc: () => any) {      myFunc.apply(thisArgs);  }    // A service  export class MyService {      private _foo() {}       execute() { this._foo(); }  }      // Another class  export class AnotherClass {      constructor(private myService: MyService) {}     execute() {         SuperFunction(this, this.myService); // Error _foo is not a function     }  }  

how to efficiently rename a lot of blobs in GCS

Posted: 01 Mar 2022 05:08 AM PST

Lets say that on Google Cloud Storage I have bucket: bucket1 and inside this bucket I have thousands of blobs I want to rename in this way: Original blob: bucket1/subfolder1/subfolder2/data_filename.csv to: bucket1/subfolder1/subfolder2/data_filename/data_filename_backup.csv

subfolder1, subfolder2 and data_filename.csv - they can have different names, however the way to change names of all blobs is as above. What is the most efficient way to do this? Can I use Python for that?

How to handle relative generic types in java?

Posted: 01 Mar 2022 05:08 AM PST

I'm writing a common abstract class for parsing configs, to adapt different config types, I use generic type to handle this problem, see the following code:

public class Tests {        @Test      public void test() {          TestResponse r = readJsonFile("config.json", TestResponse.class);          System.out.println(r);      }        public static class AbstractResponse<G extends AbstractResponse.BaseGItem<M>, M> {            private List<Item<G, M>> data;            public List<Item<G, M>> getData() {              return this.data;          }            public void setData(List<Item<G, M>> data) {              this.data = data;          }            public static class Item<G extends AbstractResponse.BaseGItem<M>, M> {                private int gId;                private int gGroupId;                private String gTitle;                private String gStyle;                private boolean gUseTab;                private List<G> gItems;                public int getgId() {                  return gId;              }                public void setgId(int gId) {                  this.gId = gId;              }                public int getgGroupId() {                  return gGroupId;              }                public void setgGroupId(int gGroupId) {                  this.gGroupId = gGroupId;              }                public String getgTitle() {                  return gTitle;              }                public void setgTitle(String gTitle) {                  this.gTitle = gTitle;              }                public String getgStyle() {                  return gStyle;              }                public void setgStyle(String gStyle) {                  this.gStyle = gStyle;              }                public boolean isgUseTab() {                  return gUseTab;              }                public void setgUseTab(boolean gUseTab) {                  this.gUseTab = gUseTab;              }                public List<G> getgItems() {                  return gItems;              }                public void setgItems(List<G> gItems) {                  this.gItems = gItems;              }          }            public static class BaseGItem<MItem> {                private int mId;                private int mType;                private String mTitle;                private int mIndex;                private int mTplId;                private List<MItem> mItems;                public int getmId() {                  return mId;              }                public int getmType() {                  return mType;              }                public String getmTitle() {                  return mTitle;              }                public int getmIndex() {                  return mIndex;              }                public int getmTplId() {                  return mTplId;              }                public List<MItem> getmItems() {                  return mItems;              }          }      }        public static class TestResponse              extends AbstractResponse<TestResponse.GItem, TestResponse.MItem> {            public static class GItem extends AbstractResponse.BaseGItem<MItem> {          }            public static class MItem {              private String adMainTitle;              private String adImgUrl;              private String adAppLinkUrl;                public String getAdMainTitle() {                  return adMainTitle;              }                public void setAdMainTitle(String adMainTitle) {                  this.adMainTitle = adMainTitle;              }                public String getAdImgUrl() {                  return adImgUrl;              }                public void setAdImgUrl(String adImgUrl) {                  this.adImgUrl = adImgUrl;              }                public String getAdAppLinkUrl() {                  return adAppLinkUrl;              }                public void setAdAppLinkUrl(String adAppLinkUrl) {                  this.adAppLinkUrl = adAppLinkUrl;              }          }      }  }  

When I parse json, I get the following error:

org.codehaus.jackson.map.JsonMappingException: Type variable 'M' can not be resolved (with context of class xxx.Tests$AbstractResponse$Item)

I know in Item class, the generic type G not bind with M, How can I solve this problem??

example config.json:

{    "msg": "success",    "data": [      {        "gStyle": "xxx",        "gId": "100",        "gTitle": "test",        "gItems": [          {            "mItems": [              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              }            ],            "mTitle": "",            "mTplId": ""          },          {            "mItems": [              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              },              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              }            ]          }        ]      },      {        "gStyle": "",        "gId": "90",        "gTitle": "test2",        "gItems": [          {            "mItems": [              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              }            ],            "mTitle": "标题",            "mTplId": "2370"          },          {            "mItems": [              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              },              {                "adAppLinkUrl": "",                "adImgUrl": "",                "adMainTitle": ""              }            ],            "mTitle": "品类入口",            "mTplId": "2371"          }        ]      }    ],    "success": true,    "errorCode": 610000  }  

Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic>' in type cast

Posted: 01 Mar 2022 05:07 AM PST

I'm pretty new to Flutter and struggling to parse a JSON data of type Map which is as below. Everytime I try fetching the data and storing it, I keep getting Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic>' in type cast

{      "status": "success",      "data": [          {              "product_id": 10,              "restaurant_name": "new restaurant5",              "product_name": "Test Product new 2",              "product_desciption": "A cool new test product new 2",              "product_image": null,              "product_selling_price": "450",              "product_status": "active",              "product_quantity": "500",              "product_rating": null,              "product_rating_count": null,              "product_sell_count": null          },          {              "product_id": 9,              "restaurant_name": "new restaurant5",              "product_name": "Test Product new 1",              "product_desciption": "A cool new test product new",              "product_image": null,              "product_selling_price": "400",              "product_status": "active",              "product_quantity": "100",              "product_rating": null,              "product_rating_count": null,              "product_sell_count": null          },          {              "product_id": 8,              "restaurant_name": "new restaurant5",              "product_name": "Test Product new",              "product_desciption": "A cool new test product new",              "product_image": null,              "product_selling_price": "350",              "product_status": "active",              "product_quantity": "1000",              "product_rating": null,              "product_rating_count": null,              "product_sell_count": null          },  }  

I have used used Quicktype.io to generate the Model Class from JSON to dart which is as follows:

Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));    String welcomeToJson(Welcome data) => json.encode(data.toJson());    class Welcome {    Welcome({      required this.status,      required this.data,    });      String status;    List<Datum> data;      factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(          status: json["status"],          data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),        );      Map<String, dynamic> toJson() => {          "status": status,          "data": List<dynamic>.from(data.map((x) => x.toJson())),        };  }    class Datum {    Datum({      required this.productId,      required this.restaurantName,      required this.productName,      required this.productDesciption,      required this.productImage,      required this.productSellingPrice,      required this.productStatus,      required this.productQuantity,      required this.productRating,      required this.productRatingCount,      required this.productSellCount,    });      int productId;    RestaurantName? restaurantName;    String productName;    String productDesciption;    String productImage;    String productSellingPrice;    ProductStatus? productStatus;    String productQuantity;    dynamic productRating;    dynamic productRatingCount;    dynamic productSellCount;      factory Datum.fromJson(Map<String, dynamic> json) => Datum(          productId: json["product_id"],          restaurantName: restaurantNameValues.map[json["restaurant_name"]],          productName: json["product_name"],          productDesciption: json["product_desciption"],          productImage:              json["product_image"] == null ? null : json["product_image"],          productSellingPrice: json["product_selling_price"],          productStatus: productStatusValues.map[json["product_status"]],          productQuantity:              json["product_quantity"] == null ? null : json["product_quantity"],          productRating: json["product_rating"],          productRatingCount: json["product_rating_count"],          productSellCount: json["product_sell_count"],        );      Map<String, dynamic> toJson() => {          "product_id": productId,          "restaurant_name": restaurantNameValues.reverse![restaurantName],          "product_name": productName,          "product_desciption": productDesciption,          "product_image": productImage == null ? null : productImage,          "product_selling_price": productSellingPrice,          "product_status": productStatusValues.reverse![productStatus],          "product_quantity": productQuantity == null ? null : productQuantity,          "product_rating": productRating,          "product_rating_count": productRatingCount,          "product_sell_count": productSellCount,        };  }    enum ProductStatus { ACTIVE }    final productStatusValues = EnumValues({"active": ProductStatus.ACTIVE});    enum RestaurantName { NEW_RESTAURANT5, RESTAURANR_2 }    final restaurantNameValues = EnumValues({    "new restaurant5": RestaurantName.NEW_RESTAURANT5,    "Restauranr 2": RestaurantName.RESTAURANR_2  });    class EnumValues<T> {    Map<String, T> map;    Map<T, String>? reverseMap;      EnumValues(this.map);      Map<T, String>? get reverse {      if (reverseMap == null) {        reverseMap = map.map((k, v) => new MapEntry(v, k));      }      return reverseMap;    }  }  

This is the class from which I'm making the API Call:

import 'package:http/http.dart' as http;  import './providerModel.dart';    class ApiProvider with ChangeNotifier {    Map<String, dynamic> _result = {};      Future<void> fetchProduct() async {      final url = Uri.https('achievexsolutions.in', '/etiano/api/all_products');      final response = await http.get(url);      print(response);      Welcome data = welcomeFromJson(response.body);     //This is probably where the error gets thrown`enter code here`      print(data);      _result = data as Map<String, dynamic>;      print(_result);    }  }  

Replacement of WebBrowser1 events in WebView2

Posted: 01 Mar 2022 05:07 AM PST

I wanted to move to WebView2 Web Control from WebBrowser2 as the IE is being deprecated. These the some events for which I was facing difficulty to find replacements:

  1. StatusTextChange
  2. BeforeNavigate2
  3. DocumentComplete
  4. WindowClosing
  5. NavigateComplete2

I am using RC6.dll for integration of Edge in VB6 code. If anyone finds anything please reply.

Flutter oAuth2 login with discord. Error with redirect URI

Posted: 01 Mar 2022 05:07 AM PST

I'm looking to make a button login with discord. For that I use flutter_web_auth but discord shows me an error with the redirect URI.

Invalid OAuth2 redirect_uri

Redirect URI is not supported by client

config discord

I set up flutter_web_auth as requested:

AndroidManifest.xml

       <activity android:name="com.linusu.flutter_web_auth.CallbackActivity" >             <intent-filter android:label="flutter_web_auth">                 <action android:name="android.intent.action.VIEW" />                 <category android:name="android.intent.category.DEFAULT" />                 <category android:name="android.intent.category.BROWSABLE" />                 <data android:scheme="com.area" />             </intent-filter>         </activity>  

function

void loginWithDiscord() async {    // App specific variables        const clientId = 'myClientId' ;      const callbackUrlScheme = 'com.area';      const redirectUri = 'com.area://home'; // OR 'com.area:/';    // Construct the url        final url = Uri.https('discord.com', '/api/oauth2/authorize', {        'response_type': 'code',        'client_id': clientId,        'redirect_uri': redirectUri,        'scope': 'identify',      });    // Present the dialog to the user        final result = await FlutterWebAuth.authenticate(          url: url.toString(), callbackUrlScheme: callbackUrlScheme);    // Extract code from resulting url        final code = Uri.parse(result).queryParameters['code'];    // Use this code to get an access token        final response = await http          .post(Uri.parse('https://discord.com/api/oauth2/authorize'), body: {        'client_id': clientId,        'redirect_uri': redirectUri,        'grant_type': 'authorization_code',        'code': code,      });    // Get the access token from the response        final accessToken = jsonDecode(response.body)['access_token'] as String;      print(accessToken);    }  

Removing certain strings from a file. Jpeg All jpegs

Posted: 01 Mar 2022 05:07 AM PST

I was wondering if you guy could help. I am using a Debian 9

I need to rename all jpegs in a folder, all my jpegs are like this image_E01760728_20220301122915852_TIMING.jpg to this 20220301122915.jpg (removing image_E10176072_ & _TIMING & removing last three characters . The string 20220301122915852 is a date, month, hour, min, seconds etc capture time.

So basically my timelapse system would see pictures like this; 20220301122915.jpg

Thank you in advance

Having some trouble filtering an array to match data and return new array

Posted: 01 Mar 2022 05:09 AM PST

I have an array of applications.

var applications = [{applicationStatus: {code: 100}}, {applicationStatus: {code: 100}}, {applicationStatus: {code: 130}}, {applicationStatus: {code: 150}}, {applicationStatus: {code: 170}},{applicationStatus: {code: 170}}];  

I also have an array of statuses

var applicableStatuses = [20, 50, 100, 170];  

I'd like to loop through my array of applications and return a new array containing only the applications containing applications matching applicationStatus.code from my applicableStatuses array. I'd tried a few ways but I'm not getting a new array with the correct data. Can someone steer me the right way?

SQL Server - How to remove all letters at the beginning of the string?

Posted: 01 Mar 2022 05:07 AM PST

I'm trying to remove the letters from the beginning of the string only from the dbo.ProductCodes table.

I have:

| ProductCode |  | -------------- |  | **XXX**8361229**BB** |  | **XY**0060482**AB** |  | **CR**0058882**A**1 |  | **CPR**777093219 |  | **CPCODE**0002835|  

I want:

| ProductCode |   | ------------- |   | 8361229**BB** |  | 0060482**AB** |  | 0058882**A**1 |  | 777093219 |  | 0002835 |  

If the letters were only at the beginning of the string, I could remove all letters using regex [^a-zA-z]. The problem is that letters appear not only at the beginning of the string.

Why does my axios request print in console but doesn't set state

Posted: 01 Mar 2022 05:09 AM PST

I'm trying to display some data from my database in my React component but the data isn't getting saved in the state hook, but the request's response does print in the console.

How can I fix this?

const [error, setError] = useState(null);  const [isLoaded, setIsLoaded] = useState(false);  const [collections, setCollections] = useState([]);    useEffect(() => {    const getCollections = async () => {      try {        const response = await axios.get('http://localhost:4000/api/collections');        setIsLoaded(true);          console.log(response); // This prints the response        setCollections(response);        console.log(collections); // This prints []        } catch (error) {        setError(error);        setIsLoaded(true);      }    }      getCollections();  }, [])  

Console logs

Im trying to create a line graph in R using ggplot

Posted: 01 Mar 2022 05:08 AM PST

I am new to R and programming in general, I have a data frame similar to this but with a lot more rows:

yes_no <- c('Yes','No','No','Yes','Yes','No','No','No','Yes','Yes','No','Yes','No','Yes','No','Yes','No','Yes','No','Yes')  age <- c('1','1','2','3','4','5','1','2','2','3','1','5','5','5','1','4','4','2','5','3')    data<- data.frame(yes_no,age)  

I am trying to create a line graph using ggplot where the x-axis is the age and the y axis is the percentage of yes for a specific age.

I am not too sure how to create the percentage

any advice? thank you!

Getting all the POJO items that match max value of a POJO variable

Posted: 01 Mar 2022 05:09 AM PST

I have a POJO class from which I want to collect all the POJO objects that matches the max value of a given POJO variable.

I have the below POJO class

@Data  @AllArgsConstructor  @NoArgsConstructor  public class IPTraceData implements Serializable {        private String factId;      private long startIp;      private long endIp;      private int confidence;      private LocalDate date;      private long ipaddr;  }  

I want to get all the POJO object which match with the max value of confidence variable.

I am able to get the results using the below code in Java 8.

int max = allTraces.stream()              .max(Comparator.comparing(IPTraceData::getConfidence))              .get()              .getConfidence();    List<IPTraceData> traceData = allTraces              .stream()              .filter(m -> m.getConfidence() == max)              .collect(Collectors.toList());  

However, I am trying to write a code in Java 8 using a single stream statement. How can I achieve the same using the single stream statement?

Flutter add dash after every 3 number textfield input and limit number of figure input

Posted: 01 Mar 2022 05:07 AM PST

I'm looking for a way to add ( - ) after every number input in flutter textformfield and to limit the number of input to just 9 figure. For example 145-123-234. I will appreciate if anyone can help with this.

Create an array of numbers like Faculty

Posted: 01 Mar 2022 05:09 AM PST

I want to build up an function where it checks which numbers are reachable... like

const number = 720  let arrayNumbers = []  let count = 30    arrayNumbers = arrayNumbers / 30     arrayNumbers is equal then to [24]  

But I want to have it like

[30, 60, 90, 120 ...]  

like an incrementing array.

Does anybody have a clue how I can reach this?

Loading built-in Python Wrappers in TensorFlow

Posted: 01 Mar 2022 05:07 AM PST

I'm trying to understand the complete process of exposing the built-in low-level C++ implementations to the Python API in TensorFlow. I've been looking at the source code, and I think I get the big picture, however, there is a step where I get stuck. Here what I made out so far:

(1) TensorFlow uses SWIG to automatically generate Python Wrappers given interface files.

(2) Bazel is used to compile the Python Wrappers into .so libraries

I can't figure out Step (3) which is how/where the .so libraries get loaded into the tensorflow framework so that it is possible to do from tensorflow.python.ops import gen_math_ops in math_ops.py for example.

Appreciate the hints!

Specify the consecutive values (zeros) and remove them but only if they are consecutive

Posted: 01 Mar 2022 05:07 AM PST

I have this list of values:

A = [0,0,1,2,3,4,5,6,0,6,6,8,8,0,0,2,3,4,5,12,45,-0,-0,-9,-2,3,-0,-2,-2,-2]

I want to get this list of values for the output :

A = [1,2,3,4,5,6,0,6,6,8,8,2,3,4,5,12,45,-9,-2,3,-0,-2,-2,-2]

Basically, I want to drop the consecutive zeros only, and keep all the other values.

Do you have any idea on how i can do that ? I tried this one but i know there will be in index error :

X = []  for j in range(len(A)):      if A[j] != 0 and A[j+1] != 0:          X.append(A[j])      else:          print('lol')  print(X)```  

How to trigger select element manually?

Posted: 01 Mar 2022 05:08 AM PST

How can I get the "select" element to open and show its option elements when I click inside "div" element? In other words, I want to trigger the "select" element when I click to green zone.

HTML

<div>    <h3>Cities</h3>    <select>      <option>Berlin</option>      <option>Paris</option>      <option>London</option>    </select>  </div>  

SCSS

body{    background-color: lightgray;    margin: 100px;          div{      display: inline-block;      padding: 50px;      background-color: green;        select{        width:300px;          &:focus{          outline: none;        }      }    }  }  

https://codepen.io/mehmetguduk/pen/vYWVGPK

How to find the value of a cell in another tab based on cell criteria

Posted: 01 Mar 2022 05:09 AM PST

I have a Wholesale market price in a list on a sheet called 'DataBank' Name of the product is column W & Price in column X

In a seperate tab called 'Position Activity' I have a drop down list in column AL based on the values of column W of the 'DataBank' sheet

When selecting the product in the dropdown list I would like the corresponding price to populate the cell next to the drop down list in column AK

Is there any help on offer for this? ideally in a script.

Thanks in advance.

R function for performing mean numb max and sum

Posted: 01 Mar 2022 05:08 AM PST

I have duration in the research and I need to mean max sum and number of duration. In library dplyr, it do not run mean and numb. summerise shows max and sum duration but can't read mean and number. There are 3 column TRT is pre, dur and post , birds and 2 pen. duration-sec is the time spend time for activity NBU.

# create a paired structure  library(dplyr)    my_new_data <- my_data.1 %>%    filter(dropout!=1)%>%    group_by(Bird,PEN,TRT) %>%    men_dur= mean(my_data.1$Duration_sec, na.rm=TRUE)  men1_dur= men_dur  summarize(men_dur)  my_datamen <- my_new_data    View(my_datamen)      my_new_data <- my_data.1 %>%   filter(dropout!=1)%>%    group_by(Bird,PEN,TRT) %>%    numb_dur = count(my_data.1$Duration_sec, na.rm = TRUE)    summarise(numb_dur)  my_datanumb <- my_new_data    View(my_datanumb)    plot(my_new_data$numb_dur ~ my_datamen$men_dur)  pdf("NumbMean.pdf",width = 20 ,height = 20, bg="white",colormodel = "cmyk",paper = "A4")     my_new_data <- my_data.1 %>%    filter(dropout!=1)%>%   group_by(Bird, PEN,TRT) %>%   summarise(sum_dur = sum(my_new_data$Duration_sec, na.rm = TRUE))   my_datasum<-my_new_data   View(my_datasum)      (my_new_data$sum_dur/54000)*100    summary(my_new_data)  my_new_data <- my_data.1 %>%    filter(dropout!=1)%>%    group_by(Bird,PEN,TRT) %>%  summarise(max_dur = max(my_new_data$Duration_sec, na.rm = TRUE))      View(my_new_data)     my_new_data <- my_data.1 %>%    filter(dropout!=1)%>%filter(PEN=="3")%>%mutate(time = as.POSIXct(hms::parse_hm(NBU.S)))  ggplot(my_new_data) +    geom_point(aes(x = as.numeric(time), y = Duration_sec),size=3) +    geom_line(aes(x  = as.numeric(time), y = Duration_sec),size=1.2)+    facet_grid(vars(Bird),vars(TRT))  ggsave("BirdTRTplot.pdf", width = 20 , height = 20, units = "cm")  ggplot(my_new_data) +    geom_point(aes(x = as.numeric(TRT), y = max_dur,group = Bird),size=3) +    geom_line(aes(x  = as.numeric(TRT), y = max_dur, group = Bird,col = Bird),size=1.2) +    scale_x_continuous(breaks = c(1,2,3), labels = c("pre", "dur","post"))+    labs(x= "condition",y= "mean duration spent NBU [sec]",size=1)+    facet_grid(.~PEN)  

Automator/Apple Script: Move files with same prefix on a new folder. The folder name must be the files prefix

Posted: 01 Mar 2022 05:09 AM PST

I'm a photographer and I have multiple jpg files of clothings in one folder. The files name structure is:

TYPE_FABRIC_COLOR (Example: BU23W02CA_CNU_RED, BU23W02CA_CNU_BLUE, BU23W23MG_LINO_WHITE)

I have to move files of same TYPE (BU23W02CA) on one folder named as TYPE.

For example:

MAIN FOLDER>

BU23W02CA_CNU_RED.jpg, BU23W02CA_CNU_BLUE.jpg, BU23W23MG_LINO_WHITE.jpg

Became:

MAIN FOLDER>

BU23W02CA_CNU > BU23W02CA_CNU_RED.jpg, BU23W02CA_CNU_BLUE.jpg

BU23W23MG_LINO > BU23W23MG_LINO_WHITE.jpg

Suppress security on localhost connection between Microsoft SQLServer VisualStudio 2022

Posted: 01 Mar 2022 05:09 AM PST

I got the following message

Microsoft.Data.SqlClient.SqlException HResult=0x80131904 Message=A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate c hain was issued by an authority that is not trusted.) Source=Core Microsoft SqlClient Data Provider

when establishing a connection to my local Microsoft SQL Server

My connection string is defined in appsettings.json

{      "ConnectionStrings": {          "DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=QandA;Trusted_Connection=True;",      },     "Logging": {        "LogLevel": {           "Default": "Information",           "Microsoft.AspNetCore": "Warning"        }     },     "AllowedHosts": "*"  }  

in Program.cs, the following code that use DbUp work

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");   EnsureDatabase.For.SqlDatabase(connectionString);  var upgrader = DeployChanges.To      .SqlDatabase(connectionString, null)      .WithScriptsEmbeddedInAssembly(System.Reflection.Assembly.GetExecutingAssembly())      .WithTransaction()      .Build();  

The API code call the following function

   /// <summary>     /// Fetch toutes les questions de la BD.     /// </summary>     /// <returns>Les questions de la BD.</returns>     public IEnumerable<QuestionGetManyResponse> GetQuestions()     {          // Le using va disposer de la connection automatiquement en quittant le block.          using (var connection = new SqlConnection(_connectionString))              {                 connection.Open();                 return connection.Query<QuestionGetManyResponse>(@"EXEC dbo.Question_GetMany");              }     }  

The _connectionString variable is set in the class constructor. It is properly set when connection.Open() is executed.

How could I remove the security on that connection and why is it working in Program.cs

Regex in Aggregation not returning documents in right order

Posted: 01 Mar 2022 05:08 AM PST

I am using the aggregation below to search user by user_name and full_name fields.

[{        $match: {          $or: [            {              user_name: {                $regex: q.trim(),                $options: 'i',              },            },            {              full_name: {                $regex: q.trim(),                $options: 'i',              },            },          ],          initialized: true,          _id: {            $nin: [userId, ...blockedUsers],          },        },      }]  

The result for the above query with q='s' is:

[  {    "_id": "62073c243c74c43befc9249f",    "user_name": "carolina",    "full_name": "Caroline Forbes",    "initialized":true    },  {    "_id": "62073d0a3c74c43befc924e9",    "user_name": "stefan",    "full_name": "Stefan",    "initialized":true  },  {    "_id": "62073d0a3c74c43befc924e9",    "user_name": "steve",    "full_name": "Steve",    "initialized":true  }  ]  

As you see the order in which documents are coming is not correct carolina should be below stefan and steve Working example: https://mongoplayground.net/p/RPL_4mpe1DS

No comments:

Post a Comment