Sunday, June 6, 2021

Posts from Recent Questions - Stack Overflow for 06/06/2021

View this email in your browser
Updates from https://stackoverflow.com/questions

Recent Questions - Stack Overflow



In the 06/06/2021 edition:

How can i merge between text and pickle file in runtime?

By mohe on Jun 06, 2021 03:59 am

I got pickle file with vectors for images using mmdetection class here Link

but the result gave me the vectors only without the image_id for each vector .. so i tried to change some lines as below

if isinstance(result[0], tuple):              result = [(bbox_results, encode_mask_results(mask_results))                                for bbox_results, mask_results in result]          data1.append(img_meta['ori_filename'])          images=          f=open('file.txt','w')          for i in data1:              i=re.sub('.jpg', '', i)              i=i.replace("COCO_val2014_", '')              f.write(i+os.linesep)              images.append(i)          d={}          d= dict(zip(images, result))          with open('filename.pkl','wb') as f1:                  pickle.dump(d, f1)            results.extend(d)          for _ in range(batch_size):              prog_bar.update()          return results  

but the number of vectors are changed

and gave me the only image_id

the original one was

[[array([3.43202576e+02, 2.43713760e+01, 4.96343414e+02, 3.32774170e+02,        8.81948233e-01],       [4.71771484e+02, 1.72076767e+02  

and what i got is

{'000000391895': [array([3.48745178e+02, 1.64561447e+02, 4.19237061e+02, 3.62992340e+02,        9.35315311e-01], dtype=float32),array([[2.54942383e+02, …  

what i need is

{'000000391895': [array([3.48745178e+02, 1.64561447e+02, 4.19237061e+02, 3.62992340e+02,        9.35315311e-01], dtype=float32),'000000125498'array([2.54942383e+02, …  

Read in browser »
share on Twitter

How to use date values from mysql to create lavacharts calendar chart?

By Dan Agaba on Jun 06, 2021 03:58 am

I am trying to build a dynamic chart generator using Lavacharts where a user selects a search parameter and date range (from / to) then a calendar chart is generated displaying the record count values (Y- Axis) on the different dates(X Axis). I wanted to inquire how I may accomplish this using Lavacharts. I have found some information on http://lavacharts.com/#examples but nothing on how data pulled from mysql database can be used in Lavacharts.

public function birthChart(Request $request)  {      $lava = new Lavacharts;      $birth = $lava->CalendarChart();      $birth->addDateColumn('Date')            ->addNumberColumn('Births');      }  

Read in browser »
share on Twitter

How to keep disappearing Flutter Bottom Navigation and AppBar after navigating from subpages

By Share Knowledge on Jun 06, 2021 03:58 am

I have a bottom Tab bar in my app for navigation and appbar, from the menu page after adding products in Cart screen there is Continue button when i pressed it take me to Login screen, there a normal login with and otp verification, now when i try to navigate back to menu screen after successfull otp verification, i see Tab bar disappeared and the App bar.

How i can fix this problem enter image description here

enter image description here

enter image description here

enter image description here

enter image description here


Read in browser »
share on Twitter

How to insert javascript variables in sql

By Martin Seguel on Jun 06, 2021 03:56 am

i need to insert this variables in mi sql database, i have the config.inc.php configured for the conection to my database, but i dont know how to insert they.

function calc_spin_time(){      function num_rand(){          var num = Math.floor(Math.random()*((20)+20)-20);          return num;}      spinTimeTotal = Math.random() * 3 + 4 * 1000 + num_rand();      spinAngleStart = Math.random() * 10 + 10;      //I need to insert spinTimeTotal and SpinAngleStart into mi sql database  }  

Then, I need to read they and use them in a new javascript file.


Read in browser »
share on Twitter

My code has a problem with double datatype

By Ahmed Gouda on Jun 06, 2021 03:56 am

when I run my code with double or long long data types it seems like it has entered an infinity loop while it works fine with int data type

#include <iostream>  #include <math.h>  #include <iomanip>  #include <string>  #include <algorithm>    using namespace std;    int main()  {  double x,k,c=-1;  cin>>x>>k;    for (double i=1; i<=k; i++)  {      c+=2;      if (i==k)      {          cout<<c;          return 0;      }      if (c==x||c==x-1)          c=0;  }  }  

Read in browser »
share on Twitter

C language - Matching the data selected by the user with the words in the word list

By Nurettin Önder on Jun 06, 2021 03:55 am

I'm working on a project with C language, but I got stuck in a part of the project and I need your help.

I have a 4-digit number and a word list for that number:

Number Word
3565 Monkey
8752 Giraffe
1672 Dolphin
2795 Crocodile
1298 Lion
9076 Bird

My question is; When the user enters the data 8752 or the user randomly draws the number 8752, I want to print the word "Giraffe" corresponding to that number in the word list.


Read in browser »
share on Twitter

How to manage and extract particular data from nested Data structures in python

By Aayush on Jun 06, 2021 03:53 am
['[{"word":"meaning","phonetics":[{"text":"/ˈmiːnɪŋ/","audio":"https://lex-audio.useremarkable.com/mp3/meaning_gb_1.mp3"}],"meanings":[{"partOfSpeech":"noun","definitions":[{"definition":"What '   'is meant by a word, text, concept, or '   'action.","synonyms":["definition","sense","explanation","denotation","connotation","interpretation","elucidation","explication"],"example":"the '   'meaning of the Hindu word is 'breakthrough, '   'release'"}]},{"partOfSpeech":"adjective","definitions":[{"definition":"Intended '   'to communicate something that is not directly '   'expressed.","synonyms":["meaningful","significant","pointed","eloquent","expressive","pregnant","speaking","telltale","revealing","suggestive"]}]}]}]']  

This is the format.

I wanna extract:

"meanings":[{"partOfSpeech":"noun","definitions":[{"definition":"A single distinct meaningful element of speech or writing, used with others (or sometimes alone) to form a sentence and typically shown with a space on either side when written or printed.",  

How may I do it, in Python. Please Help as I am new to Python

Thanks in Advance


Read in browser »
share on Twitter

I have created a PowerShell script for Displaying a Form. Looking for automating button click event

By pramod kumar on Jun 06, 2021 03:51 am

I have created a PowerShell script for Displaying a Form. Looking for automating button click event.

The form displays number of Tasks and I am planning to show the list of Tasks on the form. After running each task, dynamically update status of each task on the form.

I have created a TaskList funtion that runs after ButtonClick. The code for running each task and dynamically updating status of each task is mentioned in this function.

Only thing I am stuck at is to automate the button click event as soon as the form is launched. Then I can make the Button invisible.

Can anybody please suggest the way to automate button click or any other method to call the TaskList funtion


Read in browser »
share on Twitter

Create a user defined function that applies conditions to a pandas DataFrame?

By miquiztli_ on Jun 06, 2021 03:51 am

I'm trying to create a function that checks if any rows in a pandas DataFrame meet a list of conditions. If any are met, I want it to return a 1 to a newly created column called "Error", otherwise, it returns 0.

I created this function to apply the conditions, but it's not working:

def validation_error(row):      """      Conditions:        a. Service Type (col C) == 'NF' and Demonstration Type (col D) in ('COST', 'PERDIEM') AND              i. Validation category (col G) == 'Missing required data' and Fail column (col L) in (212.1, 212.2)        b. Service Type (col C) == 'OP' and Demonstration Type (col D) == 'COST' AND              i. (Validation category (col G) == 'Missing required data' and Fail column (col L)  == 205 OR              ii. Validation check (col H) == 'Data validations: Check selected fields for invalid negative values'              and Fail column (col L) == 205)        c. Issue severity (col I) == 'Critical - automatic rejection'      """      # create list of conditions to apply to extract rows      condition1 = (stacked_df['Issue severity'].str.lower().str.startswith('critical'))      if row['Service type'] == 'OP':          condition2 = ((stacked_df['Demonstration type'] == 'PAYMENT') & (stacked_df['Validation category']=='Missing required data') & (stacked_df['Fail column']=='205'))          condition3 = ((stacked_df['Demonstration type'] == 'PAYMENT') & (stacked_df['Validation check'].str.contains('invalid negative values')) & (stacked_df['Fail column']=='205'))      elif row['Service type'] == 'NF':          condition4 = ((stacked_df['Demonstration type'].isin(['COST','PERDIEM'])) & (stacked_df['Validation category']=='Missing required data') & (stacked_df['Fail column'].isin(['212.1','212.2'])))      return condition1 | condition2 | condition3 | condition4  

Basically, if the value in the column "Service Type" is equal to OP or NF, I want it to check for the conditions.

I also wrote this additional code that creates the new column and creates a new DataFrame with a column that checks if the conditions were met.

# Create a column called 'Error'  stacked_df['Error'] = stacked_df.apply(validation_error, axis=1)  # Create a new dataframe that meet the conditions list  filtered_df = stacked_df.loc[stacked_dfs['Error'] == 1]  

How would I include the above code within the "validation_error" function? Also, is there a more elegant way for me to apply the function? Thank you.


Read in browser »
share on Twitter

Checking if str1 can be re-arranged as str2 wth JavaScript

By Ömer Faruk Çalışkan on Jun 06, 2021 03:40 am

There are two strings called str1 and str2 and I'm trying to check if str1 can be re-arranged as str2.

function scramble(str1, str2) {      let arr=;    let str1arr =  str1.split("");    let str2arr =  str2.split("");    let j=0;      for(let i=0; i<str1.length; i++){      if(str1arr[i]==str2arr[j]){        arr.push(str1arr[i]);        str1arr=str1arr.splice(i,1);        j++;        i=0;        }      }if(arr.toString()===str2arr.toString()){      return true;    }else{      return false;    }      }  

What I tried basically if str1arr[i]==str2arr[j] it will put the str1arr[i] value on a new array called arr and at the end it will compare str2 and the arr and return True or False.

The reason why I used str1arr=str1arr.splice(i,1); to delete the i after the match is because the for loop is reseting it self to check from the "i=0" each time i and j matches and that i would match with other duplicate letters (I hope thats what it does atleast :D).

It is an internet question and im not passing the tests. I only pass if the result is FALSE.

I want to know what I'm doing and thinking wrong here. Its not performance efficent too so any comment on that would be great too.


Read in browser »
share on Twitter

pyglet gives error regarding GLSL version

By Erfan Hamdi on Jun 06, 2021 03:38 am

I am trying to run a code that has a GUI built with pyglet. but it gives this error. I have searched and found that I need to directly set the version of GLSL to be used by the code but I don't know how. would be happy if you helped me out with it.

b"0:20(27): error: cannot initialize uniform weight in GLSL 1.10 (GLSL 1.20 required)\n0:20(27): error: array constructors forbidden in GLSL 1.10 (GLSL 1.20 or GLSL ES 3.00 required)\n0:20(27): error: initializer of uniform variable `weight' must be a constant expression\n0:79(17): error: could not implicitly convert operands to arithmetic operator\n0:79(16): error: operands to arithmetic operators must be numeric\n0:89(7): warning: `coeff' used uninitialized\n"  

this is the shader.py file:
'''python

try:
print("loading shader.py")
except:
import sys
sys.stdout = open('stdout.txt', 'w')
sys.stderr = open('stderr.txt', 'w')

from pyglet.gl import *
from ctypes import *
import pyglet as pg

class Shader:
# vert, frag and geom take arrays of source strings # the arrays will be concattenated into one string by OpenGL
def init(self, vert = , frag = , geom = ):
# create the program handle
self.handle = glCreateProgram()
# we are not linked yet
self.linked = False

    # create the vertex shader      self.createShader(vert, GL_VERTEX_SHADER)      # create the fragment shader      self.createShader(frag, GL_FRAGMENT_SHADER)      # the geometry shader will be the same, once pyglet supports the extension      # self.createShader(frag, GL_GEOMETRY_SHADER_EXT)        # attempt to link the program      self.link()        self.renderquad = pg.graphics.Batch()      self.renderquad.add(4, pg.gl.GL_QUADS, None, ('v2i', (0, 0, 1, 0, 1, 1, 0, 1)), ('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))      def createShader(self, strings, type):      count = len(strings)      strings = map(lambda x: x.encode('ascii'), strings)      # if we have no source code, ignore this shader      if count < 1:          return        # create the shader handle      shader = glCreateShader(type)        # convert the source strings into a ctypes pointer-to-char array, and upload them      # this is deep, dark, dangerous black magick - don't try stuff like this at home!      src = (c_char_p * count)(*strings)      glShaderSource(shader, count, cast(pointer(src), POINTER(POINTER(c_char))), None)        # compile the shader      glCompileShader(shader)        temp = c_int(0)      # retrieve the compile status      glGetShaderiv(shader, GL_COMPILE_STATUS, byref(temp))        # if compilation failed, print the log      if not temp:          # retrieve the log length          glGetShaderiv(shader, GL_INFO_LOG_LENGTH, byref(temp))          # create a buffer for the log          buffer = create_string_buffer(temp.value)          # retrieve the log text          glGetShaderInfoLog(shader, temp, None, buffer)          # print the log to the console          print(buffer.value)      else:          # all is well, so attach the shader to the program          glAttachShader(self.handle, shader);    def link(self):      # link the program      glLinkProgram(self.handle)        temp = c_int(0)      # retrieve the link status      glGetProgramiv(self.handle, GL_LINK_STATUS, byref(temp))        # if linking failed, print the log      if not temp:          #    retrieve the log length          glGetProgramiv(self.handle, GL_INFO_LOG_LENGTH, byref(temp))          # create a buffer for the log          buffer = create_string_buffer(temp.value)          # retrieve the log text          glGetProgramInfoLog(self.handle, temp, None, buffer)          # print the log to the console          print(buffer.value)      else:          # all is well, so we are linked          self.linked = True    def bind(self):      # bind the program      glUseProgram(self.handle)    def unbind(self):      # unbind whatever program is currently bound - not necessarily this program,      # so this should probably be a class method instead      glUseProgram(0)    # upload a floating point uniform  # this program must be currently bound  def uniformf(self, name, *vals):      # check there are 1-4 values      if len(vals) in range(1, 5):          # select the correct function          { 1 : glUniform1f,              2 : glUniform2f,              3 : glUniform3f,              4 : glUniform4f              # retrieve the uniform location, and set          }[len(vals)](glGetUniformLocation(self.handle, name.encode('ascii')), *vals)    # upload a floating point uniform  # this program must be currently bound  def uniformfv(self, name, vsize, *vals):      # check there are 1-4 values      if vsize in range(1, 5):          # select the correct function          { 1 : glUniform1fv,              2 : glUniform2fv,              3 : glUniform3fv,              4 : glUniform4fv              # retrieve the uniform location, and set          }[vsize](glGetUniformLocation(self.handle, name.encode('ascii')), int(len(vals)/vsize), (GLfloat*(len(vals)))(*vals))    # upload an integer uniform  # this program must be currently bound  def uniformi(self, name, *vals):      # check there are 1-4 values      if len(vals) in range(1, 5):          # select the correct function          { 1 : glUniform1i,              2 : glUniform2i,              3 : glUniform3i,              4 : glUniform4i              # retrieve the uniform location, and set          }[len(vals)](glGetUniformLocation(self.handle, name.encode('ascii')), *vals)    # upload a uniform matrix  # works with matrices stored as lists,  # as well as euclid matrices  def uniform_matrixf(self, name, mat):      # obtian the uniform location      loc = glGetUniformLocation(self.handle, name.encode('ascii'))      # uplaod the 4x4 floating point matrix      glUniformMatrix4fv(loc, 1, False, (c_float * 16)(*mat))    def draw(self):      #Assume we're bound already      self.renderquad.draw()  

'''


Read in browser »
share on Twitter

What is the logical error in my buildHeap function?

By SubZero on Jun 06, 2021 03:34 am

I am trying to construct a minheap from an existing vector. My heapifyDown, HeapifyUp, insert, and extractMin functions seem to work fine - For example, I can use them to populate an empty array and retrieve the min.

But my buildHeap function seems incorrect. I can't figure out the logical error.

class MinHeap{      void heapifyDown(int index,vector<int> &array){          int leftIndex = 2*index + 1;          int rightIndex = 2*index + 2;          if(rightIndex < array.size()){              int smallerIndex = (array[leftIndex] < array[rightIndex] ? leftIndex : rightIndex);              if(array[index] > array[smallerIndex]){                  swap(array[index],array[smallerIndex]);                  heapifyDown(smallerIndex,array);              }          }else if(leftIndex < array.size()){             if(array[index] > array[leftIndex]){                  swap(array[index],array[leftIndex]);                  heapifyDown(leftIndex,array);              }          }      }        void heapifyUp(int index,vector<int> &array){          int parent = (index - 1)/2;          if(array[index]<array[parent]){              swap(array[index],array[parent]);              heapifyUp(parent,array);          }      }    public:      int extractMin(vector<int> &array){          int min = -1;          if(array.size()>0){              min = array[0];              array[0] = array[array.size()-1];              array.pop_back();              if(array.size()>0)              heapifyDown(0,array);          }          return min;      }        void insert(int value,vector<int> &array){          array.push_back(value);          heapifyUp((int)array.size()-1,array);      }        void buildHeap(vector<int> &array){          int startIndex = (int)array.size()/2 -1;          for(int i=startIndex; i >=0; i--){              heapifyDown(i,array);          }      }  };  

What is logically incorrect about my buildHeap function ?

The objective of the buildHeap function is to take an existing vector of numbers and convert it into a minheap.

The problem is that the buildHeap function does not convert the vector into a valid heap, and instead fills it with incorrect numbers.

An example of max-Heapify is here: https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_heapify_method.htm

I am trying to do the same, but with a minHeap instead of a maxHeap.


Read in browser »
share on Twitter

How to return item from .exec in mongoose, console.log in exec returns element but outside return undefined

By user5109293123 on Jun 06, 2021 03:33 am

I have asked this question .exec callback using returns is returning undefined, but console.log do have item in it

The answer does work, but it throws .exec away, I have been trying to re-implement it using .exec, however when I console.log something inside the .exec, it does print.

The reason I have been trying to use the .exec way is that a lot of StackOverflow questions use a lot .exec and I think ".exec" will be faster?

When I return it, it returns undefined. What is the cause and how can I solve it while keeping the .exec

let user = await User.findById(paymentBody.user_id)  .populate(User.schedule_table)  .exec((err, foundDocument) => {    console.log(foundDocuments)    return foundDocument;  });    console.log(user)  

The code inside .exec (console.log(foundDocuments)), returns the result of query.

However, when I perform console.log(user) after the query, it shows undefined.


Read in browser »
share on Twitter

javascript: how can I replace the select:after icon on click?

By Ashik on Jun 06, 2021 03:33 am

this is my icon style.

.select::after {      /* content           : "▼"; */      content: '▲';      position          : absolute;      top               : 0;      right             : 0;      padding           : 0 1em;      background        : #e100ff;      color             : #fff;      cursor            : pointer;      pointer-events    : none;      -webkit-transition: 0.25s all ease;      -o-transition     : 0.25s all ease;      transition        : 0.25s all ease;  }  

what I want is to replace the icon, when the icon is clicked. how can I achieve that?


Read in browser »
share on Twitter

Flutter Freezed - Add a generic field to a freezed class

By BeniaminoBaggins on Jun 06, 2021 02:59 am

How do I make a Freezed object take a generic type? I want to do this:

import 'package:freezed_annotation/freezed_annotation.dart';  import 'package:vepo/src/entity_types/option_entity.dart';    part 'vegan_item_tag.freezed.dart';  part 'vegan_item_tag.g.dart';    @freezed  abstract class VeganItemTag<T>      with _$VeganItemTag<T>      implements OptionEntity<T> {    const factory VeganItemTag({int? iconCodePoint, T? id, String? name}) =        _VeganItemTag;      const VeganItemTag._();      factory VeganItemTag.fromJson(Map<String, dynamic> json) =>        _$VeganItemTagFromJson(json);  }  

I've tried using @With.fromString('AdministrativeArea<House>') from the docs but can't apply it correctly to this class.

Some of the console errors are in the comments and I also see this error when I do:

<GroceryItemTagEnum, VeganItemTag<GroceryItemTagEnum>>{      GroceryItemTagEnum.babyAndChild: VeganItemTag<GroceryItemTagEnum>(          name: 'Baby & Child',          id: GroceryItemTagEnum.babyAndChild,          iconCodePoint: 0xf77c),  

The element type _$_VeganItemTag<\dynamic> can't be assigned to the map value type VeganItemTag<\GroceryItemTagEnum>


Read in browser »
share on Twitter

Getting a ValueError in Python when trying to take strings from a file and converting them to int values

By yvirdi on Jun 06, 2021 02:53 am

Doing a twitter bot on VS. I've already tried using the int(float(input)) workaround but I get another ValueError saying that a string cannot be converted to a float. For context, the code is taking strings from a .txt file and trying to convert them to int values.

Here's the code below, any way to fix this?

def read_last_seen(FILE_NAME):  file_read = open(FILE_NAME,'r')  last_seen_id = int(file_read.read().strip())  file_read.close()  return last_seen_id  

Read in browser »
share on Twitter

Can't stratify output in a customized way

By MITHU on Jun 06, 2021 02:45 am

I've created a script to parse few data points from an htmlfile link and write the same to a csv file according to this format.

I do locate the fields accordingly using the selectors I've already defined within the script, but I can't stratify the output in the right way so that I can write them later to a csv file.

location of data points:

Nature of association    `from 1st table`  Purpose  In cash (Previous balance)    `from 2nd table`  Donor Name  Address    `from 3rd table`  Country Name  Amount  

Here is what I've tried (I suppose the htmlfile link works):

import requests  from bs4 import BeautifulSoup    file_link = 'https://filebin.redpill-linpro.com/zj2qqc27va5fatm0/index.html'    res = requests.get(file_link)  soup = BeautifulSoup(res.text,"lxml")  nature_of_asso = soup.select_one("td:contains('Nature of association') + td").get_text(strip=True)    for purpose_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Purpose')) tr")[3:]:      try:          purpose = purpose_tr.select_one('td:nth-of-type(2)').get_text(strip=True)      except AttributeError: purpose = ""      try:          in_cash = purpose_tr.select_one('td:nth-of-type(3)').get_text(strip=True)      except AttributeError: in_cash = ""      print(purpose,in_cash)    for donor_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Donor Name')) tr")[2:]:      try:          donor_name = donor_tr.select_one('td:nth-of-type(2)').get_text(strip=True)      except AttributeError: donor_name = ""      try:          address = donor_tr.select_one('td:nth-of-type(3)').get_text(strip=True)      except AttributeError: address = ""      print(donor_name,address)    for country_tr in soup.select("table:has(> tr > td:nth-of-type(1) + td:contains('Country Name')) tr")[1:]:      try:          country = country_tr.select_one('td:nth-of-type(2)').get_text(strip=True)      except AttributeError: country = ""      try:          amount = country_tr.select_one('td:nth-of-type(3)').get_text(strip=True)      except AttributeError: amount = ""      print(country,amount)  

How can I arrange output as per the image above in order to write the same to a csv file?


Read in browser »
share on Twitter

How to set integer range in Scanner? [closed]

By Neetesh Khanal on Jun 06, 2021 01:23 am

I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.

Below is the code, I have tried: -

enter image description here


Read in browser »
share on Twitter

trying to create a dynamic swiper

By nuctis on Jun 05, 2021 03:11 pm

I'm trying to create a dynamic swiper that is able to automatically update itself whenever I make changes in the database. The problem that I've encountered right now is that I've got 6 sliders the sliders but all of the 6 sliders only retrieve from the first column from my database. The sliders Any help would be appreciated, thank you.

<?php    $connect = mysqli_connect("localhost", "root", "", "db");  function make_query($connect)  {   $query = "SELECT * FROM db.slider ORDER BY p_id ASC";   $result = mysqli_query($connect, $query);   return $result;  }    function make_slide_indicators($connect)  {   $output = '';   $count = 0;   $result = make_query($connect);     while($row = mysqli_fetch_assoc($result))   {    if($count == 0)    {     $output .= '     <li data-target="#" data-slide-to="'.$count.'" class="active"></li>     ';    }    else    {     $output .= '     <li data-target="#" data-slide-to="'.$count.'"></li>     ';    }      echo $output;      $count = $count++;   }   return $output;  }    function make_slides($connect)  {   $output = '';   $count = 0;   $result = make_query($connect);   while($row = mysqli_fetch_assoc($result))   {    if($count == 0)    {     $output .= '<div class="swiper-slide platform">';    }    else    {     $output .= '<div class="swiper-slide platform">';    }      {$output .='      <img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />     <div class="swiper-slide platform">      <h3>'.$row["p_desc"].'</h3>      </div>      </div>    ';      }        $count = $count + 1;   }   return $output;    }      ?>  

Read in browser »
share on Twitter

Send big file (2GB+) to anonfiles using requests

By Adirio on Jun 05, 2021 01:23 pm

I had a script to send a file to anonfiles.com for sharing using requests. It emulates the suggested curl command:

curl -F "file=@test.txt" https://api.anonfiles.com/upload  
with open(filename, 'rb') as file:      req = requests.post(          'https://api.anonfiles.com/upload',          files={'file': file},      )      res = json.loads(req.text)  

This worked properly for files smaller than 2GB, but when the file grew bigger, it started printing a error message about the filesize.

I tried to using requests-toolbelt to send the file with no success.

with open(filename, 'rb') as file:      encoder = MultipartEncoder({'file': file})      req = requests.post(          'https://api.anonfiles.com/upload',          data=encoder,          headers={'Content-Type': encoder.content_type}      )      res = json.loads(req.text)  

Which returns a the followinf error from anonfiles.com:

{      "status": false,      "error": {          "message": "No file chosen.",          "type": "ERROR_FILE_NOT_PROVIDED",          "code": 10      }  }  

I'm probably missing something obvious, but can't figure it out right now.

P.S.: the use of requests-toolbelt.MultipartEncoder is not mandatory, I tried it and didn't manage to make it work. I will accept any answer even if it doesn't include this. A solution without request is not optimal but would also work.


Read in browser »
share on Twitter

Reverse column transform

By aksa john on Jun 05, 2021 10:17 am

In a machine learning model y_train is a string so column transform was applied in y_train before training the model ,How to remove the transform while printing the end result


Read in browser »
share on Twitter

In ImageDataGenerator data is augmented in each batch or each epoch?

By Raj_Ame09 on Jun 05, 2021 07:15 am

I know that in each epoch we have a new set of augmentation. But my question is that if we have a total of 10 sample image, batch_size = 5, and we took steps_per_epoch = 3 instead of 2, then we will pass 5*3 = 15 images in each epoch,

so definitely we will have repetition, my question is that if image x is repeated, will both have the same augmentation value or different.
It depends on whether new augmentation happens in each batch or in each epoch.

Thanks,


Read in browser »
share on Twitter




Recent Articles:

org.openqa.selenium.WebDriverException: unknown error: net::ERR_CONNECTION_REFUSED
Are scannerless parser grammars still supported in ANTLR4?
Given a string how can I remove all the duplicated consecutive letters?
Spark SQL can use FIRST_VALUE and LAST_VALUE in a GROUP BY aggregation (but it's not standard)
Big-O complexity for n + n-1 + n-2 + n-3 + (...) + 1
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

Our mailing address is:
reader
88 CELICA STREET
Davao 8000
Philippines

Add us to your address book


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp

No comments:

Post a Comment