Wednesday, April 21, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


EditButton() in SwiftUI doesn't trigger EditMode

Posted: 21 Apr 2021 09:21 AM PDT

It seems like the EditButton() in SwiftUI (Xcode 12.5 beta 3) has various issues.

In my code, everything was working fine until I replaced the List with a ScrollView and added a LazyVGrid. Now, when a user taps on the EditButton, EditMode is not activated.

Any ideas for a workaround? Having 2 columns is a requirement of the UI, and while I could work with a list I prefer the look of ScrollView. I've tried numerous things... putting the ForEach in a Section and putting the EditButton in the header, replacing it with a manual button... unfortunately none of them seem to work :-(

Many thanks for any thoughts or anything anyone else has done to get round this.

struct Home: View {      @Environment(\.managedObjectContext) private var viewContext      @FetchRequest(entity: Cars.entity(), sortDescriptors: []) var cars: FetchedResults<Cars>            private var columns: [GridItem] = [              GridItem(.flexible()),              GridItem(.flexible())          ]        var body: some View {              NavigationView {              ScrollView {                    if cars.count > 0 {                      LazyVGrid(                          columns: columns) {                                    ForEach(cars) { n in                      Text("hello")                  }                  .onDelete(perform: deleteCars)                      }                      }                                    else {                      Text("You have no cars.")                  }                 }               .navigationBarItems(leading: EditButton())                 }         }            func deleteCars(at offsets: IndexSet) {          for offset in offsets {              let cars = cars[offset]              viewContext.delete(cars)          }          try? viewContext.save()      }        }  

Google Sheets Query - Issue grouping rows into the header row

Posted: 21 Apr 2021 09:21 AM PDT

Whenever I query a large amount of data, it bunches up several rows into the header row row.

I've tried =QUERY('Keywords-Raw'!A:O,"SELECT A,B,G,L,O WHERE L MATCHES '"&A1&"'",1) which removes the header, but I need the header.

I've also tried =QUERY('Keywords-Raw'!A:O,"SELECT A,B,G,L,O WHERE L MATCHES '"&A1&"' OFFSET 1"), but this only skips a row that I'll need. enter image description here Does anyone have any ideas?

Socket.io connection to different mySQL tables, Angular front end

Posted: 21 Apr 2021 09:21 AM PDT

I have an angular app that displays a table of data (mySQL database) and updates whenever anything is added to the database. I feel that I should add I'm very inexperienced, i know angular but trying to learn more about backened operations.

I'm using a websocket (socket.io) on a node.js server to achieve this. It works fine but I'd like to add a second unrelated table of data that will appear in a different part of my app. . Should I set up another websocket to achieve this? Or can one websocket interact with 2 different table in the one database.

All of the SQL queries are handled in the backend and look like this.

// Create MySQLEvents      const instance = new MySQLEvents(connection, {          startAtEnd: true  // to record only new binary logs      });    await instance.start();    instance.addTrigger({      name: 'Monitor all SQL Statements',      expression: 'mydb.*',  // listen to database      statement: MySQLEvents.STATEMENTS.ALL,      onEvent: e => {          currentData = e.affectedRows;            let newData;            switch (e.type) {  case "INSERT":                  database.table('products')                      .withFields(['id', 'title', 'quantity', 'price'])                      .sort({id: -1})                      .getAll()                      .then(prods => {                          data = prods;                          io.sockets.emit('update', {prods: [...data]});                      })                      .catch(err => console.log(err));                  .....  

My front end just accepts and displays the incoming data. I'd be unsure of how to add a second socket to it.

Here is my socket.service.ts in angular.

