Saturday, August 7, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Inspecting Ethereum blockchain to find minted NFT's?

Posted: 07 Aug 2021 08:37 AM PDT

I'm trying to discover programmatically all new and old NFT's minted on Ethereum. Does anyone know if this is even possible and what the best way would be to approach such a problem ?

How to feature flag in appDelegate.m file

Posted: 07 Aug 2021 08:37 AM PDT

I am currently feature flagging 2 apps with the use of environment variables inside one appDelegate.m file. app(A) uses HealthKit app(B) uses locations, none uses both. The problem is that the app store rejects my apps because of code reference of locations or HealthKit features that are not specified in .plist file of each app that does not have the feature. If I do specify them in the .plist file then the app gets rejected beacuse they do not se the use of locations and HealthKit.

So what would be the best approach here? Switch appDelegate.m files depending on the feature and if so how do I do that?

Running a websocket client next to an httpserver

Posted: 07 Aug 2021 08:37 AM PDT

I'm currently writing a webserver with python that can process simple requests and centralizes some API work (like OAuth, keys, tokens, and logging). One of the APIs I want to integrate into the server supports websockets and I really want these live events in my server. The example code they provide is javascript, and I'm having a rough time making sense of it:

<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js' type='text/javascript'></script>  <script type = 'text/javascript'>    const socketToken = ''; //Socket token from /socket/token end point        //Connect to socket  const streamlabs = io(`https://sockets.streamlabs.com?token=${socketToken}`, {transports: ['websocket']});        //Perform Action on event    streamlabs.on('event', (eventData) => {      if (!eventData.for && eventData.type === 'donation') {        //code to handle donation events        console.log(eventData.message);      }      if (eventData.for === 'twitch_account') {        switch(eventData.type) {          case 'follow':            //code to handle follow events            console.log(eventData.message);            break;          case 'subscription':            //code to handle subscription events            console.log(eventData.message);            break;          default:            //default case            console.log(eventData.message);        }      }    });  </script>  

My plan: Run the websocket in a separate thread so the httpserver can still process requests while waiting for events. Is that a good idea? Are there different methods? Here is the gist of my code: (will be run in parallel with the main server class)

class socketListener(threading.Thread):      socketCode = None      listening = True        sllb_url = "https://sockets.streamlabs.com?token="        def __init__(self, code):          super(socketListener, self).__init__()          self.socketCode = code            async def listen():              async with websockets.connect(self.sllb_url + self.socketCode) as ws:                  msg = await ws.recv()                  print(msg)            asyncio.get_event_loop().run_until_complete(listen())        def run(self):          print(f"Creating new socket listener! {self.socketCode}")  

Why am I not receiving anything when I'm trying to run the code with a correct token? How can I emulate the "transports: ["websocket"]" in websockets, socket.io or similar?

Is there maybe even a way to write that functionality with the basic httpserver python library?

Any help appreciated, thank you for your time and attention

Powershell to move files in specific directories up one level (Migrating from Drivebender to Drivepool)

Posted: 07 Aug 2021 08:36 AM PDT

I am working to migrate from Drivebender to Drivepool. If not familiar, these are duplication softwares, but function differently. Drivebender has primary and secondary files, and Drivepool does not.

Anyways, I am attempting to clean up the folders left behind after migration. Drivebender creates folders named "FOLDER.DUPLICATE.$DRIVEBENDER". Inside these folders are secondary files. So let's say on hard drive 1 there is D:\Jay\somefile.txt On hard disk 2, there is D:\Jay\FOLDER.DUPLICATE.$DRIVEBENDER\somefile.txt. On hard disk 2, I will be running the script to move it up a level (as that is how drivepool does duplication.

So what I'm looking to do in powershell is find directories that are specifically "FOLDER.DUPLICATE.$DRIVEBENDER", move all files in that directory up a level, and then remove the "FOLDER.DUPLICATE.$DRIVEBENDER" directory.

I had originally set up to run this as a .bat (and asked another question about this), but it seems that I am running into issues with the path being too long, and CMD.exe doesn't want to allow that, so I think powershell is a better idea.

How do I go about turning this into something that I can use on about 24 hard drives to remove the duplication left behind by Drivebender?

