Monday, April 5, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Python ctypes access violation due to invalid pointer

Posted: 05 Apr 2021 09:12 AM PDT

I have a dll and its header file that define quite a number of functions to access data in a special format. Following other solutions, I am able to get a basic start with ctypes that seems to work but as soon as I attempt to use a returned file pointer I receive the access violation so I suspect I am using the pointers incorrectly.

I'm following example code in C which lays out creating a new context, then opening the file, so I believe that part is ok. I just can't seem to do anything with the returned file reference. I do get file returned as an int after calling sie_file_open whereas the documentation says that the errors from the library return null. I've got a bunch of different functions to use with the file pointer, but even the most basic sie_release fails.

Taking the advice from here to use classes to manage the pointers (there will be many more needed to access the data later), I have:

from ctypes import *    libsie = cdll.LoadLibrary('libsie.dll')    #Set the SIE context  class pt_sie_context(c_void_p):      pass    libsie.sie_context_new.argtypes = None  libsie.sie_context_new.restype = pt_sie_context    context = libsie.sie_context_new()    #Open the SIE file  class pt_sie_file(c_void_p):      pass    libsie.sie_file_open.argtypes = [pt_sie_context,c_char_p]  libsie.sie_file_open.restypes = pt_sie_file    fpath = 'H2.sie'  file = libsie.sie_file_open(context,fpath.encode('utf-8'))    libsie.sie_release.argtypes = [pt_sie_file]  libsie.sie_release.restypes = None    libsie.sie_release(file) #access violation here  

And from the header file:

typedef void sie_Context;  typedef void sie_File;    SIE_DECLARE(sie_Context *) sie_context_new(void);  SIE_DECLARE(sie_File *) sie_file_open(void *context_object, const char *name);  SIE_DECLARE(void) sie_release(void *object);  

I'm relatively new to this whole process as well as C in general so any thoughts would be much appreciated.

How to revoke permission to edit Admin User in django admin

Posted: 05 Apr 2021 09:11 AM PDT

class MyAccountManager(BaseUserManager):      def create_user(self, email, username, password=None):          if not email:              raise ValueError("Users must have an email address")          if not username:              raise ValueError("Users must have an username")          user = self.model(              email=self.normalize_email(email),              username=username,          )            user.set_password(password)          user.save(using=self._db)          return user        def create_superuser(self, email, username, password):          user = self.create_user(              email=self.normalize_email(email),              username=username,              password=password,          )            user.is_admin = True          user.is_staff = True          user.is_superuser = True          user.save(using=self._db)          return user      class User(AbstractBaseUser,PermissionsMixin):      email = models.EmailField(verbose_name='email', max_length=80, unique=True)      username = models.CharField(max_length=30, unique=True)      first_name = models.CharField(max_length=100,null=True)      last_name = models.CharField(max_length=100,null=True)      phone_no = models.CharField(max_length=12, null=True)      date_joined = models.DateField(          verbose_name='date joined', auto_now_add=True)      last_login = models.DateField(verbose_name='last login', auto_now=True)      is_admin = models.BooleanField(default=False)      is_active = models.BooleanField(default=True)      is_staff = models.BooleanField(default=False)      is_superuser = models.BooleanField(default=False)      is_teacher = models.BooleanField(default=False)      address = models.CharField(max_length=500, null=True, blank=True)        USERNAME_FIELD = 'username'      REQUIRED_FIELDS = ['email']        objects = MyAccountManager()        def __str__(self):          return self.email        # def has_perm(self, perm, obj=None):      #     return self.is_admin        def has_module_perms(self, app_label):          return True    

I have a custom user model and I'm able to create groups without giving necessary permissions. I created a group by giving permission to view and change users. I added a staff user to that group without escalating them as an admin user or a superuser. But that user can edit admin user. How I can prevent users in that specific group editing the admin user

Select first/15th day of month plus the day before and after in python

Posted: 05 Apr 2021 09:11 AM PDT

I would like to select specific days in a table to calculate the mean for each specific group. My table has around 9000 lines like these: Example Data

I would like to select only one value for every -first value of a month, -last value of a month, -second value of a month, -every 15th, -the day before the 15th, -the day after 15th

The purpose is to calculate the mean for every specific group.

The result should look like this: Result

I am struggeling with the calculation for the 15th before and after as well as after the first.

What I tried so far is: import pandas as pd df = pd.read_excel df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True)

"Average first of month"  dffirst = df[~df.index.to_period('m').duplicated()]  monthly_first = dffirst['Value'].mean()    "Average last of month"  dflast = df.resample("M").max()  monthly_last = dflast['Value'].mean()  

Thank you

Ava+Sinon unite testing. ReferenceError: window is not defined