export class SocketService {    constructor(private socket: Socket) { }      getInitialData() {      return this.createObserver('initial');    }      getUpdatedData() {      return this.createObserver('update');    }         private createObserver(event: string) {      return this.socket.fromEvent(event);    }  

and here is the component.ts

export class DashboardComponent implements OnInit, OnDestroy {      private subs: Subscription[] = [];    localData: any[] = [];      constructor(private socketService: SocketService) {    }      ngOnInit() {      this.subs.push(        this.socketService.getInitialData().subscribe((data: ServerResponse) => {          this.localData = data.prods;        })      );          this.subs.push(        this.socketService.getUpdatedData().subscribe((data: ServerResponse) => {          this.localData = data.prods;        })      );    }      ngOnDestroy() {      this.subs.forEach(s => s.unsubscribe());    }        }    interface ServerResponse {    prods: any[];    type?: string;  }  

I just iterate over localData to display the table.

My ideal outcome would be to have the one websocket with multiple endpoints. I just don't know how to handle this with mySQL events.

Similarly if I had 2 completely separate websockets I'm unsure how to handle that on the angular side.

Ive been struggling with this and i do not know where to start

Posted: 21 Apr 2021 09:21 AM PDT

Read the following program named myQuicksort.cpp carefully. The program is to sort and display a random integer array. Implement the missing code as indicated by the comments. Compile and test your program using the command lines below before your submission:

c++ -o myQuicksort myQuicksort.cpp ./myQuicksort n m

Where n is the dimension of the integer array, m is the number of elements displayed per line.

 #include <stdio.h>   #include <cstdlib>   #include <ctime>   #include <iostream>   using namespace std;     class myArray{                 // array class        int *ptr;                     // pointer to body        int size;                     // size of body        void quickSort(int*, int, int);           // quick sort   public:       myArray(int);                  // constructor       ~myArray(){free(ptr);}             // destructor       void sort(){quickSort(ptr, 0, size-1);}        // sort elements       void display(int);                 // display elements   };     // quick sort, to be implemented    void myArray::quickSort(int a[], int l, int r){}     // constructor to create an integer array with random data, data value 0≤v<256, to be implemented   myArray::myArray(int s){}                   // display elements, m elements per line, to be implemented   void myArray::display(int m){}                  int main(int argc, char *argv[]) {         // program entrance              int n=atoi(argv[1]);             // dimension of array         int m=atoi(argv[2]);             // m elements per line         myArray a(n);                    // random integer array         a.display(m);                    // display array elements         a.sort();                        // sort array         a.display(m);                    // display sorted array           return 0;   }  

Why my cgi file is changed upon image build when in /usr/lib/cgi-bi?

Posted: 21 Apr 2021 09:21 AM PDT

I have two containers :