An alternative class for Tracert with DNS feature

Posted: 07 Aug 2021 08:36 AM PDT

I noticed, using Tracert on Windows, that if there is no data for DNS info, there is a delay too long to be acceptable - more or less 5 seconds. For this reason, I coded my own Tracert class with a latency parameter, waiting for an answer. All is done using a Task method. However, if I code for a few years, now I am trying to elaborate my code cleanly and efficiently. Please, can you tell me what I should change? Maybe you see some mistakes or non-senses. Thank you for your help ++ enter image description here

class TraceRoute  {      public void TraceRouteX(string ipAddressOrHostName, int hops = 30, int latency = 1000, bool dns = false)      {   // this way we can check if IP or HostName are valid           try          {   // a tip to get only IPv4              IPAddress ipAddress = Dns.GetHostAddresses(ipAddressOrHostName).First(address => address.AddressFamily == AddressFamily.InterNetwork);                using (Ping pingSender = new Ping())              {                  PingOptions pingOptions = new PingOptions();                  Stopwatch stopWatch = new Stopwatch();                  byte[] bytes = new byte[32]; // 32 bits as packet                  string hostName; // for DNS                  PingReply pingReply;                    pingOptions.DontFragment = true;                  pingOptions.Ttl = 1;                  int maxHops = hops;                  // just a first message on screen before TraceRoute                  Console.ForegroundColor = ConsoleColor.Green;                  Console.WriteLine(string.Format(" TraceRoute to {0} with a maximum of {1} hops, setting latency to {2} and DNS feature to {3}\n", ipAddress, maxHops, latency, dns));                  Console.ResetColor();                    for (int i = 1; i < maxHops + 1; i++)                  {   // for latence                      stopWatch.Reset();                      stopWatch.Start(); // ping options allows us to set TTL                                        pingReply = pingSender.Send(ipAddress, latency, new byte[32], pingOptions);                      stopWatch.Stop();                        if (dns)                      {   // DNS resolving using a timer                          Task<string> task = Task<string>.Factory.StartNew(() =>                          {                              var t = Dns.GetHostEntry(pingReply.Address).HostName;                              return t.ToString(); // well well ?                          });                          // waiting an answer                          bool success = task.Wait(latency);                            if (success)                              hostName = task.Result;                          else                              hostName = "TimeOut (no DNS info)";                                        }                      else                          hostName = "";                      // display string with all informations - easy reading                      if (i % 2 == 0)                          Console.ForegroundColor = ConsoleColor.DarkYellow;                      else                          Console.ForegroundColor = ConsoleColor.Cyan;                      // display final output                      Console.WriteLine(string.Format(" h{0}\t{1} ms\t{2}\t\t{3}", i, stopWatch.ElapsedMilliseconds, pingReply.Address, hostName));                      Console.ResetColor();                      // status                      if (pingReply.Status == IPStatus.Success)                      {                          Console.ForegroundColor = ConsoleColor.Green;                          Console.WriteLine("\n The IP target " + pingReply.Address + " has been reached");                          Console.ResetColor();                          break;                      }                      // increment TTL to get the next node                      pingOptions.Ttl++;                  }              }          }          catch          {              Console.ForegroundColor = ConsoleColor.Red;              Console.WriteLine(" ERROR: You Have Some TIMEOUT Issue Or An Invalid IP/Host");              Console.ResetColor();          }      }  }  

missing: ANTLR3_COMMAND)

Posted: 07 Aug 2021 08:36 AM PDT

cortexa15hf-neon-rdk-linux-gnueabi/belle-sip/git_d8c5e9e08b3bd6640898e46850333f1ad900c8d2-r0.0/recipe-sysroot-native/usr/share/cmake-3.16/Modules/FindPackageHandleStandardArgs.cmake:146 (message): | Could NOT find Antlr3 (missing: ANTLR3_COMMAND)

beele-sip.inc is having

CFLAGS += " ${ANTLR_CFLAGS} ${ANTLR_LIBS} -lantlr3c" Any pointers

Choosing a file from explorer and insert his name in python script using os.start() or Subprocess.Popen()

Posted: 07 Aug 2021 08:36 AM PDT

The user clicks on button and windows explorer opens. So how can i pick a file from explorer using Subprocess.Popen() or os.start() and insert its name to variable? Thank you for help

Url rewriting using RewriteCond whrere different url required based on query param

Posted: 07 Aug 2021 08:36 AM PDT

My requirement is