Posted: 05 Apr 2021 09:11 AM PDT

I tried to write a test file to test one of the moduel. The module has a line of code that access window.location.origin which is causing an error when running the unit test : ReferenceError: window is not defined.

The moduel under test and test case code:

myfile.js:

const isExternal =  window.location.origin.includes('.com');    const getAccess = () => {      if(isExternal){          //Do somthing      }  }  

myfile.test.js:

const test = require('ava');  const sinon = require('sinon');  const myfile = require('../../src/myfile');    test.serial('test myfile', t => {      myfile.isExternal = true;      //Assert below  })  

My problem is when I have the line const myfile = require('../../src/myfile'); in the code and run npm run test, it will show an error:

ReferenceError: window is not defined  tests\myfile.test.js exited with a non-zero exit code: 1  

Database relationship help (user with varying types and groups)

Posted: 05 Apr 2021 09:11 AM PDT

An example would if we had a website about beer.

  • We'd have Users who may or may not be Brewers.
  • Users who are Brewers could additionally be part of a Brewery.

Current setup:

// made up shorthand TS like syntax to demonstrate  User {      role: User | Moderator | Admin; // global site permissions      type: User | Brewer; // did user register as a brewer?      brewery: Brewery; // reference the Brewery if user is part of one      breweryRole: Owner | Member; // reference the Brewery Role is user is part of one  }    Brewery {      owner: User; // reference user who created the Brewery so they always have permissions      members: [User]; // list of users who belong to this Brewery  }  

Essentially we have varying user types along with external groups that the user may belong to.

apache-arrow does not compile with typescript

Posted: 05 Apr 2021 09:11 AM PDT

I've been able to get this to bundle with webpack, but I've been considering using rollup instead for other issues I'm having with my library. However, that requires me to do a tsc first.

Is this an issue with my configuration or an issue with apache-arrow?

In my package.json:

"apache-arrow": "^3.0.0",  "typescript": "^4.1.3",  

In one of my .ts files:

import { Table } from 'apache-arrow';  

My output when running tsc:

node_modules/apache-arrow/Arrow.d.ts(47,466): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(47,641): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(48,471): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(48,646): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(62,352): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(62,527): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(63,353): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(63,528): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(64,353): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(64,528): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(65,353): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(65,528): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(66,354): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(66,529): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(67,354): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(67,529): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(68,355): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(68,530): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(69,355): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(69,530): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(70,360): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(70,535): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(71,357): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(71,532): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(72,358): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(72,533): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(73,358): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(73,533): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(74,358): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(74,533): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(75,359): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(75,534): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(76,359): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(76,534): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(77,360): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(77,535): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(78,360): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(78,535): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/Arrow.d.ts(79,365): error TS2304: Cannot find name 'ReadableStreamReadValueResult'.  node_modules/apache-arrow/Arrow.d.ts(79,540): error TS2304: Cannot find name 'ReadableStreamReadDoneResult'.  node_modules/apache-arrow/interfaces.d.ts(178,5): error TS2502: '[Type.FixedSizeList]' is referenced directly or indirectly in its own type annotation.  node_modules/apache-arrow/io/interfaces.d.ts(46,54): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(51,63): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(53,13): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(53,32): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(57,22): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(57,51): error TS2304: Cannot find name 'PipeOptions'.  node_modules/apache-arrow/io/interfaces.d.ts(58,27): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(59,19): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(61,18): error TS2304: Cannot find name 'PipeOptions'.  node_modules/apache-arrow/io/interfaces.d.ts(61,32): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(62,28): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/interfaces.d.ts(88,54): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/stream.d.ts(5,53): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/io/stream.d.ts(7,91): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/stream.d.ts(30,62): error TS2304: Cannot find name 'Response'.  node_modules/apache-arrow/io/stream.d.ts(30,73): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/whatwg/builder.d.ts(24,15): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/io/whatwg/builder.d.ts(25,15): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/io/whatwg/builder.d.ts(26,18): error TS2304: Cannot find name 'ReadableStreamDefaultController'.  node_modules/apache-arrow/ipc/reader.d.ts(19,47): error TS2304: Cannot find name 'Response'.  node_modules/apache-arrow/ipc/reader.d.ts(19,82): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/ipc/reader.d.ts(62,20): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/ipc/reader.d.ts(71,27): error TS2304: Cannot find name 'ByteLengthQueuingStrategy'.  node_modules/apache-arrow/ipc/reader.d.ts(74,19): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/ipc/reader.d.ts(75,19): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/ipc/reader.d.ts(236,5): error TS2717: Subsequent property declarations must have the same type.  Property 'schema' must be of type 'Schema<T>', but here has type 'Schema<any>'.  node_modules/apache-arrow/ipc/writer.d.ts(36,27): error TS2304: Cannot find name 'QueuingStrategy'.  node_modules/apache-arrow/ipc/writer.d.ts(42,19): error TS2304: Cannot find name 'WritableStream'.  node_modules/apache-arrow/ipc/writer.d.ts(43,19): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/ipc/writer.d.ts(65,54): error TS2304: Cannot find name 'ReadableStream'.  node_modules/apache-arrow/recordbatch.d.ts(17,18): error TS2430: Interface 'RecordBatch<T>' incorrectly extends interface 'StructVector<T>'.    The types of 'slice(...).clone' are incompatible between these types.      Type '(data: Data<Struct<T>>, children?: AbstractVector<any>[]) => RecordBatch<T>' is not assignable to type '<R extends DataType<Type, any> = Struct<T>>(data: Data<R>, children?: AbstractVector<R>[]) => VectorType<R>'.        Types of parameters 'data' and 'data' are incompatible.          Type 'Data<R>' is not assignable to type 'Data<Struct<T>>'.            Type 'R' is not assignable to type 'Struct<T>'.              Property 'dataTypes' is missing in type 'DataType<Type, any>' but required in type 'Struct<T>'.  node_modules/apache-arrow/recordbatch.d.ts(24,22): error TS2415: Class 'RecordBatch<T>' incorrectly extends base class 'StructVector<T>'.  node_modules/apache-arrow/util/buffer.d.ts(10,328): error TS2304: Cannot find name 'ReadableStreamReadResult'.    

Use tableaux (or equivalent) to create a view for a table with a column for fieldname and another column for value

Posted: 05 Apr 2021 09:11 AM PDT

I have a table which is meant to accommodate new fields in the future. So the columns are:

ID Type Value

so for example I could have:

ID Type Value
John Height 60
John Weight 180
Bill Height 59
Bill Weight 160

and in the future I can add something like:

ID Type Value
John Eyecolor Brown
Bill Eyecolor Green

Of course not every ID needs to have the same set of listings for Type.

What I want to do in a visualization package like Tableaux is display the table with a flat look like:

Height Weight Eyecolor
John 60 180 Brown
Bill 59 160 Green

where I can filter by ID as well as Type.

But I can't only figure out how to get this. Is it doable?

I also envision getting subtotals of the flat columns and creating calculated columns based on the flat look.

I need an algorithm for my 2^2^n boolean functions. which can find the mobius and walash transformation for all the boolean functions

Posted: 05 Apr 2021 09:11 AM PDT

For n variables, there exists 2^(2^n) distinct boolean functions. here is the truth table a possibly one boolean function I want to calculate Mobius form, Walsh Hadamard form, and affine linear functions of all the boolean functions up to 2^2^n.

ruth table |Boolean Function 1

(0, 0, 0, 0) | 0 (0, 0, 0, 1) | 0 (0, 0, 1, 0) | 0 (0, 0, 1, 1) | 0 (0, 1, 0, 0) | 0 (0, 1, 0, 1) | 0 (0, 1, 1, 0) | 0 (0, 1, 1, 1) | 0 (1, 0, 0, 0) | 0 (1, 0, 0, 1) | 0 (1, 0, 1, 0) | 0 (1, 0, 1, 1) | 0 (1, 1, 0, 0) | 0 (1, 1, 0, 1) | 0 (1, 1, 1, 0) | 0 (1, 1, 1, 1) | 0

I am looking for an algorithm that can transform the boolean function by using Mobius transformation and then can find the affine functions using Walsh transformation.

EasyAdminBundle, configureUserMenu interface dont let me return

Posted: 05 Apr 2021 09:11 AM PDT

ERROR-> "The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned an object of type EasyCorp\Bundle\EasyAdminBundle\Config\UserMenu."

namespace App\Controller\User;    use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;  use EasyCorp\Bundle\EasyAdminBundle\Config\UserMenu;  use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;  use Symfony\Component\Routing\Annotation\Route;  use Symfony\Component\Security\Core\User\UserInterface;  use Symfony\Component\HttpFoundation\Response;  class DashboardUserController extends AbstractDashboardController  {          /**       * @Route("/userPanel", name="userPanel")       */    public function configureUserMenu(UserInterface $user): UserMenu  {  // Usually it's better to call the parent method because that gives you a  // user menu with some menu items already created ("sign out", "exit impersonation", etc.)  // if you prefer to create the user menu from scratch, use: return UserMenu::new()->...  return parent::configureUserMenu($user)  // use the given $user object to get the user name  ->setName($user->getUsername())  // use this method if you don't want to display the name of the user  ->displayUserName(false)      // you can use any type of menu item, except submenus  ->addMenuItems([  MenuItem::linkToRoute('My Profile', 'fa fa-id-card', '...', ['...' => '...']),  MenuItem::linkToRoute('Settings', 'fa fa-user-cog', '...', ['...' => '...']),  MenuItem::section(),  MenuItem::linkToLogout('Logout', 'fa fa-sign-out'),  ]);  }  }  ?>  

How can I create a virtual python environment in distributed airflow in runtime for a tfx-pipeline?

Posted: 05 Apr 2021 09:10 AM PDT

I have DAGS which I want to run in different python environments in the same distributed airflow cluster. Is it possible to create a virtual python environment while executing the DAG?

I am looking to add tfx ML pipelines to our distributed airflow platform and It is not possible to install tfx individually in the each of the worker nodes.

How to plot a figure using the data from dictionary of dictionary in Julia?

Posted: 05 Apr 2021 09:10 AM PDT

I would like to plot a chart using the details from a nested dictionary. For Example, I have a Dictionary like this:

d = Dict(:a => Dict(:val1 => rand(10), :val2 => rand(50)),      :b => Dict(:val1 => rand(40), :val2 => rand(60)))  

I would like to create a violin plot such that for each key like :a & :b the :val1 represents violin plot and :val2 represents scatter plot. (The figure should be a single plot, created using modifier functions(plot!)).

Thanks in advance!!

Can I convert huge .csv file to .ftr using chunking?

Posted: 05 Apr 2021 09:10 AM PDT

I have a really huge .csv dataset.

  1. I want to convert it to feather format for faster reading / writing.
  2. But I can't fit the whole .csv file to my RAM memory at once.
  3. I was thinking about chunking the .csv file and then storing it into the .ftr format
  4. But if I understand this correctly you can't append to .ftr right?

How would you approach this problem? I was thinking about saving every chunk into separate .ftr file?

Can I create a hybrid docker with .NET Core API referencing to some .NET Framework DLL

Posted: 05 Apr 2021 09:10 AM PDT

I know that there are ways to build a docker file for either .net core or .net framework api. But, I am not quite sure about the possibility of building a docker file that can work for a .net core project with some .net framework dll references.

Parellel.For, Console.Writeline and Deadlock

Posted: 05 Apr 2021 09:10 AM PDT

I have the following class,

public static class Logger  {        public static NLog.Logger _logger;      static Logger()      {          _logger = LogManager.GetCurrentClassLogger();      }        public static void Log(string message)      {          Console.WriteLine(message);          _logger.Info(message);      }        public static void Log(Exception ex)      {          Console.WriteLine($"Exception: {ex.Message}, StackOverFlow: {ex.StackTrace}");          _logger.Error(ex);            if(ex.InnerException != null)          {              _logger.Error(ex.InnerException);          }      }  }  

and I am using,

Parallel.For(0, tranIds.Count, new ParallelOptions { MaxDegreeOfParallelism = -1 }, j =>     var tranId = tranIds[j];     // Do Some Work With No Shared Resources     Logger.Log($"Log SomeThings");  });  

When I run the code for long time and put breakpoint. All threads are breaking at Logger.Log. I am using NLog and Console.Writeline and stopping Parallel.For to finish. Is there any deadlock?

React why use State if I can use let declaration

Posted: 05 Apr 2021 09:10 AM PDT

I have been using react for a while now but I started question why should I use state if I can just set a variable using let and mutate that instead. I have a context provider here:

const ProfileProvider = ({roles, children}) => {    let adminRole = false;    if(roles.includes('admin')) {      adminRole = true;    }      return <ProfileContext.Provider    value={{      adminRole    }}>      {children}    </ProfileContext.Provider>;   }  

Whats the difference between setting adminRole using this way vs useState?

How to eliminate this SQL String_Split function error

Posted: 05 Apr 2021 09:11 AM PDT

Trying to use the SQL string_split function in a dynamic query but I continue to receive the following error. Invalid column name 'Invoice Description'. Argument data type void type is invalid for argument 1 of string_split function. I can not figure out the issue. Any help is greatly appreciated.

DECLARE @AuthFile nvarchar(max); DECLARE @TableName AS SYSNAME;  DECLARE @sql nvarchar(max);    SET @TableName = '__tTransactions_' + REPLACE(CONVERT(CHAR(10), GETDATE(), 103), '/', '');  SET @AuthFile = '__Authorization';    create table #temp (TransactionID nvarchar(1000), CartID int, TotalAmount nvarchar(1000))    SET @sql = 'select [Transaction ID] as TransactionID, cs.value as CartID, [Total Amount] as TotalAmount               into #temp               from ' + @TableName + '              cross apply string_split([Invoice Description], ''|'') cs              where (isnull([Invoice Description], '''') <> '''')';    print(@sql);  EXEC(@sql);  SET @sql = '';    select * from #temp    drop table #temp  

Comparisons in Python

Posted: 05 Apr 2021 09:11 AM PDT

I want to perform integer comparisons in Python. However, although this is a simple concept, i don't seem to get it work.

radius = 1  if radius < 25 and radius > 50:     print("case 1")  else:     print("case 2")  

However, although radius = 1, python always returns the second case.

EDIT: This is a question that is stupid, because i was certain i had typed or, so it's not really a python question. I upvoted answers though because they took the time to answer it, and plus they are new members here.

GoDaddy shared hosting two differnt sites running different php versions

Posted: 05 Apr 2021 09:10 AM PDT

I am running a GoDaddy shared hosting package. I need one site to run php 7.4.11 and the other to run php 5.6

The server default php version is 7.4.11

I have already tried creating a .user.ini file within the site folder and inputting the reference url path session.save_path = "/var/cpanel/php/sessions/ea-php56" with no luck. I have also tried to dump the php56.php file content inside of .user.ini but that also didnt seem to work.

I have killed the php process each test and im using phpinfo.php to check the results.

Anyone have any ideas?

I am trying to swap to sections when we switch to mobile view that have a same parent class but are nested in two different divs

Posted: 05 Apr 2021 09:11 AM PDT

How can I achieve this with Javascript or CSS. The simple example of the code syntax would be :

<div class="container">       <div class="row">              <section class="one">                  <p>First Line</p>              </section>              <section class="two">                  <p> Second line</p>              </section>        </div>        <div class="row">              <section class="three">                  <p>Third Line</p>               </section>              <section class="four">                  <p> Fourth line</p>               </section>        </div>  </div>  

And I would like to swap the second and third line according to this code whenever I change to mobile view. Before that the first and second lines are in one row and third and fourth lines are in one row. Now when we switch to mobile view everything is stacked from top to bottom but I need to change the position of second(Blue) and third(Green) lines in mobile view.

enter image description here

how to run a one-off task on cloudfoundry to upload data before starting Python app

Posted: 05 Apr 2021 09:10 AM PDT

Hi this is my first experience trying to deploy a Python app on cloud using CF. I am having issues deploying my app; I sincerely appreciate if anyone can help me or point me to the right direction to solve the issue.

The main problem is the app that I am trying to deploy is large size due to a lot of python dependencies. The size of my app directory is 200 Kb. The first error I observed was: Staging fails due to "Failed to upload payload for droplet" . I think the reason is when all Python dependencies are downloaded from requirements.txt file and finally the droplet is created its size is too large for upload. The droplet size=982. 3 Mb.

The first solution I tried was vendoring app where I created a vendor directory containing all python dependencies but the size of vendor directory was greater that 1Gb, which causes the upload size exceed 1Gb limit and leads to failure in uploading app files.

The second solution I am working on is to upload all installed Python libraries on an object store (in my case S3 bucket which is bounded to my app) and then download the dependencies folder called Pypackages to the app's root directory: /home/vcap/app, so I want to have /home/vcap/app/Pypackages exist before my app starts on the cloud. But I couldn't do it successfully yet. I have included a python script in my app directory which downloads files from S3 bucket successfully. (I have put the correct absolute path for download in downloadS3.py script ie, /home/vcap/app/Pypackages) I want to run this script using "python downloadS3.py" as a one-off task. First I tried the solution here : Can I have multiple commands run in a manifest.yml file? and although I can see the status of the task is SUCCEED via '$cf tasks my-app-name' , /home/vcap/app/Pypackages does not exist.

I also tried to run one-off task as the steps below:

1- $ cf push -c 'python downloadS3.py && sleep infinity' -i 1 --no-route

2- $ cf push -c 'null' I have printed the contents of /home/vcap/app on my app, ie when app is started and I enter the url in my browser (I don't know what is the right way to see the contents of root directory). Anyway, the problem is Pypackages are not downloaded to the correct root directory. I am not sure if I am running the one-off task in a wrong way or if there is a better solution to make my app work. I appreciate any helps! (edited)

Java invoke REST service for x time period for response with periodic interval

Posted: 05 Apr 2021 09:11 AM PDT

I have to call a REST endpoint (using Java) to retrieve a response. The configurations are

totalTimeAvailableToCheck = 15 seconds, NoOfAttempts = 3 , intervalInAttempts = 3 seconds.

So consider this an endpoint will be called after every 3 seconds. if I get the desired response then complete the execution else keep on trying after every 3 seconds for next 3 attempts. Total wait time for all this on main thread should not be more than 15 seconds. As rest endpoint could have its own slowness.

Response is just a string(status indicator). So if status is IN PROGRESS keep checking after a interval else if status is DONE/CANCELLED. Returns the status as response.

Edit : Is using a ScheduleEexcutorService for this a better approach ? or any framework that provide this out of box ?

Edit : My first attempts was with while(true) but it would have flaw

while(attemptCount > noOfAttempts) {      sleep(3seconds);      String result = restService.get();      if(result == in progress) noOfAttempts ++      else return mapResponse(result);  }  throw timeOutException("timeout")    
  • The flaw with this logic is if rest service call takes long time.

Is there a way to print the last row in a column on a new sheet?

Posted: 05 Apr 2021 09:11 AM PDT

im trying to find the last row in a column with in each sheet, so if the last column in sheet1 is BD30 then i want that value to be printed on the sheet i created to get the values and input them there.

    Dim wb As Workbook      Dim sht As Worksheet      Dim LastColumn As Integer             Set wb = ActiveWorkbook      Sheets.Add.Name = "Data"      Dim shtMain As Worksheet      Set shtMain = wb.Sheets("Data")            Dim LastRow As Integer      LastRow = shtMain.Range("A1").CurrentRegion.Rows.Count            Dim c As Range        For Each sht In wb.Worksheets          If sht.Name <> shtMain.Name Then              LastColumn = sht.UsedRange.Columns(sht.UsedRange.Columns.Count).Column              With shtMain.Range("A1", "A" & LastRow)                  Set c = .Find(sht.Name, LookIn:=xlValues)                  If Not c Is Nothing Then                      c.Offset(0, 1).Value = LastColumn                  Else                      With shtMain.Range("A" & LastRow)                          .Offset(1, 0).Value = sht.Name                          .Offset(1, 1).Value = LastColumn                          LastRow = LastRow + 1                      End With                  End If              End With          End If      Next sht  End Sub  

this is the code i have it works, but the problem is that it counts how many rows there are so for example in sheet1 there are 55 rows it will show 55 and thats not what i want, i want to show me the value of the last row in column that contains data.

this is what i get when i run my code. it counts the rows but i want it to paste the last row value not count the rows. so for example if the last row is BB40 then i want that to show.

SWIFT - How to detect Firestore connection errors / offline connection

Posted: 05 Apr 2021 09:11 AM PDT

When the users sets the internet connection to offline I'm getting the following error message to the Xcode console:

7.8.0 - [Firebase/Firestore][I-FST000001] WriteStream (11ed16098) Stream error: 'Unavailable: DNS resolution failed'

But how can I detect the status of the connection programmatically? I don't find any document at the Firestore documentation regarding that topic?

Why do some signals not allow signal filtering using Fourier transformation?

Posted: 05 Apr 2021 09:10 AM PDT

I have tried Fourier transformation on two types of data:

Sample 1:

 [5.22689618e-03 2.41534315e+00 0.00000000e+00 2.44972858e-01   4.25280086e-02 9.33815370e-01 3.03247287e-01 2.30718622e-01   3.67055310e-03 1.08563452e-01 1.65198349e+00 0.00000000e+00   0.00000000e+00 3.81988895e-01 5.76292398e-02 4.30815942e-01   1.26064346e+00 1.22264457e-01 9.20206465e-01 5.10205014e-02   1.69624045e-02 1.27946761e-04 9.85479035e-02 1.47322503e-03   5.88801835e-01 9.14815956e-04 1.58679916e-02 1.80580638e-04   1.33877873e-02 4.31785412e-01 4.29998728e+00 7.28365507e-02   2.93196111e-01 6.46923082e-01 1.64020382e+00 2.66995573e-01   1.73472541e+00 1.20450527e+00 2.93713233e-01 4.37012291e-02]  

Sample 2:

 [1.63397428e-05 5.06326672e-05 5.07890481e-05 3.27493146e-05   6.19592537e-04 2.14127001e-04 3.31584036e-04 3.67715480e-05   8.80083850e-05 2.70784860e-05 1.82332876e-05 1.13016894e-04   9.62697824e-06 6.82677776e-06 1.55218678e-05 1.17480350e-04   6.16809229e-05 7.51721123e-05 1.71455229e-04 3.89279781e-05   4.14875499e-04 2.91402507e-05 2.07895269e-04 3.54011492e-04   1.81316474e-06 2.28406092e-06 1.75001077e-04 3.21301398e-04   2.77558089e-05 4.87684894e-04 1.91564056e-05 5.09892912e-06   1.91527601e-04 4.01062880e-05 8.71198341e-06 2.87598374e-04   1.81759066e-04 4.45384356e-05 1.90984648e-05 5.30995670e-04   9.18908105e-05 6.19051866e-04 7.01213246e-06 1.97357403e-05   1.52822474e-06 4.44353810e-05 2.12599086e-04 1.10231829e-04   3.34317235e-05 1.10217651e-04 2.27115357e-05 2.43621107e-04   9.59827677e-05 1.99824695e-04 1.76506191e-04 2.83759047e-04   3.95528472e-05 1.04707169e-04 1.92821332e-05 1.69779942e-04   2.82886397e-04 1.42531512e-04 1.25545297e-05 6.64785458e-05   2.49983906e-04 7.36739683e-05 1.75280514e-04 6.63189677e-05   7.10295246e-06 1.45455223e-04 1.71038217e-04 1.80725103e-05   6.81610965e-05 5.38084605e-04 7.54303898e-05 1.74061569e-05   1.26723836e-04 8.94035463e-05 9.10723041e-05 1.54759188e-05   4.62195919e-05 4.98443430e-04 1.13484031e-04 6.36021767e-05   4.85053842e-05 6.72420582e-05 3.24306672e-04 1.92741144e-05   7.68752096e-04 3.27063864e-04 2.19143305e-05 7.59406815e-05   3.59140998e-05 5.66567689e-04 2.57783290e-04 1.20276603e-04   1.99017206e-05 3.27490253e-04 9.39513533e-05 1.01252991e-04]  

I tried implementing Fourier filter transformation to extract signals from the original set but both signal does not show same findings. The sample 1 doesn't extract any function while sample 2 allows it, as shown in the figure

A partial code for the analysis is presented below.

# Positive sample  import numpy as np  import pandas as pd  import matplotlib.pyplot as plt    f = signal  t = np.arange(len(signal))  dt = 1    ## Compute the Fast Fourier Transform (FFT)  n = len(t)  fhat = np.fft.fft(f,n)                     # Compute the FFT  PSD = fhat * np.conj(fhat) / n             # Power spectrum (power per freq)  freq = (1/(dt*n)) * np.arange(n)           # Create x-axis of frequencies in Hz  L = np.arange(1,np.floor(n/2),dtype='int') # Only plot the first half of freqs  #print('PSD value is', PSD, '\n\nfhat is', fhat, '\n\nfrequency is', freq)  plt.plot(freq, PSD)    # Extracting datasets ## Use the PSD to filter out noise  indices = PSD > 0.2       # Find all freqs with large power  low_indices = PSD < 0.2  # Find all freqs with small power  PSDnoise = PSD[low_indices]  # store smaller freqs   PSDclean = PSD * indices  # Zero out all others  fhat_noise = low_indices * fhat  fhat = indices * fhat     # Zero out small Fourier coeffs. in Y  ffilt = np.fft.ifft(fhat) # Inverse FFT for filtered time signal  noise = np.fft.ifft(fhat_noise)  

I repeat this process on the noise data for multiple times and the graph I obtained from three steps is:

enter image description here

May I Know why these two functions behave differently? Thanks in advance!!

create a pipe array in c

Posted: 05 Apr 2021 09:11 AM PDT

I'm new to C and I was trying to make an array of pipe but it's giving me an error.
This is what I was trying to do :

int fd[N][2];  pipe(fd);  

Can someone tell me what I'm doing wrong ?

How to get the SUSER_NAME() of the user for auditing fields in Azure SQL

Posted: 05 Apr 2021 09:10 AM PDT

We are migrating from on-prem database into Azure SQL. We have audit fields in the database that grabs the SUSER_NAME() whenever a DML transaction (i.e., INSERT, UPDATE, DELETE - soft-delete) occurs. Since the on-prem database uses the Windows Domain Active Directory and the users login to the database using Integrated Security we can correctly get the current user's name.

However, when we use the managed identity in Azure SQL, the SUSER_NAME() comes down as a concatenation of two guids: the Managed Identity guid and the service container guid. As a result, we are losing the user name of the current user. Is it possible to get the user name with the SQL Function SUSER_NAME() (or some other SQL function) or will this be a code change where we now pass in the actual user name, for the audit field in question, to the call to the Azure SQL database?

Update 1:

Our application is designed to interact with Azure SQL using the following DbContext constructor:

public SomeDbEntities(IConfiguration objConfiguration, AzureAuthenticationInterceptor azureAuthenticationInterceptor) :      base(new DbContextOptionsBuilder<SomeDbEntities>()          .UseSqlServer(objConfiguration.GetValue<string>("Azure:ConnectionStrings:SomeDbEntities"))          .AddInterceptors(azureAuthenticationInterceptor)          .Options)  { }  

We are using an azureAuthenticationInterceptor in order to deal with a thread blocking issue. The solution for that was provided here: EF Core Connection to Azure SQL with Managed Identity

Update 2:

The audit fields are being set by triggers using the SUSER_NAME() function that log data to a history table.

Chrome crash when i try to download a file from a url in chrome extension

Posted: 05 Apr 2021 09:11 AM PDT

so i'm trying to use chrome extension to download a file from url. to do that i pass with the runtime.sendmessage() a url and then the listener in my background.js try to make some magic. Message arrives correctly and i can reply with sendResponse() without errors. When i try to add my function that use chrome.downloads.download() inside the listener function to make the user download the file, the chrome app crash. I don't know how to check if i have some error cause it close everything..

background.js

    chrome.runtime.onMessage.addListener(      function (request, sender, sendResponse) {          let url = request.url; //request correctly arrive            let filename = url.split("/");          filename = filename[filename.length - 1]; //just a split to get the name of the file from the url where i have to point          try{              download(url, filename);//If i don't call the chrome.download nothing crashes,                                       //viceversa if i only call the chrome.download and not the onMessage, it doesn't crashes                                      //it crashes only when i combine the listener and the download method          }          catch(exception){              sendResponse({status: "KO", message: "Download not completed: " + exception, url:url, filename:filename});           }            sendResponse({status: "OK", message: "Download completed", url:url, filename:filename});           return true;      })      function download(url, filename) {      chrome.downloads.download({          url: url,          filename: "videos/" + filename //Create a video folder inside default download folder      })  }  

manifest.js

{      "name": "Camnet",      "description": "Build an Extension!",      "version": "1.0",      "manifest_version": 3,      "background": {          "service_worker": "background.js"      },      "permissions": [          "storage","downloads"      ],      "action": {          "default_popup": "popup.html"      },      "content_scripts": [          {            "matches": ["<all_urls>"],            "js": ["contentScript.js"]          }        ]  }  

contentScript.js

document.getElementById('generaVideo').addEventListener("click", () => {      chrome.runtime.sendMessage({ url: "http://mirrors.prometeus.net/centos/8.3.2011/isos/x86_64/CentOS-8.3.2011-x86_64-boot.iso" }, function (response) {          console.log(response.message);          alert(response.url);          alert(response.filename);      });  }, false)  

the download is just a centos distro.

Is it possible to receive audio via Bluetooth on a esp32 arduino and then directly send it further to a bt speaker?

Posted: 05 Apr 2021 09:10 AM PDT

You would connect your phone to the esp32 arduino and send an audio stream from the phone. The arduino then would do some calculations with the music and send the music to a Bluetooth speaker, that you are able to hear the music.

So is it possible to connect to two devices while simultaneously receiving and sending data?

Thanks for the help.

Can I use lightbox2 in a <img> tag?

Posted: 05 Apr 2021 09:11 AM PDT

I'm new so I hope you can bare with me and help a newbie out.

I'm trying to apply the lightbox2 in a carousel. I want to be able to click on an image in my carousel and have that popping up in large in a lightbox. I followed all the steps (https://lokeshdhakar.com/projects/lightbox2/) but to apply the lightbox, it gives the example of using it in a a tag, but my images are inside a img tag.

I don't understand how I'm going to make it work, I've tried for hours now and I'm starting to give up. I think I'm confusing myself more than necessary.. Heres my carousel code:

<section class="page-section" id="portfolio">  <div class="container-fluid px-0">  <div class="row no-gutters">      <div class="col-md-8">              <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">                  <div class="carousel-inner">                      <div class="carousel-item active">                          <img class="d-block w-100" src="assets/img/portfolio/display-bw.jpg" alt="First slide"></div>                      <div class="carousel-item">                          <img class="d-block w-100" src="assets/img/portfolio/display-bw.jpg" alt="Second slide"></div>                      <div class="carousel-item">                          <img class="d-block w-100" src="assets/img/portfolio/display-bw.jpg" alt="Third slide"></div>                  </div>                  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">                      <span class="carousel-control-prev-icon" aria-hidden="true"></span>                      <span class="sr-only">Previous</span>                  </a>                  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">                      <span class="carousel-control-next-icon" aria-hidden="true"></span>                      <span class="sr-only">Next</span>                  </a>              </div>      </div>  

Thanks for your help,

Cris

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given in /opt/lampp/htdocs/internshala/controller/signup.php on line 38 [duplicate]

Posted: 05 Apr 2021 09:12 AM PDT

How can I fix this error?

$qry="select id,pwd,username  from users where username='jimmy'";  $res=mysqli_query($conn,$qry);  $row=mysqli_fetch_array($res);  $count = mysqli_num_rows($row); // if uname/pass correct it returns must be 1 row  

No comments:

Post a Comment