  • "build", that does compile/build my cgi application, along with a linked library (version 1.8), from ubuntu:bionic-20201119
  • "exec", that does run it (and does include the above library as well), still from ubuntu:bionic-20201119

After I launch my "exec" container, I noticed that my cgi fails, because it does miss the above library, but from a previous version :

error while loading shared libraries: libzoo_service.so.1.6: cannot open shared object file: No such file or directory  

while it should be "libzoo_service.so.1.8" : the one that is actually provided, and that was build along with the cgi app.

I was quite puzzled, and thus tried to understand.
When I "ldd" the cgi file from the "build" container, it says :

root@build:/# ldd /usr/lib/cgi-bin/zoo_loader.cgi       linux-vdso.so.1 (0x00007ffe3d56a000)      libzoo_service.so.1.8 => /usr/lib/libzoo_service.so.1.8 (0x00007f2f18186000)   ...  

When I do the same from the "exec" container, I see instead :

root@exec:/# ldd /usr/lib/cgi-bin/zoo_loader.cgi       linux-vdso.so.1 (0x00007fffdf1af000)      libzoo_service.so.1.6 => not found  ...  

And getting better : from the same "exec" container, when I copy the very same cgi file to 2 different paths, I have different results :

root@exec:/# ldd /usr/lib/cgi-bin/zoo_loader.cgi root@10907ce22d0b:/# ldd /usr/lib/cgi-bin/zoo_loader.cgi       linux-vdso.so.1 (0x00007fffdf1af000)      libzoo_service.so.1.6 => not found  ...      root@exec:/# ldd /tmp/cgi-bin/zoo_loader.cgi       linux-vdso.so.1 (0x00007ffe3d56a000)      libzoo_service.so.1.8 => /usr/lib/libzoo_service.so.1.8 (0x00007f2f18186000)  ....  

And the best is that the cgi file under /usr/lib/cgi-bin is half the size of the one from /tmp/cgi-bin, although they were copied from the same file:

FROM ubuntu:bionic-20201119     COPY dist/libzoo_service.so.1.8 /usr/lib/  COPY dist/zoo_loader.cgi /usr/lib/cgi-bin/  COPY dist/zoo_loader.cgi /tmp/cgi-bin/  

So.... I am quite sure this is absolutey legitimate... and that it is about how Ubuntu/Linux do build libraries trees : the facts that only cgi files unders /usr/lib/ are affected sounds a good hint.

But I am not familiar with either cgi or Linux to understand what does happen here... and how I can fix it so my cgi app is actually linked with its matching libzoo_service.so.1.8

Thanks in advance!

Getting a persistent ID for an LLVM BasicBlock

Posted: 21 Apr 2021 09:21 AM PDT

I'm looking for a way -- using the LLVM API -- to obtain an identifier for a BasicBlock which I can use to look up (again via the API) the same block later.

Whatever this ID is, I need it to be "stable over serialisation" (remain valid and refer to the same block after a bitcode serialise/deserialise cycle).

The block ID needn't necessarily be globally unique: if the ID is unique to a function, I can make a globally unique pair by combining the block ID with the function's symbol name.

Candidates:

  • Index of the block in order of iteration (over the parent function's blocks). But is the order of iteration defined and stable over serialisation?
  • The StringRef returned by Node->printAsOperand(). But can I query a function for the block using this as a key, or would I have to do a search with lots of string comparisons? And is this stable over serialisation?
  • Use Block::setName() to assign each block my own ID. This will work, but will bloat the bitcode.

Thank you.

Microsoft VBScript runtime error: Permission denied - pyenv install 3.x.x on Windows 10

Posted: 21 Apr 2021 09:20 AM PDT

I wanted to install a new Python version via pyenv-win, but always get the error mentioned in the title.

The output for two different versions I tried is this (in PowerShell):

PS C:\WINDOWS\system32> pyenv install 3.9.0  :: [Info] ::  Mirror: https://www.python.org/ftp/python  C:\Users\user\.pyenv\pyenv-win\libexec\pyenv-install.vbs(0, 1) Microsoft VBScript runtime error: Permission denied    PS C:\WINDOWS\system32> pyenv install 3.8.0  :: [Info] ::  Mirror: https://www.python.org/ftp/python  :: [Downloading] ::  3.8.0 ...  :: [Downloading] ::  From https://www.python.org/ftp/python/3.8.0/python-3.8.0-amd64-webinstall.exe  :: [Downloading] ::  To   C:\Users\user\.pyenv\pyenv-win\install_cache\python-3.8.0-amd64-webinstall.exe  :: [Installing] ::  3.8.0 ...  :: [Info] :: completed! 3.8.0  C:\Users\user\.pyenv\pyenv-win\libexec\pyenv-install.vbs(0, 1) Microsoft VBScript runtime error: Permission denied  

Earlier, this was not a problem. I even tried with started the PowerShell with admin-rights, still not working.

Not able to catch error in plyer notification

Posted: 21 Apr 2021 09:20 AM PDT

I am not able to catch errors produced when I provide the wrong directory path to the icon.

try:      from plyer import notification  except Exception as e:      print(e)    def notify(title, message, app_icon, timeout=4):      try:          notification.notify(              title=title,              message=message,              app_icon=app_icon,              timeout=timeout,              toast=False          )      except Exception as e:          print(e)    try:      notify("Error",'Error-description','dir/img.ico',8)  except Exception as e:      print(e)  

by producing the error :

Exception in thread Thread-1:  Traceback (most recent call last):    File "C:\Users\prana\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner      self.run()    File "C:\Users\prana\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run      self._target(*self._args, **self._kwargs)    File "C:\Users\prana\AppData\Local\Programs\Python\Python39\lib\site-packages\plyer\platforms\win\libs\balloontip.py", line 206, in balloon_tip      WindowsBalloonTip(**kwargs)    File "C:\Users\prana\AppData\Local\Programs\Python\Python39\lib\site-packages\plyer\platforms\win\libs\balloontip.py", line 130, in __init__      raise Exception('Could not load icon {}'.format(app_icon))  Exception: Could not load icon dir/img.ico  

This produces error and program quits and is not caught by 'try except' block

How to catch it?

How to Fix php Array to string converions

Posted: 21 Apr 2021 09:20 AM PDT

I am using a 2008 php program to take an image, annotate it and create a thumbnail of the image.

The program works but throws a notice of an Array to String conversion.

The relevant code is:

 $ttfont = 'Arial.TTF';  if ($ttfont != '') {     # using ttf fonts     $alpha   = range("a", "z");     $alpha_u = range("A", "Z");     $alpha = $alpha.$alpha_u.range(0, 9);     //print_r($alpha);     $_b = imageTTFBbox($fontsize,0,$ttfont,$alpha);     //print_r($_b);     $fontheight = abs($_b[7]-$_b[1]);  } else {  

The error is in the $alpha = $alpha.$alpha_u.range(0, 9); line.

The print_rs are my debugging attempts.

I hate having any notices or warnings in my code and would sure appreciate any suggestions for a fix.

Thanks.

I need (help) with python I'm a beginner I wanted to create an input system [duplicate]

Posted: 21 Apr 2021 09:20 AM PDT

name = input("Enter:")        if name == ("bin", "flex", "axe"):      print("leave!")  

This script doesn't print "leave" when I enter the name's in input

How to loop through $request and extract specific parameters

Posted: 21 Apr 2021 09:21 AM PDT

This is a screenshot dd($request) it contains alot information. I'd like to extract just the #parameter: array:10 bits. I know how to pull them out one at a time with the $request->get('parametername') method, but I was hopeing there's a way to do it with a loop. This will run in the controler.

Screenshot of a dd($request)

To print square with * by editing this given source code. without making any major changes

Posted: 21 Apr 2021 09:20 AM PDT

I want to print like the way given below (4 stars on one line)

****  ****  ****  ****  
public class OperatorDemo {        public static void main(String[] args)      {                          for(int i=1;i<=4;i++);          {                        for(int j=1;j<=4;j++);              {                  System.out.print("* ");              }                            System.out.println(" ");            }                        }    }  

SQL: mean of appearances in two columns

Posted: 21 Apr 2021 09:20 AM PDT

I have the correlation within two time series stored into a PostgreSQL database in the following way:

first_object_identifier second_object_identifier correlation_value
A B 1.0
A C 0.9
A D 0.8
B C 0.7
B D 0.6
C D 0.5

And I would like to get the mean of the correlations where each identifier appears (in one of the both columns of identifiers):

object_identifier mean_correlation
A mean_A
B mean_B
C mean_C
D mean_D

Where:

mean_A = (AB + AC + AD) / 3 = (1.0 + 0.9 + 0.8) / 3 = 0.9  mean_B = (AB + BC + BD) / 3 = (1.0 + 0.7 + 0.6) / 3 = 0.766  mean_C = (AC + BC + CD) / 3 = (0.9 + 0.7 + 0.5) / 3 = 0.7  mean_D = (AD + BD + CD) / 3 = (0.8 + 0.6 + 0.5) / 3 = 0.633  

Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net

Posted: 21 Apr 2021 09:20 AM PDT

I have an asp.net search form that includes an ajaxToolkit Combobox and a standard asp DropDownList. Both controls are bound to two separated SqlDatasource components.

Something like this:

<ajaxToolkit:ComboBox      ID="cbConvenzionato"      runat="server"      AutoCompleteMode="SuggestAppend"      DropDownStyle="DropDownList"      DataSourceID="sdsConvenzionati"      DataTextField="nome"      DataValueField="id"      AutoPostBack="true"      OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" />    <asp:DropDownList      ClientIDMode="Static"      ID="ddlVeicoli"      DataSourceID="sdsVeicoli"      DataTextField="targa"      DataValueField="id"      runat="server"      AutoPostBack="true"      OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged"      AppendDataBoundItems="true">      <asp:ListItem Text="TUTTI" Value="" Selected="True" />  </asp:DropDownList>    <asp:SqlDataSource      ID="sdsConvenzionati"      runat="server"      ConnectionString="<%$ ConnectionStrings:db %>"      ProviderName="<%$ ConnectionStrings:db.ProviderName %>"      SelectCommand="          SELECT              id,              nome          FROM              anag_convenzionati          ORDER BY nome;" />    <asp:SqlDataSource      ID="sdsVeicoli"      runat="server"      EnableCaching="false"      CancelSelectOnNullParameter="false"      ConnectionString="<%$ ConnectionStrings:db %>"      ProviderName="<%$ ConnectionStrings:db.ProviderName %>"      SelectCommand="          SELECT               id,               targa          FROM               veicoli_contratti          WHERE              ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato))          ORDER BY targa;">      <SelectParameters>          <asp:ControlParameter              Name="id_convenzionato"              ControlID="cbConvenzionato"              PropertyName="SelectedValue"              Direction="Input"              ConvertEmptyStringToNull="true"              DbType="Int32"              DefaultValue="" />      </SelectParameters>  </asp:SqlDataSource>  

There's also a third sqldatasource (sdsNoleggi) that feeds a gridview but this's not a problem right now.

In code behind I have two event handlers:

    protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e)      {          sdsVeicoli.Select(DataSourceSelectArguments.Empty);            Search();      }        protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e)      {          Search();      }        private void Search()      {          sdsNoleggi.Select(DataSourceSelectArguments.Empty);      }  

I tought in this way I should filter dropdownlist items after selecting an item in the combobox... but it's not working... why?

If I look into sdsVeicoli SelectParameters in debug I can see id_convenzionato being correctly set to selected value (id coming from combobox) I could also figure out that sdsNoleggi dataset is correctly updated with new values. So why bound control it's not? I tried also a ddlVeicoli.DataBind() ... but this has not effect.

Refactor small function using lodash/fp map, and a second argument

Posted: 21 Apr 2021 09:20 AM PDT

I have a lodash/fp map function that returns a component, Lead. It is passed a list of leads (over which i iterate), but i also want to pass an id, that ill pass into each component (same id into each component)

I pass the array and the string into the component

<tbody>{renderLeads(leads, advisor.id)}</tbody>  

and my function returns a mapped array of leads

const renderLeads = map(({ node: lead }) => { <--- how do i pass advisor.id into this function     return <Lead lead={lead} advisorId={advisorId} key={lead.id} />;  });  

How do I add the prop advisor.id (the second argument) into that map

Split html string in two array without breaking a tag / div

Posted: 21 Apr 2021 09:20 AM PDT

Let's say I have a variable like this :

const myhtml = "<div>hello</div><h1>hello</h1><div>hello</div><div>hello</div><div>hello</div><div>hello</div><p>hello</p><div>hello</div><div>hello</div>"  

Is it possible to split this string in half in two array without breaking the html, so waiting for the end of div before splitting to end up with :

myArray=['<div>hello</div><h1>hello</h1><div>hello</div><div>hello</div>','<div>hello</div><div>hello</div><p>hello</p><div>hello</div><div>hello</div>']  

Thanks in advance guys !

BigQuery: Insert into temporary table

Posted: 21 Apr 2021 09:20 AM PDT

What is the closest approximation in BigQuery to this MS-SQL (T-SQL) syntax? I am running the browser version of Google's BigQuery.

select *   into #myNewTempTable  from myTable  

In MS-SQL this will create a temporary table without having to specify the table structure. (I don't particularly care about how long the table persists.) Thank you!

Hint: This will create a table without having to specify the table structure, but it's not a temporary table.

create table `datascience-291801.temp.premier_cohort_heart` as  

MariaDB. connection re-use

Posted: 21 Apr 2021 09:20 AM PDT

i have a database that thousands of users need to connect to (via ODBC) for very brief periods (it's a subscription licensing database for a win32 desktop app). They connect, get their approval to run and disconnect). max_connections is set to 1000 but am not seeing the re-use i would expect server side. i.e. server currently has about 800 processes/connections sleeping (and another 200 connected to real data in other databases on the same server) .... yet a new attempt by a client app was rejected 'too many connections'.

What am i missing?

have increased the max_connections for now to 1500 but if that just means another 500 sleeping connections it's not a long term solution. pretty sure clients are disconnecting properly but am adding some diagnostics to the win32 app just in case.

MariaDB 10.3.11

with MySQL ODBC 5.3 ANSI Driver

axios network error with cors activated still returns error

Posted: 21 Apr 2021 09:20 AM PDT

the link to the code link

I am using axios and nodejs. All routes work and give a response except one. which returns Network error. that route is /api/ads/myads.

The route works on its own but when used with redux actions it doesn't

The network tab says that this request was blocked. So I tried to add cors but that didn't solve the issue.

The file in question is .../actions/adActions this one is producing the error while others don't

I will be uploading the code in a minute

Postgres DB Schema - multiple columns vs one json column

Posted: 21 Apr 2021 09:21 AM PDT

I have a db that contains username with 3 different phone numbers and 3 different ids. also we will have 3 different type of notes for each username.

I am using postgres and data are planned to increase to millions of rows. querying and inserting new data process are really important to be fastest way.

which schema would be better for that:

username | no1(string) | no2(string) | no3(string) | id1(string) | id2(string) | | id3(string) | note1(string) | note2(string) | note3(string)  

OR

username | no(JSON) | id(JSON) | note(JSON)  

A difficult web-scrape - Multiple values of interest in the same cell

Posted: 21 Apr 2021 09:21 AM PDT

I am having some issues with web-scraping the wiki polls for the Spanish Political Parties (Link below). The issue is that the cells contain both the % score in the poll (the top number), but also the number of seats this equates to in Spanish Parliament. I have been using a basic Pandas web-scrape (read_html) for my other polling web-scrapes and they work fine. I am not sure if Pandas is even capable to read the numbers separately, so any guidance would be great.

For reference, when you do pd.read_html, this table is table 1, so df[0].

Link: https://en.wikipedia.org/wiki/Opinion_polling_for_the_next_Spanish_general_election

Current Code - really simple, but df adds all the objects together from the wiki page

df = pd.read_html('https://en.wikipedia.org/wiki/Opinion_polling_for_the_next_Spanish_general_election',header=1)  df[0]  

Any help much appreciated. Thanks

Tabulator processing ajax data before load

Posted: 21 Apr 2021 09:20 AM PDT

I need help if it is possible to modify table data before load into table in Tabulator library. I need to convert decimal value of (8 poles)DIP switch to separate 8 bits and load it to table. I have data in json format like this:

[  {"id":1, "name":"DIP1", "value":15},  {"id":2, "name":"DIP2", "value":75}  ]  

and I would like format data to this (for decimal value 15):

[{"id":1, "name":"DIP1", "sw1":0,"sw2":0,"sw3":0,"sw4":0,"sw5":1,"sw6":1,"sw7":1,"sw8":1,}]  

to this table:

columns:[          { title:'ID', field:'id', width:50 },          { title:'DIP NAME', field:'name', headerFilter:'input', editor:'input', hozAlign:'center' },          { title:' DIP SWITCHES', hozAlign:'center',              columns:[                                 { title:'SW1', field:'sw1',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW2', field:'sw2',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW3', field:'sw3',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW4', field:'sw4',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW5', field:'sw5',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW6', field:'sw6',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW7', field:'sw7',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },                  { title:'SW8', field:'sw8',  width:30, hozAlign:'center', editor:true, formatter:'tickCross', headerVertical:true, headerFilter:'tickCross',  headerFilterParams:{"tristate":true}, headerSort:false },              ],          }  ],  

I know how to extract each bit in c:

 var sw1 = bitRead( value, 7 );   var sw2 = bitRead( value, 6 );   var sw3 = bitRead( value, 5 );   var sw4 = bitRead( value, 4 );   var sw5 = bitRead( value, 3 );   var sw6 = bitRead( value, 2 );   var sw7 = bitRead( value, 1 );   var sw8 = bitRead( value, 0 );  

but I dont know how to do this when data are loaded into table using ajax.

Can somebody help how to do it please?

I am newbie and I cant help myself.

Thank you!

Accessing Google Adsense API from a server with Python?

Posted: 21 Apr 2021 09:20 AM PDT

Is there any way to use Python to access the Google Adsense API from a server without any user interaction?

This is typically done by setting up a "service account", but Google's docs say that "AdSense doesn't support Service Accounts".

They say to use the web or installed application flows, but these require the user to manually confirm access for every access. My application needs to run on a headless server, without user interaction, so it can pull data every hour, so this won't work. This similar question suggests going through the user consent screen once and then caching the token on the server, but this isn't feasible in my case since my process needs to be 100% automated, and the token will eventually expire and require user interaction.

Unfortunately, Google's docs are quiet unhelpful, and even worse their Python coding examples haven't been updated in 7 years, and don't even seem to have worked back then, as many of them don't even run Python 2.7, much less 3.

Swift LinkedList resulting in segmentation fault

Posted: 21 Apr 2021 09:21 AM PDT

Just to learn more and practice some Swift, I attempted a LinkedList implementation. It appears to work as I am able to add and remove some integers and verify these two operations are working as expected.

However, at the end of this main program, when I re-initialize the nums variable which is an instance of LinkedList<Int>, a segmentation fault occurs... why and how to fix?

import Foundation    var start = DispatchTime.now()  var nums = LinkedList<Int>()  for i in 1...100000 {    nums.insert(i)  }  var end = DispatchTime.now()  print(end.rawValue - start.rawValue)    // reinitialize causes segmentation fault, why?  nums = LinkedList<Int>()  

The complete class is below, and it is also executable here on Replit:
https://replit.com/@J_W_Clark/SwiftLinkedList-SegFault

class LinkedList<T: Comparable> : CustomStringConvertible {    private var head: Node<T>?    private var tail: Node<T>?    private var size = 0      private class Node<T: Comparable> : CustomStringConvertible {      var next: Node?      var value: T        init(_ value: T) {        self.value = value      }        public var description: String { return "\(self.value)" }    }      func insert(_ value: T) {      if size < 1 {        head = Node(value)        tail = head      } else {        let newNode = Node(value)        tail!.next = newNode // add new node to tail        tail = newNode // newNode becomes new tail      }      size += 1    }      func remove(_ value: T) {      if size < 1 { return } // head is nil        // head is not nil      if head!.value == value {        if head!.next == nil {          head = nil        } else {          head = head!.next        }        size -= 1        return      }        var node = head!.next      var previous = head!      while node != nil {        if node!.value == value {          if node!.next == nil { // the last one            tail = previous            previous.next = nil          } else {            previous.next = node!.next          }          return        }        previous = node!        node = node!.next      }    }      public var description: String {      var text = "["      var node = head      while node != nil {        text += "\(node!.value)"        node = node!.next        if node != nil { text += ", " }      }      return text + "]"    }  }v  

Regex pattern for postal codes

Posted: 21 Apr 2021 09:21 AM PDT

I am trying to write a regex pattern for 4 digits hyphen or space continued by 3 digits e.g.

1234 123  1234-123  

I have tried this but it is not matching the requirements

^\\d{4}[-]{0,1}\\d{3}$  

How do I obfuscate Javascript in Ember?

Posted: 21 Apr 2021 09:20 AM PDT

Does anyone know how to use the javascript-obfuscator (or similar) in Ember ?

I guess it needs to be called inside ember-cli-build.js but I don't know where and how.

Thank you in advance for any help :)

C# Nlog - How to rotate log files so it creates rotated logs file and archives

Posted: 21 Apr 2021 09:20 AM PDT

I have a trouble with creating a following log rotation settings:

1 - Current log file (service.log)

10 - rotated logs file like service.1.log, service.2.log etc. Log files size are 10MB.

10 - archived logs

When the file reaches 10mb, we discard it with the name .1 when there are 10 such rotated files, the last one is archived and there are also 10 archives.

Example:

  1. I have a log file - service.log. When the file reaches 10mb, we discard it with the 'service.1.log' name and create a new 'service.log' file. Then, when this situation is repeated, we discrad the log file with the 'service.2.log' name.

  2. When there are 10 such rotated files, then the oldest one is archived and so we have the following situation: 1 - service.log (new created file); 9 files - service.2.log, service.3.log, .... service.10.log; 1 archived that was created from the 'service.1.log' file.

  3. We should have also maximun 10 such archives. The oldest archives should be deleted.

Thank you!

Deleting & Recreating NTFS Journals (Or How to Properly run the 'fsutil usn' Command)

Posted: 21 Apr 2021 09:21 AM PDT

I have a chkdsk Stage 3 error (which relates to NTFS usn journals and security descriptors).

Corrupted NTFS journals prevent chkdsk /f from running a repair of the volume. So chkdsk repairs won't run and this is not a solution.

However, I have heard the corruption can be repaired by deleting and recreating the NTFS journal. This can be done by executing the following commands at the command prompt or PowerShell with administrator privileges:

fsutil usn deletejournal /d /n  

followed by

fsutil usn createjournal m=<maxsize> a=<allocationdelta> <volumepath>  

However, Microsoft documentation on the switches and parameters for these commands is very poor. Can anyone please advise :

  1. What the /d and /n switches actually do. Are they permanent? Do I need to re-enable them if I am creating a new journal? How would I re-enable if I had to?
  2. What are the <maxsize> and <allocationdelta> parameters?
  3. How do I figure out what values to set <maxsize> and <allocationdelta>to? What are the default values?

Finally, how safe is it to delete the NTFS journals in this manner?

Thanks.

enter image description here

NPM scripts not shown in explorer sidebar

Posted: 21 Apr 2021 09:20 AM PDT

I have this problem with Visual Studio Code for Windows 10: I can't see anymore the NPM scripts in explorer sidebar.

I deleted all the extensions, uninstalled Vscode cancelling also its folder and the extension folders, installed latest version of VsCode again with no custom options and no extensions, but not solved: NPM scripts menu does not appear. How could I solve it? Thanks for your support.

Stop Visual Studio 2019 from automatically adding comment prefix when enter pressed?

Posted: 21 Apr 2021 09:20 AM PDT

I can't find the option to turn of the VS2019 editor from automatically continuing a comment to the next line. Example:

// This is my comment and when I press enter it gives me:  //   

I don't want it to add the // on enter. Where do I turn that off?

Thanks.

No comments:

Post a Comment