  1. domain.com/src/home.php?page=category&category=recipe
  2. domain.com/src/home.php?page=article&key=myarticle
  3. domain.com/src/home.php

Expected end url

  1. domain.com/src/category/recipe

  2. domain.com/src/article/myarticle

  3. domain.com

I have written one

RewriteRule ^src/([A-Za-z0-9-]+)/?$ src/home.php?page=article&key=$1 [NC,L]

The problem is if one is working then the other is not. Can anyone please suggest how to make it work with some condition based on "page" query param.

Thanks in advance.

How to send special keys to textbox

Posted: 07 Aug 2021 08:36 AM PDT

I am working with Textbox to convert characters. I needed to press 'Oem3(192 in keys enum)' key automatically. I tried sendkeys(), but I cannot find that key. What can I do to send that key to textbox? Codes I tried:

sendkeys.send({OEM3});  //error  sendkeys.send(keys.Oem3);  //just entering '192' into textbox  sendkeys.send({192});  //error  

Passing a component as props for another component in Routes

Posted: 07 Aug 2021 08:36 AM PDT

I have components like Dashboard, Users, Posts, Category and so on and I want to render these components inside Admin component. when my Url will be : /admin/dashboard I want to render Dashboard inside Admin , when my url will be : /admin/users I want to render Users inside Admin and so on. For this my Routing is:

            <Route exact path='/' component={Home} />              <Route exact path='/admin/dashboard'                  component={() => <Admin comp={<Dashboard />} />}              />              <Route exact path='/admin/users                  component={() => <Admin comp={<Users />} />}              />              <Route exact path='/admin/posts'                  component={() => <Admin comp={<Post />} />}              />              <Route exact path='/admin/category'                  component={() => <Admin comp={<Category />} />}              />  

My question is: Is this good approach of routing?

How to make an if when button is clicked, how does it know whats selected?

Posted: 07 Aug 2021 08:37 AM PDT

