Monday, September 6, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Matlab GPU Coder - Dimension 1 is fixed on the left-hand side but varies on the right ([1 x :?] ~= [:? x :?])

Posted: 06 Sep 2021 07:56 AM PDT

I am using Matlab GPU coder(https://www.mathworks.com/products/gpu-coder.html) to convert my Matlab code to Nvidia CUDA code, in my Matlab code I have called a Matlab built-in function "conv2()", and during the generation of CUDA code I got error message as below :

enter image description here

Since "conv2()" is a built-in function of Matlab, I do not exactly know the dimension of "c" or the output of "coder.internal.gpu_conv2_kernel_separable();", hence I have no idea about how to deal with this error, any suggestion would be vary appreciated, thanks.

Table of Contents for Math Equations in Latex

Posted: 06 Sep 2021 07:56 AM PDT

What's the best way to have equations in LaTeX reference back to a table of contents at the beginning of a document? Something similar to the way that chapters and subchapters easily make a table of contents at the beginning of a document. Is there a clear method for doing this?

When I install FCM form larave-noticiation-channels this problem faced me

Posted: 06 Sep 2021 07:56 AM PDT

enter image description here I have this problem when I used composer require laravel-notification-channels/fcm:~2.0

Gnuplot plot a 2D heatmap in polar coordinates from Matrix data

Posted: 06 Sep 2021 07:55 AM PDT

the past days I tried to plot a matrix into a polar 2D heatmap. The matrix consists of 80x720 data points. To specify the whole thing a bit more. It is data from a XRD in polar coordinates (a pole figure). The columns are the angular the sample was rotated around between 0° and 360° in steps of 0.5° (lets call it phi), the rows are another angular the sample was tilted by between 35° and 75° in 0.5° steps (lets call this one psi). The value on a specific position in the matrix is the intensity from the detector at these angulars. I want to end up with a polar plot where the radius is psi, the angular is phi and z or more precise the color represents the intensity.

I already found this nicely discussed question but could not apply it to my problem. I managed to plot the whole thing with splot -file- matrix u ($2/2):($1/2):3 using a pm3d map but thats obviously not polar.

Does anyone here has an idea how to plot the matrix in polar form? Thanks very much! Any advice about what direction to take would be very much appreciated

(I also have 80 individual data files of this measurement with the psi angular (0°-360°) and the corresponding intensity which didn't help me much so far).

cheers Flo

What's the best way to implement a Unity App into an existing iOS project

Posted: 06 Sep 2021 07:55 AM PDT

I have a Unity AR Application which can display AR Models at different locations. Now I want to integrate the Unity App into an existing iOS App so that I can start the Unity Player from my existing iOS App. The methods I tried so far haven't really convinced me to stick with them.

I tried importing the whole Xcode project of the Unity App into the workspace of my existing app and followed all the steps on posts like this one. It worked and I was able to start my Unity AR Application from my already existing iOS App.

However, when trying to commit & push my changes to git I noticed that there were around 900 new files with some of them having a file size of above 100mb. Besides the fact that I definitely shouldn't push that, I think there is a better way to integrate my Unity App into my existing project. Maybe I make an own Framework out of the Unity Xcode project or compress it to one single file which I can then implement into my existing app somehow.

I hope anyone can help me with this.

How to return array inside array on net core api

Posted: 06 Sep 2021 07:55 AM PDT

how can i get response below

[      {        displayName: 'DevFestFL',        iconName: 'close',        children: [          {            displayName: 'Speakers',            iconName: 'group',            children: [              {                displayName: 'Michael Prentice',                iconName: 'person',                route: 'michael-prentice',                children: [                  {                    displayName: 'Create Enterprise UIs',                    iconName: 'star_rate',                    route: 'material-design'                  }                ]              },              {                displayName: 'Stephen Fluin',                iconName: 'person',                route: 'stephen-fluin',                children: [                  {                    displayName: 'What\'s up with the Web?',                    iconName: 'star_rate',                    route: 'what-up-web'                  }                ]              },              {                displayName: 'Mike Brocchi',                iconName: 'person',                route: 'mike-brocchi',                children: [                  {                    displayName: 'My ally, the CLI',                    iconName: 'star_rate',                    route: 'my-ally-cli'                  },                  {                    displayName: 'Become an Angular Tailor',                    iconName: 'star_rate',                    route: 'become-angular-tailer'                  }                ]              }            ]          },          {            displayName: 'Sessions',            iconName: 'speaker_notes',            children: [              {                displayName: 'Create Enterprise UIs',                iconName: 'star_rate',                route: 'material-design'              },              {                displayName: 'What\'s up with the Web?',                iconName: 'star_rate',                route: 'what-up-web'              },              {                displayName: 'My ally, the CLI',                iconName: 'star_rate',                route: 'my-ally-cli'              },              {                displayName: 'Become an Angular Tailor',                iconName: 'star_rate',                route: 'become-angular-tailer'              }            ]          },          {            displayName: 'Feedback',            iconName: 'feedback',            route: 'feedback'          }        ]      },      {        displayName: 'Disney',        iconName: 'close',        children: [          {            displayName: 'Speakers',            iconName: 'group',            children: [              {                displayName: 'Michael Prentice',                iconName: 'person',                route: 'michael-prentice',                children: [                  {                    displayName: 'Create Enterprise UIs',                    iconName: 'star_rate',                    route: 'material-design'                  }                ]              },              {                displayName: 'Stephen Fluin',                iconName: 'person',                route: 'stephen-fluin',                children: [                  {                    displayName: 'What\'s up with the Web?',                    iconName: 'star_rate',                    route: 'what-up-web'                  }                ]              },              {                displayName: 'Mike Brocchi',                iconName: 'person',                route: 'mike-brocchi',                children: [                  {                    displayName: 'My ally, the CLI',                    iconName: 'star_rate',                    route: 'my-ally-cli'                  },                  {                    displayName: 'Become an Angular Tailor',                    iconName: 'star_rate',                    route: 'become-angular-tailer'                  }                ]              }            ]          },          {            displayName: 'Sessions',            iconName: 'speaker_notes',            children: [              {                displayName: 'Create Enterprise UIs',                iconName: 'star_rate',                route: 'material-design'              },              {                displayName: 'What\'s up with the Web?',                iconName: 'star_rate',                route: 'what-up-web'              },              {                displayName: 'My ally, the CLI',                iconName: 'star_rate',                route: 'my-ally-cli'              },              {                displayName: 'Become an Angular Tailor',                iconName: 'star_rate',                route: 'become-angular-tailer'              }            ]          },          {            displayName: 'Feedback',            iconName: 'feedback',            route: 'feedback'          }        ]      },      {        displayName: 'Orlando',        iconName: 'close',        children: [          {            displayName: 'Speakers',            iconName: 'group',            children: [              {                displayName: 'Michael Prentice',                iconName: 'person',                route: 'michael-prentice',                children: [                  {                    displayName: 'Create Enterprise UIs',                    iconName: 'star_rate',                    route: 'material-design'                  }                ]              },              {                displayName: 'Stephen Fluin',                iconName: 'person',                route: 'stephen-fluin',                children: [                  {                    displayName: 'What\'s up with the Web?',                    iconName: 'star_rate',                    route: 'what-up-web'                  }                ]              },              {                displayName: 'Mike Brocchi',                iconName: 'person',                route: 'mike-brocchi',                children: [                  {                    displayName: 'My ally, the CLI',                    iconName: 'star_rate',                    route: 'my-ally-cli'                  },                  {                    displayName: 'Become an Angular Tailor',                    iconName: 'star_rate',                    route: 'become-angular-tailer'                  }                ]              }            ]          },          {            displayName: 'Sessions',            iconName: 'speaker_notes',            children: [              {                displayName: 'Create Enterprise UIs',                iconName: 'star_rate',                route: 'material-design'              },              {                displayName: 'What\'s up with the Web?',                iconName: 'star_rate',                route: 'what-up-web'              },              {                displayName: 'My ally, the CLI',                iconName: 'star_rate',                route: 'my-ally-cli'              },              {                displayName: 'Become an Angular Tailor',                iconName: 'star_rate',                route: 'become-angular-tailer'              }            ]          },          {            displayName: 'Feedback',            iconName: 'feedback',            route: 'feedback'          }        ]      },      {        displayName: 'Maleficent',        disabled: true,        iconName: 'close',        children: [          {            displayName: 'Speakers',            iconName: 'group',            children: [              {                displayName: 'Michael Prentice',                iconName: 'person',                route: 'michael-prentice',                children: [                  {                    displayName: 'Create Enterprise UIs',                    iconName: 'star_rate',                    route: 'material-design'                  }                ]              },              {                displayName: 'Stephen Fluin',                iconName: 'person',                route: 'stephen-fluin',                children: [                  {                    displayName: 'What\'s up with the Web?',                    iconName: 'star_rate',                    route: 'what-up-web'                  }                ]              },              {                displayName: 'Mike Brocchi',                iconName: 'person',                route: 'mike-brocchi',                children: [                  {                    displayName: 'My ally, the CLI',                    iconName: 'star_rate',                    route: 'my-ally-cli'                  },                  {                    displayName: 'Become an Angular Tailor',                    iconName: 'star_rate',                    route: 'become-angular-tailer'                  }                ]              }            ]          },          {            displayName: 'Sessions',            iconName: 'speaker_notes',            children: [              {                displayName: 'Create Enterprise UIs',                iconName: 'star_rate',                route: 'material-design'              },              {                displayName: 'What\'s up with the Web?',                iconName: 'star_rate',                route: 'what-up-web'              },              {                displayName: 'My ally, the CLI',                iconName: 'star_rate',                route: 'my-ally-cli'              },              {                displayName: 'Become an Angular Tailor',                iconName: 'star_rate',                route: 'become-angular-tailer'              }            ]          },          {            displayName: 'Feedback',            iconName: 'feedback',            route: 'feedback'          }        ]      }    ]  

when my dbstructure like this

dbstructure

Is there an efficient way to visualize SQL JOIN?

Posted: 06 Sep 2021 07:55 AM PDT

I would like to visualize SQL like:

SELECT * FROM A   INNER JOIN B ON A.id=B.id  

I need to draw diagrams like DDL like this: https://www.jetbrains.com/help/datagrip/creating-diagrams.html

Connecting the ON keys(perhaps with arrows)

Are there any online tools to help me to do visualize such DQL SQL?

Better if it can just input SQL and generate diagrams

Microsoft solutions are also welcomed.

Strange Flickering transparent border after laying GIF on static background

Posted: 06 Sep 2021 07:55 AM PDT

After placing a gif on top of a background with pil, the resulting has this weird flickering transparent border at the beginning, this shows up in photos and also the browser. However, if I open the resulting gif in Photoshop, the flickering border is not there. I can then save it for web, and photoshop's resulting gif is fine and there is no black flickering.

This has me baffled.

Any help would be greatly appreciated :)

pil resulting gif: https://uploads.codesandbox.io/uploads/user/87194565-6648-44ab-a3e3-14cdb8e3157d/NOOk-image.gif (Keep hitting refresh)

After photoshop: https://uploads.codesandbox.io/uploads/user/87194565-6648-44ab-a3e3-14cdb8e3157d/-ppw-image-photoshop.gif

def main():      background   = Image.open('bg.png')      animated_gif = Image.open("7.gif")      bg_w, bg_h = background.size        all_frames = []      for gif_frame in ImageSequence.Iterator(animated_gif):          img_w, img_h = gif_frame.size            # duplicate background image because we will change it          new_frame = background.copy()              # need to convert from `P` to `RGBA` to use it in `paste()` as mask for transparency          gif_frame = gif_frame.convert('RGBA')              # paste on background using mask to get transparency           offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)          new_frame.paste(gif_frame, offset, mask=gif_frame)             all_frames.append(new_frame)                # save all frames as animated gif      all_frames[0].save("image.gif",                       save_all=True,                       append_images=all_frames[1:],                       disposal=2,                      optimize=True,                      duration=60,                       loop=0)  

Raw Images bg.png: https://uploads.codesandbox.io/uploads/user/87194565-6648-44ab-a3e3-14cdb8e3157d/fFce-bg.png

7.gif: https://uploads.codesandbox.io/uploads/user/87194565-6648-44ab-a3e3-14cdb8e3157d/qJDJ-7.gif

How to add inline style to React component as prop?

Posted: 06 Sep 2021 07:56 AM PDT

I am trying to move the BUTTON component below by adding a style further up my screen but it does not seem to be responding.

import ExpandMoreIcon from '@material-ui/icons/ExpandMore';  import Button from '@material-ui/core/Button';  import { makeStyles } from '@material-ui/core/styles';    const useStyles = makeStyles((theme) => ({    downButton: {  marginLeft: 10,  bottom: 50  },  }));    function App() {  const style = useStyles();      <Button    style={useStyles.downButton}    onClick={() => console.log('clicked')}    color="default"    startIcon={<ExpandMoreIcon/>}    ></Button>      }  

How do I add style this button and move it?

Each location in the list should not have any leading and trailing spaces. The output should be sorted in ascending order

Posted: 06 Sep 2021 07:57 AM PDT

my current code is

def location_list(checkins):      """ takes input of check in and return the locations from the given checkins"""      checks=str(checkins)      final=[]      for elem in checks:          final.extend(elem.strip().split(';'))      return final  

and result i am getting is

checkins = '(33.63, -111.92);   (33.34, -111.88);     (33.57, -111.93);     (33.26, -111.88);(33.55, -111.93)'  print(location_list(checkins))    ['(', '3', '3', '.', '6', '3', ',', '', '-', '1', '1', '1', '.', '9', '2', ')', '', '', '', '', '', '(', '3', '3', '.', '3', '4', ',', '', '-', '1', '1', '1', '.', '8', '8', ')', '', '', '', '', '', '', '', '(', '3', '3', '.', '5', '7', ',', '', '-', '1', '1', '1', '.', '9', '3', ')', '', '', '', '', '', '', '', '(', '3', '3', '.', '2', '6', ',', '', '-', '1', '1', '1', '.', '8', '8', ')', '', '', '(', '3', '3', '.', '5', '5', ',', '', '-', '1', '1', '1', '.', '9', '3', ')']  

while the correct outcome should be

checkins = '(33.63, -111.92);   (33.34, -111.88);     (33.57, -111.93);     (33.26, -111.88);(33.55, -111.93)'  print(location_list(checkins))    ['(33.26, -111.88)', '(33.34, -111.88)', '(33.55, -111.93)', '(33.57, -111.93)', '(33.63, -111.92)']  

How to clear all elements in a vector except for the last one in a vector in c++

Posted: 06 Sep 2021 07:55 AM PDT

As the title says, I have a vector that has 11 integer elements ranging from 1 - 11. I am trying to use the .erase() function to clear all elements in my vector except for the last one. I am having trouble using iterators to do it as they clear out all elements except the first one. I tried a lot of solutions from the internet such as using .rbegin() and .rend() but they just gave me an error.

Here is my code below:-

#include <vector>  #include <iostream>    using namespace std;    vector<int> epos = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};  vector<int>::iterator it1, it2;    int main() {        it1 = epos.begin();      it2 = epos.end();        epos.erase(it1, it2);      for (int i=0; i<=epos.size(); i++) {          cout << epos[i] << ' ';      }      return 0;  }  

I am still a beginner in c++ and would appreciate any help!

Why is the output 16 and not 11?

Posted: 06 Sep 2021 07:55 AM PDT

I was learning javascript and I came across the following example,

let n = 2;    n *= 3 + 5;    console.log( n ); 

Since we have used "*=" in the expression I thought the expression is supposed to be n = n * 3+5. If the expression is n = n * 3+5 then shouldn't we get 11? I am getting 16 as the answer. Can someone please explain why is the answer 16 and not 11 ?

Error: No viable overloaded operator[] for type vector<int>

Posted: 06 Sep 2021 07:55 AM PDT

Hi I am trying to practice c++ and came across a error while solving a problem, I am using vectors in my code and getting error where I added two elements in vector through reference operator'[]'

C++

class Solution {  public:      vector<int> twoSum(vector<int>& nums, int target) {          vector<int> temp;          int p = 0;          for (auto i = nums.begin(); i != (nums.end() - 1); ++i) {              cout<<*i;              p = nums[i]+nums[i+1];                 //Error is in this line              if ((p) == target) {                  temp.push_back(i);                  temp.push_back(i + 1);                  return temp;              }          }      }  };  

Error: No viable overloaded operator[] for type vector

Get all role assignments of an Azure AD Principal

Posted: 06 Sep 2021 07:55 AM PDT

I have an Azure environment with multiple subscriptions and resources. My requirement is to have a functionality where if I pass a user name or SPN name, it gives me all azure resources (from management group to azure resource) where that user/spn has access to and what access it is (reader/ data reader etc).

Major catch is - I want PIM role assignments too. Is there a way to get it?

Options explored

  1. https://docs.microsoft.com/en-us/rest/api/authorization/role-assignments but this gives role assignments per scope. I want per user/spn
  2. https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-list-portal it does not cover PIM assignments and gives assignments per subscription only
  3. Azure Resource Graph Explorer - this does not cover role assignments at all

Apart from iterating through 50 subscriptions, fetching role assignments per scope and then comparing object id, is there any better way?

Fetching JSON from API, adding it to sqlite3 database and automatically fetching the next page

Posted: 06 Sep 2021 07:55 AM PDT

I'm busy trying to add data that is being collected from an API to a sqlite3 database and afterwards extracting the next page, loading that page and adding that data to the database until there is no more next page (next_is_after).

Loading the data is working well (thanks to another user) but when I'm trying to load it as a list the formatting is faulty and when I'm loading it as a dictionary it works well but I'm struggling to load it into the database.

I have no clue how to achieve the loop of loading the next page as it isn't a "normal" page number but a code (e.g. "WzExNDEuMTYsNTYwNTkzNTFd").

I have attached the code where I'm at below. I would again appreciate any help.

import requests  import json  import sqlite3    con = sqlite3.connect('takealot.db')  cur = con.cursor()    cur.execute('''CREATE TABLE IF NOT EXISTS products                      (sku text PRIMARY KEY, title text, slug text, reviews integer, star_rating real, listing_price real, pretty_price real)''')    baseurl = 'https://api.takealot.com/rest/v-1-10-0/searches/products,filters,facets,sort_options,breadcrumbs,slots_audience,context,seo'  endpoint = '?after=WzExNDEuMTYsNTYwNTkzNTFd'    def main_request(baseurl, endpoint):      res = requests.get(baseurl + endpoint)      return res.json()    daten = main_request(baseurl, endpoint)    next_is_after = daten['sections']['products']['paging']['next_is_after']    prodlist = []  for data in daten['sections']['products']['results']:      prod = {          'sku': data['product_views']['core']['id'],          'title': data['product_views']['core']['title'],          'slug': data['product_views']['core']['slug'],          'reviews': data['product_views']['core']['reviews'],          'star_rating': data['product_views']['core']['star_rating'],          'listing_price': data['product_views']['buybox_summary']['listing_price'],          'pretty_price': data['product_views']['buybox_summary']['pretty_price']      }      prodlist.append(prod)      cur.executemany("INSERT OR IGNORE INTO products VALUES (?, ?, ?, ?, ?, ?, ?)", [prod['sku'], prod['title'], prod['slug'], prod['reviews'], prod['star_rating'], prod['listing_price'], prod['pretty_price']])  con.commit()    for row in cur.execute('''SELECT * FROM products'''):      print(row)

fail run scripts - Uncaught SyntaxError: Unexpected token '<'

Posted: 06 Sep 2021 07:56 AM PDT

I have an html aspx, and I believe your scripts are not loading. I believe this because every time I comment on one of the scripts, it's one less error on the console.

images/prints:

initially with 11 errors

10 errors after commenting one of the scripts

And the funniest thing is that the path of the files is right, as it is also set for css.

Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" %>    <!DOCTYPE html>  <html lang="pt-br">  <head runat="server">      <meta charset="utf-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <meta name="viewport" content="width=device-width, initial-scale=1">        <script src="https://www.google.com/recaptcha/api.js" type="text/javascript"></script>        <!-- Bootstrap -->      <link href="<%= ResolveUrl("~/css/bootstrap.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/docs.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/bootstrap-datepicker.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/bootstrap-datepicker3.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/bootstrap-datetimepicker.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/bootstrap-multiselect.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/select2.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/bootstrap-switch.min.css")%>" rel="stylesheet" />      <link href="<%= ResolveUrl("~/css/main.css")%>" rel="stylesheet" />                <script src="<%= ResolveUrl("~/js/jquery3.5.1.js")%>"></script>      <script src="<%= ResolveUrl("~/js/jquery-ui-1.11.4.min.js")%>"></script>        <script src="<%= ResolveUrl("~/js/bootstrap.js")%>"></script>      <script src="<%= ResolveUrl("~/js/bootstrap-datepicker.min.js")%>"></script>      <script src="<%= ResolveUrl("~/js/bootstrap-datetimepicker.min.js")%>"></script>      <script src="<%= ResolveUrl("~/js/locales/bootstrap-datepicker.pt-BR.min.js")%>"></script>      <script src="<%= ResolveUrl("~/js/bootstrap-switch.min.js")%>"></script>      <script src="<%= ResolveUrl("~/js/bootstrap3-typeahead.min.js")%>"></script>      <script src="<%= ResolveUrl("~/js/bootstrap-multiselect.js")%>"></script>      <script src="<%= ResolveUrl("~/js/jquery.mask.js")%>"></script>      <script src="<%= ResolveUrl("~/js/main.js")%>"></script>            <script>          //Remover focus dos campos na tela          function removeFocus(campo) {              $("#" + campo.id).blur();          }      </script>        </head>  

if I use '<link href="' it finds, but I find it doesn't work correctly. Can anyone help me?

Response for VDWWD:

Response for VDWWD

Accessing rememberLauncherForActivityResult from Util / Jetpack Composee

Posted: 06 Sep 2021 07:56 AM PDT

I have a photo composable that allows the user to pickup the photo from the their mobile gallery.

I want to have this function/service from Util class/Function because i have other composable that needs the same service and i don't want to keep copy/pasting the same code. also this allows me to use it to pick up documents by changing the Mime type from launch { } but this looks tricky for me. if i use a @Composable function, i can't use the .launch also if i kept it as a class with a value the rememberLauncherForActivityResult needs Composable.

any help?

@OptIn(ExperimentalCoilApi::class)  @Composable  fun ContactPagePhoto() {      val imageUriState = remember {          mutableStateOf<Uri?>(null)      }      val pickingUp = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) {          imageUriState.value = it      }      Box(          contentAlignment = Alignment.Center,          modifier = Modifier              .layoutId("userPhoto")              .fillMaxHeight(0.4f)              .fillMaxWidth(1f)      ) {          imageUriState.value?.let {              Image(                  modifier = Modifier                      .align(Alignment.TopCenter)                      .fillMaxSize(1f),                  contentDescription = "UserImage",                  contentScale = ContentScale.Crop,                  painter = rememberImagePainter(data = it)              )          }      }      TextButton(          onClick = { pickingUp.launch("image/*") },          modifier = Modifier.layoutId("changePhoto")      ) {          Text(              text = "Change Photo",          color = Color.Black)      }  }  

how i expect to use it... inside ``util``` package i want to create a new kotlin file that has the service i need

I may use a @Composable function that allow me to use rememberLauncherForActivityResult or make a class and extend it to MainActivity to gain access to ComponentActivity() and use registerForActivityResult to get the Uri

like

class PickUp(){  val launcher = registerForActivityResult...  }  

or

@Composable  fun pickup():MutableState<Uri>{  rememberLauncherForActivityResult ...  }  

just suggesting...

[python-sphinx]how to add ref in paragraph

Posted: 06 Sep 2021 07:55 AM PDT

as you can see my sphinx code:

.. _ok:    abcdefg  """"""""""""    check :ref:`ok`    ::        you cen check :ref:`ok`  

show

in paragraph the ref is not work.

how to use ref in '::', how to use ref in paragraph

Is it possible to link object files generated from the Go toolchain using gcc/clang linker?

Posted: 06 Sep 2021 07:55 AM PDT

executable files built by the Go compiler are not compatible on target environment as the loader expects program sections to be in specific order.

As a result, I'm trying to compile the Go source using go tool compile to generate .o files, which I want to link using the gcc/clang linker option instead of go tool link

Does the object files generated from go build are compatible to be linked with gcc/clang toolchain ?

Mysql Duplicates

Posted: 06 Sep 2021 07:56 AM PDT

I would like to avoid duplicate entires in DB.

  1. In php i check if record exists, before insert takes place.
$lead = $CI->db->get_where(db_prefix(). 'leads', ['fbid' => $sender]);  if ($lead->num_rows() == 0) {      $CI->social_model->create($sender);  }  
  1. In mysql i have UNIQUE parameter set to fbid.

Issue is that sometimes facebook sends identical queries at the same time, and my php check fails because of that reason. I was wondering if there is any way to avoid duplicates on mysql end for the queries that are sent at the same time. (or any other way is welcome)

How to add custom class to body element for some routes - nexjts

Posted: 06 Sep 2021 07:56 AM PDT

I want to add my custom class to some pages. for example

all pages must be this class fixed-header exception this routes:

/cart/step-1     /login  

this class add or remove to body element.

<body className="bg-gray fixed-header"   

but I don't know how I can handle this scenario?

How to retrieve child from Firebase Database with a randomkey into recycler view in Android?

Posted: 06 Sep 2021 07:56 AM PDT

I'm actually new to Android programming, but I want to retrieve a child (comment) from Firebase Database with a random key into RecyclerView. I've written some code but when I launch the application the child (comment) does not show it does not also give me any error. Please help, thanks in advance.

My firebase database image

My Java Code:

private String commentsID = "";  private ImageView imageView, share, commentimage, profileimage, newslikeimage, send;  private TextView heading, description, newsdate, newstime, newscounter, sharecounter, newcommentcounter, profilename;  private String commentsend, commentcurrentusers, newcommentcurrentusers;  private EditText writecomment;  private DatabaseReference commentRef;  private RecyclerView.LayoutManager layoutManager;  private RecyclerView recyclerView;    private String saveCurrentDate, saveCurrentTime, commentRandomKey;    @Override  protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_comment);        commentRef = FirebaseDatabase.getInstance().getReference().child("Comments");            recyclerView = findViewById(R.id.commentrecycler);      recyclerView.setHasFixedSize(true);      layoutManager = new LinearLayoutManager(this);      recyclerView.setLayoutManager(layoutManager);      recyclerView.setLayoutManager(layoutManager);        commentsID = getIntent().getStringExtra("comments");        imageView = findViewById(R.id. newsimage);      heading = findViewById(R.id. newsname);      description = findViewById(R.id. newsdescription);      newsdate = findViewById(R.id. newdate);      newstime = findViewById(R.id. newtime);      newscounter = findViewById(R.id. newcounter);      sharecounter = findViewById(R.id. sharecounter);      commentimage = findViewById(R.id. commentimage);      newcommentcounter = findViewById(R.id. newcommentcounter);        newslikeimage = findViewById(R.id. newslike);      share = findViewById(R.id. share);      profileimage = findViewById(R.id. profileimage);      profilename = findViewById(R.id. profilename);      send = findViewById(R.id. send);      writecomment = findViewById(R.id. sendcomment);  }    @Override  protected void onStart() {      super.onStart();        FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();      newcommentcurrentusers = currentuser.getUid();        getCommentsDetails(commentsID);          send.setOnClickListener(new View.OnClickListener() {          @Override          public void onClick(View v)          {              commentsend = writecomment.getText().toString();                if (TextUtils.isEmpty(commentsend))              {                  Toast.makeText(CommentActivity.this, "Please type your comment", Toast.LENGTH_SHORT).show();              }              else              {                  sendingCommentsToFirebase();              }            }      });        FirebaseRecyclerOptions<Comment> options =              new FirebaseRecyclerOptions.Builder<Comment>()                      .setQuery(commentRef, Comment.class)                      .build();        FirebaseRecyclerAdapter<Comment, CommentsViewHolder> adapter =              new FirebaseRecyclerAdapter<Comment, CommentsViewHolder>(options) {                  @Override                  protected void onBindViewHolder(@NonNull CommentsViewHolder holder, int position, @NonNull Comment model) {                        holder.comment.setText(model.getComments());                  }                    @NonNull                  @Override                  public CommentsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {                      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item_layout, parent, false);                      CommentsViewHolder holder = new CommentsViewHolder(view);                      return holder;                  }              };      recyclerView.setAdapter(adapter);      adapter.startListening();  }    private void sendingCommentsToFirebase()  {      FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();      commentcurrentusers = currentuser.getUid();        Calendar calendar = Calendar.getInstance();        SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");      saveCurrentDate = currentDate.format(calendar.getTime());        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");      saveCurrentTime = currentTime.format(calendar.getTime());        commentRandomKey = saveCurrentDate + saveCurrentTime;        HashMap<String, Object> commentMap = new HashMap<>();      commentMap.put("comments", commentsend);      commentMap.put("userID", commentcurrentusers);      commentMap.put("newspid", commentRandomKey);        commentRef.child(commentsID).push().setValue(commentMap).addOnCompleteListener(new OnCompleteListener<Void>() {          @Override          public void onComplete(@NonNull  Task<Void> task)          {              if (task.isSuccessful())              {                  Toast.makeText(CommentActivity.this, "Comments added", Toast.LENGTH_SHORT).show();                }          }      });  }    private void getCommentsDetails(String commentsID) {      DatabaseReference newsRef = FirebaseDatabase.getInstance().getReference().child("News");        newsRef.child(commentsID).addValueEventListener(new ValueEventListener() {          @Override          public void onDataChange(@NonNull DataSnapshot snapshot) {              if (snapshot.exists()) {                  News news = snapshot.getValue(News.class);                    heading.setText(news.getHeading());                  description.setText(news.getDecription());                  profilename.setText(news.getUsername());                  newsdate.setText(news.getDate());                  newstime.setText(news.getTime());                  newscounter.setText(news.getLikes());                  sharecounter.setText(news.getShare());                  newcommentcounter.setText(news.getComment());                    Picasso.get().load(news.getProfileimage()).into(profileimage);                  Picasso.get().load(news.getImage()).into(imageView);              }          }            @Override          public void onCancelled(@NonNull DatabaseError error) {            }      });  

This is my View Holder

public class CommentActivity extends AppCompatActivity  {      private String commentsID = "";      private ImageView imageView, share, commentimage, profileimage, newslikeimage, send;      private TextView heading, description, newsdate, newstime, newscounter, sharecounter, newcommentcounter, profilename;      private String commentsend, commentcurrentusers, newcommentcurrentusers;      private EditText writecomment;      private DatabaseReference commentRef;      private RecyclerView.LayoutManager layoutManager;      private RecyclerView recyclerView;        private String saveCurrentDate, saveCurrentTime, commentRandomKey;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_comment);            commentRef = FirebaseDatabase.getInstance().getReference().child("Comments");                    recyclerView = findViewById(R.id.commentrecycler);          recyclerView.setHasFixedSize(true);          layoutManager = new LinearLayoutManager(this);          recyclerView.setLayoutManager(layoutManager);          recyclerView.setLayoutManager(layoutManager);            commentsID = getIntent().getStringExtra("comments");            imageView = findViewById(R.id. newsimage);          heading = findViewById(R.id. newsname);          description = findViewById(R.id. newsdescription);          newsdate = findViewById(R.id. newdate);          newstime = findViewById(R.id. newtime);          newscounter = findViewById(R.id. newcounter);          sharecounter = findViewById(R.id. sharecounter);          commentimage = findViewById(R.id. commentimage);          newcommentcounter = findViewById(R.id. newcommentcounter);            newslikeimage = findViewById(R.id. newslike);          share = findViewById(R.id. share);          profileimage = findViewById(R.id. profileimage);          profilename = findViewById(R.id. profilename);          send = findViewById(R.id. send);          writecomment = findViewById(R.id. sendcomment);      }        @Override      protected void onStart() {          super.onStart();            FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();          newcommentcurrentusers = currentuser.getUid();            getCommentsDetails(commentsID);            send.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v)              {                  commentsend = writecomment.getText().toString();                    if (TextUtils.isEmpty(commentsend))                  {                      Toast.makeText(CommentActivity.this, "Please type your comment", Toast.LENGTH_SHORT).show();                  }                  else                  {                      sendingCommentsToFirebase();                  }                }          });            FirebaseRecyclerOptions<Comment> options =                  new FirebaseRecyclerOptions.Builder<Comment>()                          .setQuery(commentRef, Comment.class)                          .build();            FirebaseRecyclerAdapter<Comment, CommentsViewHolder> adapter =                  new FirebaseRecyclerAdapter<Comment, CommentsViewHolder>(options) {                      @Override                      protected void onBindViewHolder(@NonNull CommentsViewHolder holder, int position, @NonNull Comment model) {                            holder.comment.setText(model.getComments());                      }                        @NonNull                      @Override                      public CommentsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {                          View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item_layout, parent, false);                          CommentsViewHolder holder = new CommentsViewHolder(view);                          return holder;                      }                  };          recyclerView.setAdapter(adapter);          adapter.startListening();      }        private void sendingCommentsToFirebase()      {          FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();          commentcurrentusers = currentuser.getUid();            Calendar calendar = Calendar.getInstance();            SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");          saveCurrentDate = currentDate.format(calendar.getTime());            SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");          saveCurrentTime = currentTime.format(calendar.getTime());            commentRandomKey = saveCurrentDate + saveCurrentTime;            HashMap<String, Object> commentMap = new HashMap<>();          commentMap.put("comments", commentsend);          commentMap.put("userID", commentcurrentusers);          commentMap.put("newspid", commentRandomKey);            commentRef.child(commentsID).push().setValue(commentMap).addOnCompleteListener(new OnCompleteListener<Void>() {              @Override              public void onComplete(@NonNull  Task<Void> task)              {                  if (task.isSuccessful())                  {                      Toast.makeText(CommentActivity.this, "Comments added", Toast.LENGTH_SHORT).show();                    }                }          });        }        private void getCommentsDetails(String commentsID) {          DatabaseReference newsRef = FirebaseDatabase.getInstance().getReference().child("News");            newsRef.child(commentsID).addValueEventListener(new ValueEventListener() {              @Override              public void onDataChange(@NonNull DataSnapshot snapshot) {                  if (snapshot.exists()) {                      News news = snapshot.getValue(News.class);                        heading.setText(news.getHeading());                      description.setText(news.getDecription());                      profilename.setText(news.getUsername());                      newsdate.setText(news.getDate());                      newstime.setText(news.getTime());                      newscounter.setText(news.getLikes());                      sharecounter.setText(news.getShare());                      newcommentcounter.setText(news.getComment());                        Picasso.get().load(news.getProfileimage()).into(profileimage);                      Picasso.get().load(news.getImage()).into(imageView);                  }              }                @Override              public void onCancelled(@NonNull DatabaseError error) {                }          });      }  }  

This is my Class:

public class Comment  {      private String comments, newspid, userID;        private Comment()      {        }        public Comment(String comments, String newspid, String userID) {          this.comments = comments;          this.newspid = newspid;          this.userID = userID;      }        public String getComments() {          return comments;      }        public void setComments(String comments) {          this.comments = comments;      }        public String getNewspid() {          return newspid;      }        public void setNewspid(String newspid) {          this.newspid = newspid;      }        public String getUserID() {          return userID;      }        public void setUserID(String userID) {          this.userID = userID;      }  }  

Animating multiple circles in a canvas

Posted: 06 Sep 2021 07:55 AM PDT

I'm trying to make an animation inside a canvas: here, a numbered circle must be drawn and move from left to right one single time, disappearing as soon as it reaches the end of animation.

For now I managed to animate it in loop, but I need to animate at the same time (or with a set delay) multiple numbered circles, strating in different rows (changing y position) so they wont overlap.

Any idea how can I manage this? my JS code is the following:

// Single Animated Circle - Get Canvas element by Id  var canvas = document.getElementById("canvas");    // Set Canvas dimensions  canvas.width = 300;  canvas.height = 900;    // Get drawing context  var ctx = canvas.getContext("2d");    // Radius  var radius = 13;  // Starting Position  var x = radius;  var y = radius;    // Speed in x and y direction  var dx = 1;  var dy = 0;    // Generate random number  var randomNumber = Math.floor(Math.random() * 60) + 1;    if (randomNumber > 0 && randomNumber <= 10) {    ctx.strokeStyle = "#0b0bf1";  } else if (randomNumber > 10 && randomNumber <= 20) {    ctx.strokeStyle = "#f10b0b";  } else if (randomNumber > 20 && randomNumber <= 30) {    ctx.strokeStyle = "#0bf163";  } else if (randomNumber > 30 && randomNumber <= 40) {    ctx.strokeStyle = "#f1da0b";  } else if (randomNumber > 40 && randomNumber <= 50) {    ctx.strokeStyle = "#950bf1";  } else if (randomNumber > 50 && randomNumber <= 60) {    ctx.strokeStyle = "#0bf1e5";  }    function animate3() {    requestAnimationFrame(animate3);      ctx.clearRect(0, 0, 300, 900);      if (x + radius > 300 || x - radius < 0) {      x = radius;    }      x += dx;      ctx.beginPath();    ctx.arc(x, y, 12, 0, Math.PI * 2, false);    ctx.stroke();    ctx.fillText(randomNumber, x - 5, y + 3);  }    // Animate the Circle    animate3();
<canvas id="canvas"></canvas>

Python: parallel processing while yielding

Posted: 06 Sep 2021 07:55 AM PDT

I am creating a generator of the lines in a list of files, my approach is something like:

def load(f_name: str):      with open(f_name, "r") as f:          lines = f.readlines()      # some calculations      return lines    def iter_files(f_names: list):      for f in f_names:          for line in load(f):              yield line  

What I would like to do, if possible and useful, is to load the next file while yielding on another. Being completely new to multiprocessing I tried the following:

cache = dict()    def load(f_name: str, id: int):      global cache      with open(f_name, "r") as f:          lines = f.readlines()      # some calculations      cache[id] = lines    def iter_list(arr):      for x in arr:          yield x    def iter_files(f_names: list):      global cache      num_files = len(f_names)      load(f_names[0], 0)      for n in range(num_files - 1):          current = mp.Process(target=iter_list, args=(cache[n],))          next = mp.Process(target=load, args=(f_names[n + 1], n + 1))          current.start()          next.start()          current.join()          next.join()          del cache[n]      iter_list(cache[num_files - 1])      del cache[num_files - 1]  

But besides looking overly complicated, its not working.

First if I don't put the main code into an 'if __name__ == "__main__":' (which I would rather not be mandatory) I get the following error:

RuntimeError:        An attempt has been made to start a new process before the        current process has finished its bootstrapping phase.  

But even if I do the files are not added to the cache:

current = mp.Process(target=iter_list, args=(cache[n],))  KeyError: 1  

Is it possible to achieve what I am trying to do? What am I doing wrong?

Thank you all

Yii2 Activerecord not saved before redirect and shown in "view"

Posted: 06 Sep 2021 07:55 AM PDT

Yii2 framework. When I save multiple ActiveRecords in AFTER_INSERT_EVENT of another ActiveRecord, the values in the database is not updated fast enough, so old values are shown when redirect to viewing the data.

To be more specific: Standard XAMPP environment with PHP 7.2.9. I have made a trait to make it easy to have extra attributes with history in model (either existing attributes or new attributes). The trait is used on ActiveRecord.

Notice the sleep(5) in function TL_save. This handled the problem, but it is not the correct solution. How do I ensure all is updated before it is read again? I want to avoid use locks on the row as that would require alteration of a table before it can be used. Is there a way around it? Transactions - I have tried it but perhaps not correct as it had no effect. A reload of the view page also solves the problem, but again: not very classy :-)

Also: Should I share this code on GitHub? I have not done so before and are not quite sure if it would be of any value to others really.

trait TimelineTrait  {         private $timelineConfig;        public function timelineInit($config)      {          $std = [              'attributes' => [],  // required              '_oldAttributes'=>[],              'datetime'=> date('Y-m-d H:i:s'),              'validationRule'=>'safe',              'table'=>$this->tableName(),              'onlyDirty'=>true, // using !=, not !==              'events'=>[                  self::EVENT_AFTER_INSERT=>[$this, 'TL_EventAfterInsert'],                  self::EVENT_AFTER_UPDATE=>[$this, 'TL_EventAfterUpdate'],                  self::EVENT_AFTER_FIND=>[$this, 'TL_EventAfterFind'],                  self::EVENT_AFTER_DELETE=>[$this, 'TL_EventAfterDelete'],              ],              'TimelineClass'=>Timeline::class,              /*                  Must have the following attributes                  id integer primary key auto increment not null,                  table varchar(64) not null,                  table_id integer not null,                  attribute varchar(64) not null,                  datetime datetime not null                  value text (can be null)              */          ];          $this->timelineConfig = array_replace_recursive($std, $config);          foreach($this->timelineConfig["events"]??[] as $trigger=>$handler)              $this->on($trigger, $handler);      }        public function __get($attr)      {                  $cfg = &$this->timelineConfig;          if (in_array($attr, array_keys($cfg["attributes"])))              return $cfg["attributes"][$attr];          else              return parent::__get($attr);      }        public function __set($attr, $val)      {                  $cfg = &$this->timelineConfig;                  if (in_array($attr, array_keys($cfg["attributes"]))) {              $cfg["attributes"][$attr] = $val;                      } else              parent::__set($attr, $val);      }        public function attributes()      {          return array_merge(parent::attributes(), $this->timelineConfig["attributes"]);      }        public function rules()      {          $temp  = parent::rules();          $temp[] = [array_keys($this->timelineConfig["attributes"]), $this->timelineConfig["validationRule"]];          return $temp;      }        public function TL_EventAfterInsert($event)       {          $this->TL_save($event, true);      }        public  function TL_EventAfterUpdate($event)      {          $this->TL_save($event, false);      }        private function TL_save($event, $insert)       {          $cfg = &$this->timelineConfig;              if ($cfg["onlyDirty"])               $cfg["_oldAttributes"] = $this->TL_attributesOnTime();                           foreach($cfg["attributes"] as $attr=>$val) {              $a = [                  'table'=>$cfg["table"],                   'table_id'=>$this->id,                  'attribute'=>$attr,                  'datetime'=>$cfg["datetime"],              ];                if ($insert)                  $model=null;              else                   $model = Timeline::find()->where($a)->one();                $isNew = empty($model); // this exact attribute does not exist on timeline already                if ($isNew)                   $model = new $cfg["TimelineClass"]($a);                $model->value = $val;                           if (!$cfg["onlyDirty"]                   || $cfg["onlyDirty"] && $model->value!=($cfg["_oldAttributes"][$attr]??\uniqid('force_true'))) {                                    $ok = $model->save();                  if (!$ok) $this->addErrors($attr, $model->getErrorSummary());              }           }          sleep(5);              }        public function TL_EventAfterFind($event)      {          $cfg = &$this->timelineConfig;          $data = $this->TL_attributesOnTime();          foreach($data as $attr=>$val)              $cfg["attributes"][$attr] = $val;            $cfg["_oldAttributes"] = $cfg["attributes"];      }        private function TL_attributesOnTime()      {          $cfg = &$this->timelineConfig;          $timelineTable = $cfg["TimelineClass"]::tableName();                            $sql = "SELECT t1.* FROM $timelineTable AS t1                  LEFT JOIN (SELECT * FROM $timelineTable WHERE `table`=:table AND table_id=:table_id AND datetime<=:datetime) AS t2                  ON (t1.table=t2.table and t1.table_id=t2.table_id and t1.datetime<t2.datetime AND t1.attribute=t2.attribute)                  WHERE t2.id IS NULL AND t1.datetime<:datetime AND t1.table=:table AND t1.table_id=:table_id                  ";          $params = [              'table'=>$cfg["table"],              'table_id'=>$this->id,              ':datetime'=>$cfg["datetime"],          ];                  $data = \Yii::$app->db->createCommand($sql,$params)->queryAll();          $data = ArrayHelper::map($data,'attribute','value');                  return $data;      }        public function TL_EventAFterDelete($event)       {          $cfg = &$this->timelineConfig;          $cfg["TimelineClass"]::deleteAll([              'table'=>$cfg["table"],              'table_id'=>$event->sender->id          ]);      }    }  

Example of it's use:

<?php  namespace app\models;    class KeyTime extends Key  {      use \app\behaviors\TimelineTrait;        public function init()      {          parent::init();          $this->timelineInit([              'attributes'=>[                  // default values for attributes                  'keyid'=>'historic id', // this is existing attribute in Key model                  'label'=>'mylabel', // label and color does not exist in Key model                  'color'=>'red',              ],             ]);      }  }  

The actionUpdate

   public function actionUpdate($id)      {          $model = $this->findModel($id);            if ($model->load(Yii::$app->request->post()) && $model->save()) {              return $this->redirect(['view', 'id' => $model->id]);          }            return $this->render('update', [              'model' => $model,          ]);      }  

How implement indexedDB to Cypress tests?

Posted: 06 Sep 2021 07:55 AM PDT

I want to test my app that use indexedDB, and becouse of indexedDB my tests dont work, shoud I set up indexedDB for tests, and what correct way to do it.

Me code

import Dexie from 'dexie';      describe('The Login Page', () => {    before(() => {      const db = new Dexie("timesheetsDB");      db.version(1).stores({        user: 'id, name, email, company, active, isAdmin, *permissions',        userCompanies: '++,name',        rules: 'permissionId, name',      });    })      beforeEach(() => {      connectDB((data)=>{        console.log('db open', data)      })        cy.request({        method: 'POST',        url: 'http://localhost:3000/api/auth/login',        body: {          email: "admin@gmail.com",          password: "password"        }      }).then(function (response) {        cy.log(JSON.stringify(response.body.payload))      }).then(() => {        cy.visit("http://localhost:3000/home");      })    })  })  

Component that I want to test use indexedDB requests for first component load, and I get error from cypress

Unhandled Rejection (OpenFailedError): UnknownError Internal error opening backing store for indexedDB.open.   UnknownError: Internal error opening backing store for indexedDB.open.  

I just want to now way to run tests, and open indexedDB connection for end to end cypress enviroment.

Dash Plotly triggering callbacks

Posted: 06 Sep 2021 07:55 AM PDT

I have a live-updating graph that connects to an SQL database. On page loading, the user inputs credentials and the appropriate data is loaded and displayed. I noticed that the lag time to load the data is related to the "dcc.interval" interval setting. This timer triggers the callback. However, when I added a "submit" button, to the callback input this does not trigger the callback, instead the callback awaits the "Interval" time before firing. My Question is: How can I get the callback to fire on button "submit" and not on 'interval' time on initial load?

dcc.Interval(                      id='graph-update2',                      interval=60000,                      n_intervals=0),  
@app.callback(      dash.dependencies.Output('live-graph', 'figure'),      [dash.dependencies.Input('graph-update-BP', 'n_intervals')],      Input('submit-val', 'n_clicks'),      Input('data_list', 'data'),  )  def update_graph_scatter_1(n,submit, data_list):      if data_list == 'null' or data_list is None:          raise PreventUpdate        else: ....      

How to get logs from kubernetes using Go?

Posted: 06 Sep 2021 07:56 AM PDT

I'm looking for the solution of how to get logs from a pod in Kubernetes cluster using Go. I've looked at "https://github.com/kubernetes/client-go" and "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client", but couldn't understand how to use them for this purpose. I have no issues getting information of a pod or any other object in K8S except for logs.

For example, I'm using Get() from "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client#example-Client--Get" to get K8S job info:

found := &batchv1.Job{}  err = r.client.Get(context.TODO(), types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)  

Please share of how you get pod's logs nowadays. Any suggestions would be appreciated!

Update: The solution provided in Kubernetes go client api for log of a particular pod is out of date. It have some tips, but it is not up to date with current libraries.

Why doesn't GCC show vectorization information?

Posted: 06 Sep 2021 07:56 AM PDT

I'm using Codeblocks for a C program on Windows 7. The program is using the OMP library. GCC version is 4.9.2. Mingw x86_64-w64-mingw32-gcc-4.9.2.exe.

Flags used are: -fopenmp -O3 -mfpmath=sse -funroll-loops -ftree-loop-distribution -ftree-vectorize -ftree-vectorizer-verbose=2.

The program runs correctly but the problem is that it doesn't show information on what loops were vectorized or not. How can I solve it?

Build log info:

-------------- Build: Release in **** (compiler: GNU GCC Compiler)---------------

x86_64-w64-mingw32-gcc-4.9.2.exe -Wall -O2 -march=corei7 -fexpensive-optimizations -O3 -fopenmp -mfpmath=sse -funroll-loops -ftree-loop-distribution -ftree-vectorize -ftree-vectorizer-verbose=2 -c C:\Users...\f.c -o obj\Release\f.o x86_64-w64-mingw32-g++.exe -o bin\Release\d.exe obj\Release\f.o obj\Release\main.o -s "C:\Program Files...\libgomp-1.dll" Output file is bin\Release\d.exe with size 21.00 KB Process terminated with status 0 (0 minute(s), 0 second(s)) 0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

How can I pass an array as an argument to a Rake task?

Posted: 06 Sep 2021 07:55 AM PDT

I'm writing a Rake task and I want to pass an array as one of the arguments. Here's how I currently have it.

task :change_statuses, :ids, :current_status, :new_status do |task, args|    puts "args were #{args.inspect}"  end  

I've tried running the task these ways:

# First argument as array  rake "change_statuses[[1,2,3], active, inactive]"    # First argument as string  rake "utility:change_account_statuses['1,2,3', foo, bar]"  

My expected output would be:

args were {:ids=> [1,2,3], :current_status=> 2 , :new_status=> 3}  

However, my actual output in each case is:

args were {:ids=>"[1", :current_status=>"2", :new_status=>"3]"}  

How can I pass an array to a Rake task?

No comments:

Post a Comment