  void draw() {      image(mImage, posX, posY); //shows all images              if(isClicked) {           //--------check if player selected the right image-------          if(mImage == imageTrue[0] || mImage == imageTrue[1]          || mImage == imageTrue[2] || mImage == imageTrue[3]          || mImage == imageTrue[4] || mImage == imageTrue[5]) {            print("You found the right image!");          }          else {            print("wrong!");          }       }          //------------------------------       if(isClicked && mImage != buttom) { //dont mark the buttom        image(selected, posX, posY, width, height); //mark the selected pic. (selected is a                                                      empty green square image, so its shown whats                                                      selected)       }    }  

The player is shown 6 different images, but there is only one true image that he needs to selected. When selected its marked green and then player needs to click on the buttom so submit. Then the if should check if the player selected the true picture or wrong.

The problem: when right images are selected, the console say its a wrong image, because it only check what the players clicks right now. Button is not a true image so the "if" says its wrong.

Question: How can I make an if that it should not check whats clicked right now, it should check whats selected and then check if the picture on what player selected is true or not. How can I solve this in code?

Note: selected is an image that will be placed over the selected picture green empty square, so player can see its selected. the imageTrue is an Array [ ]

How to image to fullscreen in List row?

Posted: 07 Aug 2021 08:35 AM PDT

I try to make the behavior when you tap on the image when the image with the animation is transferred to the center of the screen with a fullscreen background (in my example it is center + 'y: -200' offset only to show you animation what i want). I made a similar code in ChildView, I encapsulated all the logic there and it works as i expected. But I show images in the List in ParentView and when I touch the picture in the List behavior is not what I expected, seems it cannot go beyond the boundaries of List row area. How can I make image open on tap to full screen with animation in List but stay all the logic in ChildView incapsulated?

import SwiftUI    struct ParentView: View {      var body: some View {          List(1...10, id: \.self) { row in              ChildView()          }            //        ChildView()      }  }    struct ChildView: View {            @State private var isFullscreen = false      @Namespace private var animation            var body: some View {          VStack {              if isFullscreen {                  Image(systemName: "swift")                      .resizable()                      .scaledToFit()                      .matchedGeometryEffect(id: "Image", in: animation)                      .offset(x: 0, y: -200)                      .frame(width: 300, height: 300)                      .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)                      .background(                          Color.purple                              .ignoresSafeArea()                      )                      .onTapGesture(perform: toggle)              } else {                                    Image(systemName: "swift")                      .resizable()                      .scaledToFit()                      .matchedGeometryEffect(id: "Image", in: animation)                      .foregroundColor(.purple)                      .frame(width: 300, height: 300)                      .onTapGesture(perform: toggle)              }          }      }            func toggle() {          withAnimation {              isFullscreen.toggle()                        }      }  }    struct ParentView_Previews: PreviewProvider {      static var previews: some View {          ParentView()      }  }  

Selenium Instagram Login - Unable to locate element

Posted: 07 Aug 2021 08:36 AM PDT

from selenium import webdriver    userName = "myusername123"  driver = webdriver.Chrome()  driver.get("https://www.instagram.com/")  driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').send_keys(userName)  

error Unable to locate element: {"method":"xpath","selector":"//[@id="loginForm"]/div/div[1]/div/label/input"} (Session info: chrome=92.0.4515.131)

I'm trying to make a login in instagram usini selenium but I can't reach the username box with xpath

How do you debug 3D raycasts?

Posted: 07 Aug 2021 08:36 AM PDT

In Godot, if a 3D raycast isn't hitting where you'd expect it to hit, how do you debug it? I'm looking for some way to draw the ray (or a line that follows the ray), problem is, I can't find anything in the docs, so your help is much appreciated.

child element should fill content no matter how much content is on the screen

Posted: 07 Aug 2021 08:37 AM PDT

In the example, I cannot get the main and #root elements to claim the remaining space when the expand button is clicked.

html {    border: 5px solid purple;  }    body {    font-size: 19px;    border: 5px solid red;    margin: 0;  }    *,  *:before,  *:after {    box-sizing: border-box;  }    html,  body {    margin: 0;    padding: 0;    min-width: 100%;    width: 100%;    max-width: 100%;    min-height: 100%;    height: 100%;    max-height: 100%;    overflow: auto;  }    #root {    max-width: 62rem;    margin: 0 auto;    display: flex;    flex: 1;    flex-direction: column;    border: 10px solid blue;    height: 100%;  }    main {    display: flex;    flex-direction: column;    flex-grow: 1;    flex-shrink: 1;    border: 15px solid yellow;    height: 100%;  }
<html>    <head>      <title>Parcel Sandbox</title>      <meta charset="UTF-8" />      <script type="text/javascript">        function moreContent() {          for (var i = 0; i < 50; i++) {            document              .querySelector("main")              .insertAdjacentHTML("afterend", "<div>one</div>");          }        }      </script>      <link rel="stylesheet" href="./style.css" />    </head>      <body>      <div id="root">        <main>          <div>one</div>          <div>one</div>          <div>one</div>          <div>one</div>          <div>            <button onclick="moreContent()">Expand</button>          </div>        </main>      </div>    </body>  </html>

Why does python return "NameError: name 'correct' is not defined when it has been defined?

Posted: 07 Aug 2021 08:36 AM PDT

Essentially I am making a quiz, and python returns an error saying the variable shown below is undefined when it has been defined.

def guesscheck(guess, answer):      correct = "null"      print(lives * '\u2665')      if guess.upper() == answer:          print("Marvelous! That is correct!")          correct = True          return correct       if guess.upper() != answer:          print("That is incorrect.")          correct = False          return correct    lives = 3  guess = input("ok: ")  guesscheck(guess, "OK")  if correct == False:      lives = lives - 1      print(lives * '\u2665')  

As you can see, I call the function which should define the variable 'correct' as True or False and return it to the rest of the program, but for some reason it is showing as undefined. Please help me!

Partitioning Data by Year and Month based on long based date column using Pyspark

Posted: 07 Aug 2021 08:36 AM PDT

I have the following dataframe

root   |-- id: long (nullable = false)   |-- name: string (nullable = true)   |-- school: string(nullable = true)   |-- subject: string(nullable = true)   |-- created_date: long(nullable = false)   

I want to store the data in this dataframe partioned by year and months based on the created_date column.

newDataframe=originaldataframe.select(col("id"),col("name"),col("school"),col("subject"),date_format(from_unixtime(col["created_date"]/1000,"MM-dd-yyyy"),"MM-dd-yyyy")).cast('date')      dataframePationed= newDataframe.withColumn("year", year(newDataframe.created_date)).withColumn("month", month(newDataframe.created_date)).drop("created_date")      dataframePationed.write.partitionBy("year", "month").format("csv").save("path/to/partion/data")  

But after long data type is converted date format if I try to print createdDate column value is shown as null. How can I achieve this correctly?

How to navigate between months using icons (shapes) in excel VBA?

Posted: 07 Aug 2021 08:37 AM PDT

I've created several tables in the same sheet, each table assigning it to a month, plus there are two icons (two shapes) to navigate to the next or previous month. What I need is to cycle through the months using the two icons (next/previous month). For example, if the user needs January, the columns (B:AD) will be shown and the reset will be hidden, so on with the other months.

Columns to be shown: January (B:AD) February(AF:BH) March(BJ:CL) April(CN:DP) May(DR:ET) June(EV:FX) July(FZ:HB) August(HD:IF) September(IH:JJ) October(JL:KN) November(KP:LR) December(LT:MV)

Here is the link to my excel: https://1drv.ms/x/s!Av2jQlwHZCT3gjeo3q_Po99tvoSr?e=SuMvis

Why is there a speed difference when slicing a pandas dataframe?

Posted: 07 Aug 2021 08:37 AM PDT

I am slicing a large amount of dataframes over time.

However, the run times of the two codes below show a big difference.

code1.

for i in city_list:       from_line = df[(df['Timestamp']==time_from)                                  & (df['city']==i)]       to_line = df[(df['Timestamp']==time_to)                                  & (df['city']==i)]         value1 = len(from_line['Value'])       value2 = len(to_line['Value'])       ...       ...  

code2.

for i in city_list:         from_line_sub = df[df['Timestamp']==time_from]       from_line = from_line_sub[from_line_sub['city']==i]         to_line_sub = df[df['Timestamp']==time_to)]                                  to_line = to_line_sub[to_line_sub['city']==i]         value1 = len(from_line['Value'])       value2 = len(to_line['Value'])       ...       ...  

Code1 takes over an hour, while code2 takes just over 20 minutes.

I think the result of slicing is the same, but what is the reason for this speed difference?

This speed difference can be seen not only with == condition, but also with > and < conditions.

Maybe I am missing something?

Thanks for reading this far.

Need help in vectorizing of nested for loop in data accessing and updating

Posted: 07 Aug 2021 08:37 AM PDT

trying to update csv files based on trade data but taking hours of time for total completion because of using nested for loops.

I am looking for output data updated when whenever stock low is less than entry then update "trade_triggered"="yes".And after that whenever low is less than "sl", then update "trade_result"="sl_hit", or whenever high is greater than "target", then update "trade_result"="target_hit.

dfentry-->    date        symbol   entry  sl     target   trade_triggered  trade_result  08-07-21    GABRIEL  123.4  117.23 141.91   no               no  08-07-21    SANDHAR  254    241.3  292.1    no               no      new_bhavcopy-->    date         symbol open    high    low     close     11-01-21    SANDHAR 246     247     234     235.35    11-01-21    GABRIEL 117.35  119.35  114     115.05    12-01-21    SANDHAR 235.5   235.55  229     230   12-01-21    GABRIEL 115.95  116.95  113.6   114.35    13-01-21    GABRIEL 115     116.7   112.4   113.8     13-01-21    SANDHAR 233.8   276     233.7   254.15    14-01-21    SANDHAR 259     264.5   248     249.15    14-01-21    GABRIEL 114.25  115.8   113.05  113.8     15-01-21    SANDHAR 248.8   255.55  243.05  246.15    15-01-21    GABRIEL 115 115 110.6   110.95    18-01-21    GABRIEL 112.2   112.35  107.1   107.7     18-01-21    SANDHAR 244.25  248.15  240.8   244.15    19-01-21    SANDHAR 252.9   253     240     241.4     19-01-21    GABRIEL 109.5   110.6   107.8   109   20-01-21    SANDHAR 242.1   244.9   236     237.5     20-01-21    GABRIEL 110.1   115     109.05  112.85    

CODE-->

df_data=pd.read_csv("new_bhavcopy.csv")      df_entry=pd.read_csv("dfentry.csv")          df_data["date"]= pd.to_datetime(df_data["date"], format='%d-%m-%y')  df_entry["date"]= pd.to_datetime(df_entry["date"], format='%d-%m-%y')    for eidx in df_entry.index:        for didx in df_data.index:          i=0          if (df_entry["symbol"][eidx] == df_data["symbol"][didx]) & (df_entry["date"][eidx] < df_data["date"][didx]):              datex= df_entry["date"][eidx]              symbolx=df_data["symbol"][didx]                                          if (df_data["low"][didx] < df_entry["entry"][eidx]) & (df_entry["trade_triggered"][eidx]=="no") &(i==0) :                                      df_entry.loc[(df_entry["symbol"]== symbolx) & (df_entry["date"]== datex),"trade_triggered"]="yes"                  df_entry.loc[(df_entry["symbol"]== symbolx) & (df_entry["date"]== datex),"trade_result"]="holding"                  i=1                  print("trade_triggered")                                                    if (df_data["low"][didx] < df_entry["sl"][eidx]) & (df_entry["trade_triggered"][eidx]=="yes") & (df_entry["trade_result"][eidx]=="holding") & (i==0):                  df_entry.loc[(df_entry["symbol"]== symbolx) & (df_entry["date"]== datex),"trade_result"]="sl_hit"                  i=1                  print("sl_hit")                                  if (df_data["high"][didx] >= df_entry["target"][eidx]) & (df_entry["trade_triggered"][eidx]=="yes") & (df_entry["trade_result"][eidx]=="holding")  & (i==0):                  df_entry.loc[(df_entry["symbol"]== symbolx) & (df_entry["date"]== datex),"trade_result"]="target_hit"                  i=1                  print("target_hit")                      df_entry.to_csv("dfentry_update.csv",index=False)                  

"dfentry.csv" got 2052recoeds.

"new_bhavcopy.csv" got 156222 records.

It is taking hours to complete..please guide me in optimizing above code through vectorizing.

Is there a way to deploy an Azure DevOps repo to an Azure VM?

Posted: 07 Aug 2021 08:36 AM PDT

Essentially what I'm wanting to happen is the following:

  1. Push changes to .NET Core app in Azure DevOps repo
  2. Changes get pulled down to an Azure VM
  3. dotnet publish the pulled down code to a directory

I've tried creating a Release pipeline and I'm able to create an IIS website, etc. but there aren't any options for deploying a .NET Core app

What's the best way to style an email template in Django?

Posted: 07 Aug 2021 08:36 AM PDT

I am trying to style an email template in Django. From researching the best way to do this seems to be to do inline CSS styles. This seems like it would be a tedious process so was wondering if anyone has any better suggestions?

I saw another suggestion saying to use django-inlinecss but I can't for the life of me locate the css file when using {% inlinecss "static/css/email.css" %}

Path of template: Coronavirus_Dashboard/home/templates/home/newsletter_emails/newsletter_body.html Path to CSS: Coronavirus_Dashboard/static/css/email.css

I just keep getting a file not found error, not sure what way I need to specify the location.

Loop through a column to find first occurrence of special character for each location

Posted: 07 Aug 2021 08:35 AM PDT

There are two columns in the dataframe

location experience  a1       tech  a2       loyalty  a2       ‡€asd  a5       Ù…Ù  a5       completed  a6         a7       --  a8       happy  a8       best  a9       for sure  a9       notgood  b1       amazing:  b1       /§!vision  b5       referral  
  1. how to loop through location and if special character is identified in the first row of experience, remove all locations. If the second row or other rows in Experience starts with special character, I dont have to remove it.

Example1: b1 amazing:

b1 /§!vision

Here first row, experience value starts with letter, so I dont have to remove any rows with location value b1

Example2: a5 Ù…Ù

a5 completed

Here first experience value starts with special character, so I have to remove all rows with location value a5

output as

location experience  a1       tech  a2       loyalty  a2       ‡€asd  a6   a8       happy  a8       best  a9       for sure  a9       notgood  b1       amazing:  b1       /§!vision  b5       referral  

HTML table in php foreach loop where the cell data is only populated if an element is equal to the table column head name

Posted: 07 Aug 2021 08:37 AM PDT

I have created my column headers in my table by using:

if (count($round) > 0): ?>  <table>    <thead>      <tr>  <?php foreach ($round as $colhead): array_map('htmlentities', $colhead); ?>        <th><?php  echo implode('</th><th>',$colhead); ?></th>      </tr>  <?php endforeach; endif;  ?>    </thead>  

$round is:

Array  (      [0] => Array          (              [32] => -7              [31] => -6              [29] => -5              [27] => -4              [23] => -3              [19] => -2              [17] => -1              [0] => 1              [2] => 2              [10] => 3              [14] => 4              [16] => 5              [33] => 6          )    )  

This results in exactly what I want because $round won't always result in the same number of columns.

The data I want in the table row beneath those headers needs to be only those items that contain the column header's name.

Let's say the column headers are: | -7 | -6 | -5 | -4 | -3 | -2 | -1 | 1 | 2 | 3 | 4 | 5 | 6 | based on the foreach loop above.

I used the following to then populate my first column in the next row:

<tbody>      <tr>        <td>    <?php foreach ($matches as $match)  {  $firstCharacter = $match['match']['scores_csv'][0];  $lastCharacter = $match['match']['scores_csv'][-1];   $id1 = $match['match']['player1_id'];  $id2 = $match['match']['player2_id'];      if ($match['match']['round'] === -7)         echo  "Table: ".$match['match']['player1_votes']."</br>".$participants[$id1]["name"].$participants[$id1]['misc'].": ".$firstCharacter. "</br>".$participants[$id2]["name"].$participants[$id2]['misc'].":".$lastCharacter. "</br>";    }    ?>      </td>     </tr>    </tbody>  </table>  

And while it works, it's only because I know the header of my first column in the table is -7. I'm trying to figure out how to only display those items that are equal to my column header to display in the following row based on the column header so that I can then do another foreach loop to display the remainder of my table. So basically, instead of -7 that I have above, what do I need to do? I'm completely drawing a blank.

$match['match']['round'] is what is equal to the column headers. And a small sample of var_dump($matches) is below in case that helps.

 [{"match":{"id":246811883,"tournament_id":10128202,"state":"complete","player1_id":152239163,"player2_id":152239166,"player1_prereq_match_id":null,"player2_prereq_match_id":null,"player1_is_prereq_match_loser":false,"player2_is_prereq_match_loser":false,"winner_id":152239166,"loser_id":152239163,"started_at":"2021-08-07T01: 59: 51.967+02: 00","created_at":"2021-08-07T01: 59: 51.692+02: 00","updated_at":"2021-08-07T02: 22: 29.417+02: 00","identifier":"A","has_attachment":false,"round":1,"player1_votes":1,"player2_votes":null,"group_id":null,"attachment_count":null,"scheduled_time":null,"location":null,"underway_at":"2021-08-07T02: 05: 31.834+02: 00","optional":false,"rushb_id":null,"completed_at":"2021-08-07T02: 22: 29.455+02: 00","suggested_play_order":null,"forfeited":null,"open_graph_image_file_name":null,"open_graph_image_content_type":null,"open_graph_image_file_size":null,"prerequisite_match_ids_csv":"","scores_csv":"0-2"}},{"match":{"id":246811884,"tournament_id":10128202,"state":"complete","player1_id":152239594,"player2_id":152239168,"player1_prereq_match_id":null,"player2_prereq_match_id":null,"player1_is_prereq_match_loser":false,"player2_is_prereq_match_loser":false,"winner_id":152239594,"loser_id":152239168,"started_at":"2021-08-07T01: 59: 51.984+02: 00","created_at":"2021-08-07T01: 59: 51.698+02: 00","updated_at":"2021-08-07T02: 32: 30.655+02: 00","identifier":"B","has_attachment":false,"round":1,"player1_votes":2,"player2_votes":null,"group_id":null,"attachment_count":null,"scheduled_time":null,"location":null,"underway_at":"2021-08-07T02: 05: 23.667+02: 00","optional":false,"rushb_id":null,"completed_at":"2021-08-07T02: 32: 30.690+02: 00","suggested_play_order":null,"forfeited":null,"open_graph_image_file_name":null,"open_graph_image_content_type":null,"open_graph_image_file_size":null,"prerequisite_match_ids_csv":"","scores_csv":"2-1"}}]  

I've attempted to reindex the array by using:

$matchesa = array_column($matches, 'match');  $matchesa = array_column($matchesa, null, 'round');    foreach ( $matches as $match )  {              $id1 = $match['match']['round'];   {          echo $matchesa[$id1]['round'].PHP_EOL;      }    }  

Partially read really large csv.gz in R using vroom

Posted: 07 Aug 2021 08:37 AM PDT

I have a csv.gz file that (from what I've been told) before compression was 70GB in size. My machine has 50GB of RAM, so anyway I will never be able to open it as a whole in R.

I can load for example the first 10m rows as follows:

library(vroom)    df <- vroom("HUGE.csv.gz", delim= ",", n_max = 10^7)  

For what I have to do, it is fine to load 10m rows at the time, do my operations, and continue with the next 10m rows. I could do this in a loop.

I was therefore trying the skip argument.

df <- vroom("HUGE.csv.gz", delim= ",", n_max = 10^7, skip = 10^7)  

This results in an error:

Error: The size of the connection buffer (131072) was not large enough  to fit a complete line:    * Increase it by setting `Sys.setenv("VROOM_CONNECTION_SIZE")`  

I increased this with Sys.setenv("VROOM_CONNECTION_SIZE" = 131072*1000), however, the error persists.

Is there a solution to this?

Edit: I found out that random access to a gzip compressed csv (csv.gz) is not possible. We have to start from top. Probably the easiest is to decompress and save, then skip should work.

Remap key to a specific touchbar functionality in macOS (using an external keyboard)

Posted: 07 Aug 2021 08:36 AM PDT

I am using a mac and I have an external keyboard. I'm using the amazing Karabiner-elements to remap keys to mac functionalities.

I fail to map some of the keys to the functionality that exists in the mac touchpad: notification canter, do not disturb, night shift, screenshot, show desktop, screen saver, screen lock, sleep, quick actions.

These functions do not exist in the Karabiner-element key options.

Is there a way of doing this mapping?

Example: when clicking f1 --> show desktop will be triggered.

Thank you! enter image description here

Unable to pass parameter to the Controller in Visual Studio (2019 v)

Posted: 07 Aug 2021 08:35 AM PDT

I am currently unable to pass the parameter from a method I created to the Controller. When I run it manually with the parameter in postman, everything works OK.

How do I pass the parameter to the Controller? Is there any way to set this up to automatically route instead of creating individuals routes based on different parameters? It's a very basic application.

Error Message: {"Message":"No HTTP resource was found that matches the request URI 'https://localhost:44364/api/WebInterface/RemoveNurse'.","MessageDetail":"No action was found on the controller 'WebInterface' that matches the request."}

CONTROLLER:

using WebInterfaceAPI.Helpers;  using WebInterfaceAPI.Services;  using WebInterfaceAPI.Models;  using Newtonsoft.Json;  using System.Data.SqlClient;  using System.Web.Http;  using System.Net;    namespace WebInterfaceAPI.Controllers  {      public class WebInterfaceController : ApiController      {          private NurseService NurseService { get; set; }            public WebInterfaceController()          {              NurseService = new NurseService();          }            #region Nurse Actions          /// <summary>          /// Removes specified nurse          /// </summary>          /// <param name="nurseID"></param>          /// <returns></returns>          [HttpPost]          public IHttpActionResult RemoveNurse(int nurseID)          {              APIResponseModel result = NurseService.removeNurse(nurseID);              if (result.IsSuccess)              {                  return Ok(result.Message);                }              else              {                  return Content(HttpStatusCode.BadRequest, result.Message);              }          }            

No comments:

Post a Comment