text:
Q: AWS Lambda, Python3 and Large XLSX files to CSV files I have a batch of XLSX files that range from 10Mb to 400Mb in size. They always have the same sheets and structure inside, but some contain more data than others.
I am trying to process these using AWS Lambda; its part of a submission process so the file drop in S3 is the event to the Lambda.
I'm quickly learning that XLSX is a horrid format for this but I cannot alter this. Currently I have my main Lambda working using this class I found online and slightly altered. The memory usage and speed has improved over Pandas read_excel but its still not enough. With the 400Mb files the Lambda simply times out or eats up its memory allocation (even at max).
Doing some memory profiling on the script I can see the size decreases during the pivot operation but I can't really skip that.
Pre-Pivot DF is ~1230Mb

Post-Pivot DF is ~220Mb

Any tips on how I can improve this to be more memory efficient?
Each sheet needs to be saved to its own CSV but it can be split into multiple CSV files if it helps, like maybe a chunksize style iterator?
import io
import zipfile
from lxml import etree
from pandas import read_csv, to_numeric

class ExcelParse:
    sheet_xslt = etree.XML('''
        <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:sp="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
            >
            <xsl:output method="text"/>
            <xsl:template match="sp:row">
               <xsl:for-each select="sp:c">
                <xsl:value-of select="parent::*/@r"/> <!-- ROW -->
                <xsl:text>,</xsl:text>
                <xsl:value-of select="@r"/> <!--REMOVEME-->
                <xsl:text>,</xsl:text>
                <xsl:value-of select="@t"/> <!-- TYPE -->
                <xsl:text>,</xsl:text>
                <xsl:value-of select="sp:v/text()"/> <!-- VALUE -->
               <xsl:text>\n</xsl:text>
               </xsl:for-each>
            </xsl:template>
        </xsl:stylesheet>
    ''')

    def __init__(self, file):
        self.fh = zipfile.ZipFile(file)
        self.ns = {
            'ns': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
        }
        self.shared = self.load_shared()
        self.workbook = self.load_workbook()

    def load_workbook(self):
        # Load workbook
        name = 'xl/workbook.xml'
        root = etree.parse(self.fh.open(name))
        res = {}
        for el in etree.XPath("//ns:sheet", namespaces=self.ns)(root):
            res[el.attrib['name']] = str(
                int(el.attrib['sheetId']) -
                1)  # Sheet ID in the XML starts at 2 for some reason?
        return res

    def load_shared(self):
        # Load shared strings
        name = 'xl/sharedStrings.xml'
        root = etree.parse(self.fh.open(name))
        res = etree.XPath("/ns:sst/ns:si/ns:t", namespaces=self.ns)(root)
        return {str(pos): el.text for pos, el in enumerate(res)}

    def _parse_sheet(self, root):
        transform = etree.XSLT(self.sheet_xslt)
        result = transform(root)
        df = read_csv(io.StringIO(str(result)),
                      header=None,
                      names=['row', 'cell', 'type', 'value'])
        return df

    def read(self, sheet_name):
        sheet_id = self.workbook[sheet_name]
        sheet_path = f'xl/worksheets/sheet{sheet_id}.xml'
        root = etree.parse(self.fh.open(sheet_path))
        df = self._parse_sheet(root)

        # First row numbers are filled with nan
        df['row'] = to_numeric(df['row'].fillna(0))

        # Translate string contents
        cond = (df.type == 's') & (~df.value.isnull())
        df.loc[cond, 'value'] = df[cond]['value'].map(self.shared)
        # Add column number and sort rows
        df['col'] = df.cell.str.replace(r'[0-9]+', '', regex=True)

        # Pivot everything
        df = df.pivot(
            index='row', columns='col',
            values='value').reset_index(drop=True).reset_index(drop=True)
        df.columns.name = None  # pivot adds a name to the "columns" array
        # Sort columns (pivot will put AA before B)
        cols = sorted(df.columns, key=lambda x: (len(x), x))
        df = df[cols]
        df = df.dropna(how='all')  # Ignore empty lines
        df = df.dropna(how='all', axis=1)  # Ignore empty cols

        new_header = df.iloc[0]  # Grab the first row for the header
        df = df[1:]  # Take the data less the header row
        df.columns = new_header  # Set the header row as the df header

        return df

def new_method():
    xlsx = ExcelParse(
        'BigFile.xlsx'
    )
    print(xlsx.workbook)
    df = xlsx.read('Task')

    # for sheet_name, sheet_id in xlsx.workbook.items():
    #     df = xlsx.read(sheet_name)
    #     do stuff

new_method()

A: To speed up the process, you can try these things and check

*

*Try using xlsx2csv to convert each sheet in the workbook in csv then do a pd.read_csv(). Csv reads are faster than excel.

*As you said, the data is fixed structure and will not change try to use 'dtype' option in read_csv. This will help pandas to avoid automatically identifying data type of each column which will save some time I guess.

For the memory issue,

*

*I was not able to grasp my mind around that 10GB of RAM is fully used but in any case atleast as per my knowledge a drastic improvement may be hard. The use of 'dtype' option may help because some data types take more memory than others, you can make all columns as str and check. read_csv has chunksize option as well. You can explore that.

*You can also explore low_memory and memory_map options in read_csv. I haven't tried them so can't really tell you about the effectiveness.

*In case I got it wrong and if you are talking about storage memory, you can use storage_options in read_csv which will directly read/write from/to S3 in case if you are not doing it.

*If you need more storage memory locally check out EFS for Lambdas.

*On the other hand, you can make a Fargate image and invoke that from your lambda. With this you can get long execution times if that is not the constraint. Check out more.

A: Note that if you have less than 1.7GB of memory in a lambda, you get only a fraction of a CPU. That's why things may look surprisingly slow. By doubling memory you double CPU, which halves execution time (for CPU-bound tasks). Double memory for half duration costs the same amount (assuming it's CPU-bound).
Try bumping up the memory to 1.7GB if it's a single-threaded process. Even more if it's multi-threaded. (I think pandas uses aiobotocore under the hood to download, so more may help.)
That helps address speed.


text:
Q: pyqgis: release all image locks I have a QGIS 3.2 workflow that helps me to mass produce image classiication labels for some deep learning work.  The workflow creates multiple files with various prefixes in tif format.  At the end of it all, the python script below does checks for bugs in some files, applies compression to some tif files, moves the needed files into a designated folder for training a CNN and then deletes files that are no longer needed.  If I run this in Spyder (and quit QGIS) it works fine.  But for the sake of simplicity and productivity, I'm trying to run it in the QGIS python console.  I've successfully installed skimage in the QGIS environment, so no problem with modules.  But, even if I remove all layers from QGIS, I still get permission errors that are presumably from a file lock imposed by QGIS. I need to reboot QGIS which cancels out any time gained when compared to running this in Spyder.   Is there a quick pyqgis command I could issue at the end of the code below to just release all locks? note that I don't even know a priori which layers are locked.
import os
import shutil
import numpy as np
from skimage.external.tifffile import imsave
from skimage import io

#############################################################
#User data input. Fill in the info below before running
PreProcessPath = "D:\\DeepRiverscapes\\PreProcess\\"
TrainPath = "D:\\DeepRiverscapes\\Predict\\"
RiverName = "StMarg"

################################################################
################################################################
#Reconvert the segments to a 1 band set of 1 label objects with integer labels without gaps

def RebuildSegments(Segments):
    FloatValues = np.unique(Segments)
    IntSegments = np.zeros(Segments.shape)
    S=1
    for n in range(0,len(FloatValues)):
        IntSegments[Segments == FloatValues[n]] = S
        S+=1
    return np.int32(IntSegments)

#Check for anomalies in the classification
def CheckClass(Class, name):
        if np.max(Class) > 7:
            print('WARNING some training class labels are greater than expected')
            print(name)
        elif np.min(Class) < 0:
            print('WARNING some training class labels are negative')
            print(name)
        elif np.count_nonzero(Class != np.int32(Class)):
            print('WARNING some training class labels are non-integers')
            print(name)

for i in range(0,99999): #goes to 99999 but do not use that many images!  It will just scan through the possible names
       ImPath = PreProcessPath + RiverName + format(i,'05d') +'_modified' + '.tif'
       ImPathIn = PreProcessPath + RiverName + format(i,'05d') + '.jpg'
       ClassPath = PreProcessPath + 'R_VECT_' + RiverName + format(i,'05d') +'_modified'+'.tif'
       SegPath = PreProcessPath + 'SEG_' + RiverName + format(i,'05d') +'_modified' + '.tif'
       ImPathOut = TrainPath + RiverName + format(i,'05d')  + '.jpg'
       ClassPathOut = TrainPath + 'CLS_' + RiverName + format(i,'05d') +'.tif'
       SegPathOut = TrainPath + 'SEG_' + RiverName + format(i,'05d') + '.tif'
       if os.path.exists(ClassPath):

           Class = io.imread(ClassPath)
           CheckClass(Class,ClassPath)
           imsave(ClassPathOut, Class, compress=7)
           Segments = io.imread(SegPath, as_grey = True)
           Segments_int = RebuildSegments(Segments)
           imsave(SegPathOut, Segments_int, compress=7)
           #Cleanup and move operations
           shutil.move(ImPathIn,ImPathOut)
           os.remove(SegPath)
           os.remove(ImPath)
           os.remove(ClassPath)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotly Draw a 3d line between two points My question is clear. I want to draw 3d line between two points.
I have a set of points
i_list = [(0,0,0), (5,5,5), (10,10,10)]
j_list = [(20,20,20), (25,25,25), (30,30,30)]
I want to draw a line between (0,0,0) and (20,20,20).
Also, another line between (5,5,5) and (25,25,25).
Last line between (10,10,10) and (30,30,30).
how can i do that with python and plotly.

A: If it helps, it is possible to do this relatively simply with matplotlib without the need for plotly. All the user has to do is identify the points correctly and it's done...
here is an example for which solves the question above:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(111, projection='3d')

# lists of points
i_list = [(0,0,0), (5,5,5), (10,10,10)]
j_list = [(20,20,20), (25,25,25), (30,30,30)]

for i in range(3):
    # example of (0,0,0) -> (20,20,20)
    # example of (5,5,5) -> (25,25,25)
    # example of (10,10,10) -> (30,30,30)
    xs = [i_list[i][0],j_list[i][0]]
    ys = [i_list[i][1],j_list[i][1]]
    zs = [i_list[i][2],j_list[i][2]]

    # Plot contour curves
    ax.plot(xs, ys, zs)

plt.show()

The result is this:

A: You can iterate through your list of starting and ending coordinates, and add each pair of points as a go.Scatter3d trace:
import plotly.graph_objects as go

i_list = [(0,0,0), (5,5,5), (10,10,10)]
j_list = [(20,20,20), (25,25,25), (30,30,30)]

fig = go.Figure()
for start, end in zip(i_list, j_list):
    fig.add_trace(go.Scatter3d(
        x=[start[0], end[0]],
        y=[start[1], end[1]],
        z=[start[2], end[2]],
        mode='lines'
    ))

fig.show()


text:
Q: setting up Sift parameters, opencv I 'm implementing sift using opencv 2.3.
Sift implementation with OpenCV 2.2
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <vector>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
  Mat image = imread("TestImage.jpg");

  // Create smart pointer for SIFT feature detector.
  Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT");
  vector<KeyPoint> keypoints;

  // Detect the keypoints
  featureDetector->detect(image, keypoints); // NOTE: featureDetector is a pointer hence the '->'.

  //Similarly, we create a smart pointer to the SIFT extractor.
  Ptr<DescriptorExtractor> featureExtractor = DescriptorExtractor::create("SIFT");

  // Compute the 128 dimension SIFT descriptor at each keypoint.
  // Each row in "descriptors" correspond to the SIFT descriptor for each keypoint
  Mat descriptors;
  featureExtractor->compute(image, keypoints, descriptors);

  // If you would like to draw the detected keypoint just to check
  Mat outputImage;
  Scalar keypointColor = Scalar(255, 0, 0);     // Blue keypoints.
  drawKeypoints(image, keypoints, outputImage, keypointColor, DrawMatchesFlags::DEFAULT);

  namedWindow("Output");
  imshow("Output", outputImage);

  char c = ' ';
  while ((c = waitKey(0)) != 'q');  // Keep window there until user presses 'q' to quit.

  return 0;

}

How can I change default  CommonParams, DetectorParams, DescriptorParams parametrs.

A: The answer is at OpenCV change keypoint or descriptor parameters after creation. Relevant snippet:
featureDetector->set("someParam", someValue);


text:
Q: Get the value inside of url("") I'm trying with the following Regex:
[^url("](.*(?:jpg|jpeg|png|gif))
But I only need the value inside of url(" ")
Example:

*

*from: url("34eb1bd00e8e0e4f59a33f654edc483a.jpg")

*extract: 34eb1bd00e8e0e4f59a33f654edc483a.jpg

A: Try this:

const str = 'background: #fbfbfb url("34eb1bd00e8e0e4f59a33f654edc483a.jpg");';
const regex = /^.*?url\(['"]?([^'"\)]*)['"]?\).*$/;
let result = str.replace(regex, '$1');
console.log(result);

Output:
34eb1bd00e8e0e4f59a33f654edc483a.jpg

Explanation:

*

*^ - anchor at start

*.*? - non-greedy scan

*url\( - literal url(

*['"]? - optional quotes

*([^'"\)]*) - capture group with everything up to a quote or )

*['"]? - optional quotes

*\) - literal )

*.*$ - match all to end of string

A: I hope this goes acording your need's
You can use this pattern for get all between in url("") OR url(''):
(?<=url\(("|')).*?(?=("|')\))

Here is te regex test: URL
And if ypu want get all that only have '.jpg', '.jpeg', '.png', '.gif':
(?<=url\(("|')).*?\.(jpg|jpeg|png|gif)(?=("|')\))

Here is te regex test: URL Img


text:
Q: How do i configure Github to only send notifcations when I'am tagged I have tried for 7 years to configure Github to only notify me:

*

*When I´am being added to a Pull request

*When a pull request I have responded to is updated

*When someone has reviewed my pull request

*Tagged in a comment

Nothing else.
Whatever I do I end up getting either too much or too little notifications. Feels like there something I'am not seeing. There are so many checkboxes :)
(I would prefer the slack github bot, but email also works)
thanks

A: Had the same question. It wasn't obvious at first, but there is a way to set up a Slack integration.

*

*Go to https://github.com/settings/reminders.

*Search for Scheduled reminders in the navigator (Integrations section).

*Click edit reminders for an organization (a pencil icon).

*Authorize your Slack workspace. Do not fill out the form below! It will be cleared after the space authorization. It will write you a personal message in Slack from the GitHub Slack bot.

*Set Days.

*Set Times (multiple select is available) for a time zone.

*Check Enable real-time alerts.

*In the new list below pick your notifications from your PR/comment/mentions/assignments.

*Create or update the reminder.

You can make a test run for the reminder if you have a pending PR. Just click a new button with a megaphone icon (near the pencil button).
Hope, this will help.


text:
Q: C# XMLGregorianCalendar How do I convert XMLGregorianCalendar to C# DateTime? We have C# client application that receives data from Java server and one of type of the field is defined as XMLGregorianCalendar in Java and C# will be receving this as  a string (XMLGregorianCalendar.toXMLFormat()). How can I convert this into a DateTime instance?
Thanks

A: Just add over your XMLGregorianCalendar field annotation:
@XmlSchemaType(name="dateTime")
It will map this field in wsdl to xs:dateTime which generate in your C# webservice proxy class DateTime property.


text:
Q: Rails render doesn't work I'm trying to return a json value from rails controller, but strangely it doesn't work and always wants html format. Here's my controller method:
  def result
        @command = params[:output]
        @result = []
        IO.popen("free -m") { |f| f.each { |e| @result << e } }
    rescue Errno::ENOENT
        @result << "No command found"

    render json: @result.to_json
  end

After I try to reach to this page, I get this kind of error:
Processing by MainController#result as HTML
ActionView::MissingTemplate (Missing template main/result, application/result with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}. Searched in:
  * "/home/vyivrain/Documents/RubyProjects/Diploma/app/views"

Somewhy it only wants html format. I also tried to do respond_to or render nothing or render plain, but it gives the same result. By the way my rails version is 4.1.5. So it's kinda strange. Thx for your answers.

A: Change it to this:
  def result
    begin
        @command = params[:output]
        @result = []
        IO.popen("free -m") { |f| f.each { |e| @result << e } }
    rescue Errno::ENOENT
        @result << "No command found"
    end

    render json: @result.to_json
  end

A: try to specify :remote => true when you click on the link that redirects to result action


text:
Q: pylab in wx application when I try make a picture with pylab
import pylab
pylab.plot([0,1,2,3],[10,50,30,40])
pylab.savefig('graph.png')

in a wx application, no returned the terminal control.

A: I imagine that you are calling the wx main-loop in your main (only?) thread.  However can you clarify the context of your code snippet?  How do you make it into a "wx application" and why do you want terminal control?  For example, do you want to see your figure on screen while also entering stuff at the terminal.  Or do you want to just save it, without it showing on screen?
Anyway, the code snippet you give runs just fine for me, but if I do
import pylab
pylab.plot([0,1,2,3],[10,50,30,40])
pylab.savefig('graph.png')
pylab.plot()

Then if I run your code ...

*

*as "python snippet.py", then it just writes the file and exits, fine.

*from "ipython -wthreads", it shows the plot, saves it and returns control to me.

*from "ipython", then it does it's thing and never returns control.
This is because pylab.plot() calls the main loop of a GUI (gtk in my case, I expect wx will do the same).


text:
Q: I can't mix ECS and k8s slaves My top level pipeline directive looks like this:
pipeline {
    agent {
        kubernetes {
            defaultContainer "mycontainer"
            yaml 'my full podspec'
        }
    }

Then later in a stage I want to use ECS like this:
stage('my stage') {
    agent { node { label 'my-ecs-cluster'; customWorkspace 'myworkspace'; } }

I get this error:
Also:   java.lang.ClassCastException: com.cloudbees.jenkins.plugins.amazonecs.ECSSlave cannot be cast to org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave

If I put the ecs agent in the toplevel pipeline directive and then switch to k8s slaves in subsequent stages I don't get an error. So this is only an issue one way. Very frustrating. I only have a few stages that need the ecs slave for so having to define that as the default in the pipeline definition is a pain.
The bigger issue too is the if I define the ECS slaves in the pipeline definition they are provisioned every time and I have some cases where I don't want them to be provisioned at all because they aren't needed.
Just to add more info, setting agent any or none I don't think will work either because when I specify the agent in multiple stages they use a different container. I want to be able to set the ECS agent at the top-level pipeline when required because then all the stages will run with the same container and use the same workspace.


text:
Q: Relacionar tabela de sub consulta com consulta principal SGDB: MySql.
PROBLEMA: Preciso de alguma forma relacionar a subquery (Sendo tabela e campo em destaque Funcionario.codZona1) com a tabela "Zona", que está na consulta principal. Existe alguma maneira?

Tabela "ZONA":
Contém todas as Zonas da cidade.
Campos da tabela:
"codigo" (INT - Chave - autoincrement - código identificador da tabela),
nomeZona (VARCHAR - nome das Zona)
Dados:
 Código | NomeZona
1 | Zona Centro-Oeste
2 | Zona Centro-Sul
3 | Zona Leste
4 | Zona Norte
5 | Zona Oeste
6 | Zona Sul

Tabelas "ITINERARIO", "ITINERARIODEPENDENTE", "ITINERARIOEXTRA" (TODAS IGUAIS):
Contém lista de funcionários e Zonas onde moram.
Campos da tabela:
"Codigo" (INT - Chave - autoincrement),
"codFuncionario" (INT - Código do funcionário),
"codZona1" (INT - Código da zona onde o funcionário está alocado)
Dados: Codigo | codFuncionario | codZona1
1 | 1 | 5
2 | 2 | 1
3 | 3 | 4
4 | 4 | 3
5 | 5 | 5
6 | 6 | 6
7 | 7 | 2
8 | 8 | 4
9 | 9 | 5

A consulta abaixo tenta exibir a quantidade de "codFuncionario" (Feita por COUNT )existentes nas tabelas "ITINERARIO", "ITINERARIODEPENDENTE" E "ITINERARIOEXTRA" que estão sendo unificadas por UNION, sendo somadas em uma Sub Consulta no trecho "SELECT SUM(qtdPessoas) AS ttPessoas FROM (". E em uma consulta principal (que está acima da SOMA de "qtdPessoas"), está a "nomeZona", que devem ser relacionadas diretamente com a tabelas "ITINERARIO", "ITINERARIODEPENDENTE" E "ITINERARIOEXTRA" pelos campos "codZona1" com o campo "codigo" da tabela "Zona".
    SELECT Zona.nomeZona, (
        SELECT SUM(qtdPessoas) AS ttPessoas FROM (
            SELECT      COUNT(DISTINCT Itinerario.codFuncionario) AS qtdPessoas
            FROM        Itinerario
            WHERE       Itinerario.codZona1 = Zona.codigo
            UNION ALL
            SELECT      COUNT(DISTINCT ItinerarioDependente.codDependente) AS qtdPessoas
            FROM        ItinerarioDependente
            WHERE       ItinerarioDependente.codZona1 = Zona.codigo
            UNION ALL
            SELECT      COUNT(DISTINCT ItinerarioExtra.codExtra) AS qtdPessoas
            FROM        ItinerarioExtra
            WHERE       ItinerarioExtra.codZona1 = Zona.codigo)
        AS tbP1) AS QtdFuncionarios
    FROM Zona

Pois da maneira que estou fazendo, está resultado assim:
Zona Centro-Oeste   900
Zona Centro-Sul     900
Zona Leste          900
Zona Norte          900
Zona Oeste          900
Zona Sul            900

Ao invés de vir assim:
Zona Centro-Oeste   100
Zona Centro-Sul     200
Zona Leste          100
Zona Norte          400
Zona Oeste          50
Zona Sul            50

A:  SELECT Zona.nomeZona, (
        SELECT SUM(qtdPessoas) AS ttPessoas FROM (
            SELECT      COUNT(DISTINCT Itinerario.codFuncionario) AS qtdPessoas,
                        Itinerario.codZona1
            FROM        Itinerario
            GROUP BY       Itinerario.codZona1
            UNION ALL
            SELECT      COUNT(DISTINCT ItinerarioDependente.codDependente) AS qtdPessoas,
                        ItinerarioDependente.codZona1
            FROM        ItinerarioDependente
            GROUP BY  ItinerarioDependente.codZona1
            UNION ALL
            SELECT      COUNT(DISTINCT ItinerarioExtra.codExtra) AS qtdPessoas,
                        ItinerarioExtra.codZona1
            FROM        ItinerarioExtra
            GROUP BY       ItinerarioExtra.codZona1)
        AS tbP1
        WHERE tbP1.codZona1 = Zona.codigo) AS QtdFuncionarios
    FROM Zona

Como nosso amigo acima disse seria assim a consulta;


text:
Q: How to add gesture recognizers to multiple buttons? Hi, I am trying to add gesture recognizers to 'UIButton'. When I do it like this:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.LeftBottomSpaceBtn addGestureRecognizer:singleTap];
[singleTap requireGestureRecognizerToFail:doubleTap];
[singleTap release];

It works properly, but when I tried to add this gesture to multiple buttons it did not work:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.LeftBottomSpaceBtn addGestureRecognizer:singleTap];
[self.LeftUpSpaceBtn addGestureRecognizer:singleTap];
[self.RightBUpSpaceBtn addGestureRecognizer:singleTap];
[self.LeftReturnBtn addGestureRecognizer:singleTap];
[self.RightReturnBtn addGestureRecognizer:singleTap];
[self.DeleteBtn addGestureRecognizer:singleTap];
[self.CapsBtn addGestureRecognizer:singleTap];
[singleTap requireGestureRecognizerToFail:doubleTap];
[singleTap release];

So how can I add the same gesture to multiple buttons in the same way I have added the 'longPress' and 'doubleTap'?

A: I'd suggest the following:
NSMutableSet *buttons = [[NSMutableSet alloc] init];

[buttons addObject: self.LeftBottomSpaceBtn];
[buttons addObject: self.LeftUpSpaceBtn];
[buttons addObject: self.RightBUpSpaceBtn];
[buttons addObject: self.LeftReturnBtn];
[buttons addObject: self.RightReturnBtn];
[buttons addObject: self.DeleteBtn];
[buttons addObject: self.CapsBtn];

for(UIButton *button in buttons)
{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [button addGestureRecognizer:singleTap];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [singleTap release];
}

If you save the set as a variable, you can do other stuff for all buttons as well, such as releasing them all and changing all their backgroundColors, without calling them all individually.
You will probably need to make seperate doubletaprecognizers for each button as well.

A: You can add one gesture recognizer to one view alone. If you add it to more than one views, the last added view will be added with the recognizer.
Create different instances of gesture recognizers and add them to individual views.


text:
Q: VS Code's flake8's ignore arguments don't work on format on save? Here is my settings.json:
{
    "python.pythonPath": "/home/zhaodachuan/anaconda3/envs/ranking_engine/bin/python",
    "python.autoComplete.extraPaths": [
        "/mnt/c/Users/hnjyz/OneDrive/jupyter_lab/code/ranking_engine",
    ],
    "python.linting.pylintEnabled": false,
    "python.linting.enabled": true,
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": [
        "--max-line-length=120",
        "--ignore=E402,F401",
    ],
}

But the flake8 --ignore doesn't work when I turn on the format on save in VS Code.
What should I do?

A: Flake8 is not a formatter, it's a linter.
It's certainly one of the supported linters of VS Code's Python extension, but it will not affect the setting editor.formatOnSave or be triggered by the Format Document command. If configured correctly, it should automatically run and check your file for possible issues, then display them on the Problems tab:

If I add:
    "python.linting.flake8Args": [
        "--ignore=F401"
    ],

Then the previously displayed F401 error should disappear:

What you seem to be looking for is a formatter. See the Formatting section of the VS Code docs on Python: https://code.visualstudio.com/docs/python/editing#_formatting:

Formatting makes code easier to read by human beings by applying
specific rules and conventions for line spacing, indents, spacing
around operators, and so on (see an example on the autopep8 page).
Formatting doesn't affect the functionality of the code itself.
(Linting, on the other hand, analyzes code for common syntactical,
stylistic, and functional errors as well as unconventional programming
practices that can lead to errors. Although there is a little overlap
between formatting and linting, the two capabilities are
complementary.)
The Python extension supports source code formatting using either
autopep8 (the default), black, or yapf.

Install one of the selected formatters, and enable formatOnSave:
    "[python]": {
        "editor.formatOnSave": true
    },
    "python.formatting.provider": "yapf",
    "python.formatting.yapfPath": "/usr/local/bin/yapf",
    "python.formatting.yapfArgs": [
        "--style=/path/to/setup.cfg"
    ],


text:
Q: Show and Hide options are captured commonly to single Id in the table Here when I click the glyphicon it has to display a show hide function for a single column. Where now when I click the glyphicon it shows the function commonly for the first one only.
Here's the fiddle https://jsfiddle.net/7vcqpo0t/2/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />

<div class="col-lg-12" style="width: 100%"

        Driver
        First Name
        Cell Phone
        Acct To
        Container#
        Ord Typ
        Start Date
        Start Time
        Sched From
        Sched To
        Order Status

        <button class="btn btn-default btn-xs">

</button>

         /%DADRVC%/
         /%NMEFRS%/
         /%PHNCEL%/
         /%DAACCO%/
         /%DACNT#%/
         /%DAORDT%/
         /%DASTRD%/
         /%DASTRT%/
         /%DASAFR%/
         /%DASATO%/
         /%DAORDS%/

                <form name="form1" method="post" action="DRVAPP100C.PGM">
                  <input type="submit" value="Send" class="btn btn-default btn-md btn3d" name="SUBMIT">

        <input name=SCR type=hidden value="SM">
        <input name=DRVA type=hidden value="/%DRVA%/">
        <input name=DRVC type=hidden value="/%DRVC%/">
        <input name=SMSTXT type=text>
        </form>

          <button type="button" class="btn btn-default btn-md btn3d">
 Mobile App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Show Text</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Update App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Thank You</button>

        <button class="btn btn-default btn-xs">

</button>

         /%DADRVC%/
         /%NMEFRS%/
         /%PHNCEL%/
         /%DAACCO%/
         /%DACNT#%/
         /%DAORDT%/
         /%DASTRD%/
         /%DASTRT%/
         /%DASAFR%/
         /%DASATO%/
         /%DAORDS%/

                <form name="form1" method="post" action="DRVAPP100C.PGM">
                  <input type="submit" value="Send" class="btn btn-default btn-md btn3d" name="SUBMIT">

        <input name=SCR type=hidden value="SM">
        <input name=DRVA type=hidden value="/%DRVA%/">
        <input name=DRVC type=hidden value="/%DRVC%/">
        <input name=SMSTXT type=text>
        </form>

          <button type="button" class="btn btn-default btn-md btn3d">
 Mobile App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Show Text</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Update App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Thank You</button>

A: Working fiddle.
You've to change the duplicate id's  demo1 should be demo2 in the second button since the id should be unique in the same document :

Change the data-target too :

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />

<div class="col-lg-12" style="width: 100%"

        Driver
        First Name
        Cell Phone
        Acct To
        Container#
        Ord Typ
        Start Date
        Start Time
        Sched From
        Sched To
        Order Status

        <button class="btn btn-default btn-xs">

</button>

         /%DADRVC%/
         /%NMEFRS%/
         /%PHNCEL%/
         /%DAACCO%/
         /%DACNT#%/
         /%DAORDT%/
         /%DASTRD%/
         /%DASTRT%/
         /%DASAFR%/
         /%DASATO%/
         /%DAORDS%/

                <form name="form1" method="post" action="DRVAPP100C.PGM">
                  <input type="submit" value="Send" class="btn btn-default btn-md btn3d" name="SUBMIT">

        <input name=SCR type=hidden value="SM">
        <input name=DRVA type=hidden value="/%DRVA%/">
        <input name=DRVC type=hidden value="/%DRVC%/">
        <input name=SMSTXT type=text>
        </form>

          <button type="button" class="btn btn-default btn-md btn3d">
 Mobile App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Show Text</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Update App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Thank You</button>

        <button class="btn btn-default btn-xs">

</button>

         /%DADRVC%/
         /%NMEFRS%/
         /%PHNCEL%/
         /%DAACCO%/
         /%DACNT#%/
         /%DAORDT%/
         /%DASTRD%/
         /%DASTRT%/
         /%DASAFR%/
         /%DASATO%/
         /%DAORDS%/

                <form name="form1" method="post" action="DRVAPP100C.PGM">
                  <input type="submit" value="Send" class="btn btn-default btn-md btn3d" name="SUBMIT">

        <input name=SCR type=hidden value="SM">
        <input name=DRVA type=hidden value="/%DRVA%/">
        <input name=DRVC type=hidden value="/%DRVC%/">
        <input name=SMSTXT type=text>
        </form>

          <button type="button" class="btn btn-default btn-md btn3d">
 Mobile App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Show Text</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Update App</button>

          <button type="button" class="btn btn-default btn-md btn3d">
 Thank You</button>


text:
Q: What is the right way to run python vaex.ml.catboost.CatBoostModel.fit in parallel for several folds? Description
I have a python code that sequentially calls vaex.ml.catboost.CatBoostModel.fit for 3 folds.
It takes a lot of time, I would like to run vaex.ml.catboost.CatBoostModel.fit in parallel.
Problem
I get different results when I run vaex.ml.catboost.CatBoostModel.fit sequentially and in parallel. Definitely, I do smth wrong. I expect parallel results be very close to sequential results (seed is not hardcoded, so there is always some minor fluctuation). Sequential and parallel versions produce absolutely incomparable results.
Here is sequential code. It produces approved result
estimator = CatBoostModel(
        features=features + features_cat,
        target=target,
        num_boost_round=700,
        prediction_name="catboost_prediction",
        prediction_type=prediction_type
    )

for fold in folds:
    logging.info(f"training fold: {fold}")  # 1,2,3
    df_train = df[df.cv_fold != fold]
    df_val = df[df.cv_fold == fold]
    estimator.fit(df=df_train, evals=[df_val], early_stopping_rounds=100, verbose_eval=True)
    cv_scores[cv_fold == fold] = estimator.predict(df_val)

Here is my parallel code:
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_to_result = {executor.submit(train_fold, fold, cv_scores, df, task, estimator): fold for fold in
                        folds}
    for future in concurrent.futures.as_completed(future_to_result):
        res = future_to_result[future]
        (fold, result) = future.result()
        logging.info(f"completed future for {fold}, result: {result.shape}")
        cv_scores[cv_fold == fold] = result

def train_fold(fold,
               cv_scores,
               df, estimator: CatBoostModel):
    logging.info(f"training fold: {fold}")
    df_train = df[df.cv_fold != fold]
    df_val = df[df.cv_fold == fold]
    estimator.fit(df=df_train, evals=[df_val], early_stopping_rounds=100, verbose_eval=True)
    result = estimator.predict(df_val)

    return (fold, result)


text:
Q: befor the MainActivity shows in my app a white page shows in android i wrote an app and my first activity is splash screen but befor this activity a null white page shows. how i can remove that?
this is my code
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    getActionBar().hide();
    delay=4000;
    new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
    Intent intent_obj=new Intent(Splash.this,Content.class);
    startActivity(intent_obj);
    finish();
    }
    },delay);

A: try adding your handler code in a separate function.
 public void splashTimer(int duration) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent_obj = new Intent(Splash.this, Content.class);
            startActivity(intent_obj);
            finish();
        }
    }, duration);
}

and call it from the onCreate() method


text:
Q: How to use machine learning on unlabeled data to predict input features as the output? Firstly, sorry if the question is confusing, it was hard to phrase the question without properly explaining what I want to achieve. To make the problem statement more understandable, I made-up the following scenario (please bear with me):
I am in a factory that makes muffins in batches. They get the muffin mixture from a supplier, but due to variation, the muffin mixture is sometimes short of certain ingredients. The lead baker must add or remove ingredients from the mixture to ensure the best flavor and quality.
For each batch of muffins, a sample is taken and analysed. The results give you a breakdown of the ingredients contained in the sample muffin.
Suppose that for a batch of chocolate muffins, the results for the sample muffin are as follows:

*

*Sugar: 40g

*Chocolate chips: 10g

*Peanut Butter: 0g

*Cocoa Powder: 5g

*Flour: 80g

*Other: 5g

For each of these ingredients/"features", there's an ideal value that it should have.  In this sample, there is not enough chocolate chips; it is out of the ideal weight by 5g (i.e there should have been 15g of chocolate chips) . The lead baker decides to add 1 kg of chocolate chips to the next batch of chocolate muffin mixture, leaving all other ingredients the same since they are in their ideal range.  Now, in the next batch, due to the baker's adjustment, the results obtained for the sample are as follows:

*

*Sugar: 41g

*Chocolate chips: 17g

*Peanut Butter: 0g

*Cocoa Powder: 5g

*Flour: 78g

*Other: 5g

So, the baker adjusts the ingredients when needed to get the ideal muffin. He/she is making sure to record any changes he/she makes. The results for each batch are also recorded somewhere.
Now the goal: I want to predict what proportion of our own ingredients to add to get the best possible muffin mixture.
To summarize, the input data is as follows:
(Ingredients before lead-baker adjustment)

 - Datetime: 202001010900
 - Sugar: 40g
 - Chocolate chips: 10g
 - Peanut Butter: 0g
 - Cocoa Powder: 5g
 - Flour: 80g
 - Other: 5g

(Lead-baker adjustment)

 - Datetime: 202001011000
 - Chocolate: 1 kg

(Ingredients after most recent lead-baker adjustment)

 - Datetime: 202001011100
 - Sugar: 41g
 - Chocolate chips: 17g
 - Peanut Butter: 0g
 - Cocoa Powder: 5g
 - Flour: 78g
 - Other: 5g

(Lead-baker adjustment)

 - Datetime: 202001011200
 - Sugar: -100 g

+++hundreds of other similar entries.
After learning the effect of several adjustments, the algorithm should have predicted that, in the first example, the best adjustment to make would have been to add 800 g of chocolate to the mix(which in theory would give us the ideal value of 15g of chocolate chips for each muffin).
What ML algorithm can actually achieve this ? I have worked on a few ML/Deep learning problems,but none of them are like this, where we have unlabeled data, we want to determine a relationship between the features and predict feature values as the output. I have tried going over many more examples, but none seem to remotely fit a problem type like this.

A: You can frame your problem as a denoising task.
That is, for a given input list of "noisy" ingredient quantities, output a list of adjusted ingredient quantities.
I would proceed as follow.

*

*Make a dataset of adjusted ingredient batches

*Make a dataset of "noisy" ingredient batches. To do so, you can use your data of ingredient batches before adjustement by baker, and augment this dataset by randomly add noise to adjusted ingredient batches

*Train your model at predicting the adjusted batch given a corresponding noisy one.

Denoising autoencoder is a popular model for this, especially in natural language processing, for tasks like spelling-mistakes auto-correction.
Though the original statement of your problem is a regression task, you can convert it  into a classification problem by binning your ingredient quantities. Here is an example on how to do this.


text:
Q: Jest defaults to format currency to "en-US" even when the window navigator language is mocked to be "en-GB" I have a test file and am testing for the formatCurrency function. The problem, even though I've mocked window.navigator.language to be en-GB my function in test doesn't format the currency in £. In the UI it works as expected, but in jest looks like you can't change window.navigator.language. Any suggestions?
const languageCurrency = {
  "en-GB": "GBP",
  "en-US": "USD",
};

const userLanguage = window.navigator.language

export const formatCurrency = (value) =>
  Intl.NumberFormat(userLanguage, {
    style: "currency",
    currency: languageCurrency[userLanguage],
  }).format(value);

and here is my test file
import { formatCurrency } from "./formatCurrency";

describe("given formatCurrency fucntion", () => {
  let windowSpy;

  beforeEach(() => {
    windowSpy = jest.spyOn(window, "window", "get");
  });

  afterEach(() => {
    windowSpy.mockRestore();
  });

  it("should set the user language to `en-GB`", () => {
    windowSpy.mockImplementation(() => ({
      navigator: {
        language: "en-GB",
      },
    }));

    expect(window.navigator.language).toBe("en-GB"); //this will pass
    expect(formatCurrency(1000)).toBe("£1000.00"); // this fails
  });
});

A: Since the userLanguage variable is assigned in the module scope. You should mock window.navigator.language first, then import the module. So that the userLanguage variable will be assigned with the mock value.
Note: The code defined in the module scope will be executed immediately when you import the module.
Besides, the formatted currency should be '£1,000.00'
Intl.NumberFormat('en-GB', {style: 'currency', currency: 'GBP'}).format(1000)
// '£1,000.00'

E.g.
formatCurrency.ts:
const languageCurrency = {
  'en-GB': 'GBP',
  'en-US': 'USD',
};

const userLanguage = window.navigator.language;

export const formatCurrency = (value) => {
  console.debug('languageCurrency[userLanguage]: %s userLanguage: %s', languageCurrency[userLanguage], userLanguage);
  return Intl.NumberFormat(userLanguage, {
    style: 'currency',
    currency: languageCurrency[userLanguage],
  }).format(value);
};

formatCurrency.test.ts:
// import { formatCurrency } from './formatCurrency';

describe('given formatCurrency fucntion', () => {
  let windowSpy;

  beforeEach(() => {
    windowSpy = jest.spyOn(window, 'window', 'get');
    jest.resetModuleRegistry();
  });

  afterEach(() => {
    windowSpy.mockRestore();
  });

  it('should set the user language to `en-GB`', async () => {
    windowSpy.mockImplementation(() => ({
      navigator: {
        language: 'en-GB',
      },
    }));

    const { formatCurrency } = await import('./formatCurrency');

    expect(window.navigator.language).toBe('en-GB');
    expect(formatCurrency(1000)).toBe('£1,000.00');
  });

  it('should set the user language to `en-US`', async () => {
    windowSpy.mockImplementation(() => ({
      navigator: {
        language: 'en-US',
      },
    }));

    const { formatCurrency } = await import('./formatCurrency');

    expect(window.navigator.language).toBe('en-US');
    expect(formatCurrency(1000)).toBe('$1,000.00');
  });
});

Test result:
 PASS  stackoverflow/75399792/formatCurrency.test.ts (11.303 s)
  given formatCurrency fucntion
    ✓ should set the user language to `en-GB` (41 ms)
    ✓ should set the user language to `en-US` (3 ms)

  console.debug
    languageCurrency[userLanguage]: GBP userLanguage: en-GB

      at formatCurrency (stackoverflow/75399792/formatCurrency.ts:9:11)

  console.debug
    languageCurrency[userLanguage]: USD userLanguage: en-US

      at formatCurrency (stackoverflow/75399792/formatCurrency.ts:9:11)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        12.209 s


text:
Q: Otimização de query SQL SERVER Estou com um problema de desempenho na query abaixo. Tenho um banco de dados razoavelmente grande e com isso a execução do comando demora um bom tempo para ser executado.
O comando basicamente mostra algumas informações sobre produtos, taxas e a quantidade sugerida de produtos que o cliente deve comprar em produtos seguindo valores de quantidade por deposito data, quantidade vendida e etc(esta coluna é o problema). Preciso de dicas e sugestoes para melhoria de desempenho
SELECT DISTINCT p.id                                                     AS
                'Cód. Produto',
                p.nome                                                   AS
                'Produto',
                (SELECT TOP 1 codigo_barras
                 FROM   produto_cod_barra
                 WHERE  id_produto = p.id)                               AS
                'Cód. Barras',
                (SELECT Sum(a.quantidade)
                 FROM   estoque a
                 WHERE  a.id_produto = p.id
                        AND a.id_deposito IN( 1 )
                        AND a.id_deposito IN (SELECT b.id
                                              FROM   deposito b
                                              WHERE  b.id_empresa = 1))  AS
                'ATALIBA - Estoque',
                CONVERT(INT, Isnull((SELECT Sum(a.quantidade)
                                     FROM   venda_item_produto a
                                            INNER JOIN venda aa
                                                    ON aa.id = a.id_venda
                                     WHERE  aa.id_empresa = 1
                                            AND p.id = a.id_produto
                                            AND aa.data BETWEEN
                                                '2022-09-01 00:00:00' AND
                                                '2022-11-30 23:59:00'
                                            AND aa.cancelada = 'N'), 0)) AS
                'ATALIBA - Qtde. Vendida',
                Isnull((SELECT Sum(pit.quantidade)
                        FROM   pedido_item pit
                               INNER JOIN pedido ped WITH (nolock)
                                       ON ped.id = pit.id_pedido
                        WHERE  ped.realizou_entrada = 0
                               AND ped.cancelado = 0
                               AND ped.id_empresa = 1
                               AND pit.id_produto = p.id), 0)            AS
                'ATALIBA - Qtde. Pedida',
                Isnull(Cast((SELECT Sum(a.valor_custo)
                             FROM   produto_empresa a
                             WHERE  a.id_produto = p.id
                                    AND a.id_empresa = 1) /
                            (SELECT Count(a.valor_custo)
                             FROM   produto_empresa a
                             WHERE  a.id_produto = p.id
                                    AND a.id_empresa = 1) AS
                                   DECIMAL(10, 2)), 0)                   AS
                'ATALIBA - Custo Un',
                Cast(p.valor_negociacao AS DECIMAL(18, 2))               AS
                'Valor Negociação',
                depa.departamento                                        AS
                'Departamento',
                cate.categoria                                           AS
                'Categoria',
                subc.subcategoria                                        AS
                'Sub-Categoria',
                marca.marca                                              AS
                'Marca',
                Cast(CASE
                       WHEN RIGHT(CASE
                                    WHEN Isnull((
                                    ( (SELECT Sum(a.quantidade)
                                       FROM   venda_item_produto a
                                              INNER JOIN venda aa
                                                      ON
                                              aa.id = a.id_venda
                                       WHERE  Cast(aa.data AS DATE
                                              ) BETWEEN
                                              '2022-09-01 00:00:00' AND
                                              '2022-11-30 23:59:00'
                                              AND aa.id_empresa = 1
                                              AND p.id = a.id_produto
                                              AND aa.cancelada = 'N') / ((
                                             Cast(( CASE
                                                      WHEN Datediff(day,
                                                           '2022-09-01 00:00:00'
                                                           ,
                                                           '2022-11-30 23:59:00'
                                                           )
                                                           + 1 = 0 THEN 1
                                                      ELSE Datediff(day,
                                                           '2022-09-01 00:00:00'
                                                           ,
                                                           '2022-11-30 23:59:00'
                                                           )
                                                           + 1
                                                    END ) AS INT) )) * 91 ) -
                                                    (SELECT
                                    Sum(CASE
                                          WHEN a.quantidade < 0
                                        THEN 0
                                          WHEN a.quantidade >=
                                               0 THEN
                                          a.quantidade
                                          ELSE 0
                                        END)
                                                     FROM   estoque a
                                                     WHERE  a.id_produto = p.id
                                                            AND a.id_deposito IN
                                                    (SELECT b.id
                                                     FROM   deposito b
                                                     WHERE  b.id_empresa =
                                                            1))
                                         ), 0) < 0 THEN 0
                                    ELSE Isnull((
                                  ( (SELECT Sum(a.quantidade)
                                     FROM   venda_item_produto a
                                            INNER JOIN venda aa
                                                    ON
                                            aa.id = a.id_venda
                                     WHERE  Cast(aa.data AS DATE
                                            ) BETWEEN
                                            '2022-09-01 00:00:00' AND
                                            '2022-11-30 23:59:00'
                                            AND aa.id_empresa = 1
                                            AND p.id = a.id_produto
                                            AND aa.cancelada = 'N') / ((
                                           Cast(( CASE
                                                    WHEN Datediff(day,
                                                         '2022-09-01 00:00:00',
                                                         '2022-11-30 23:59:00')
                                                         + 1 = 0 THEN 1
                                                    ELSE Datediff(day,
                                                         '2022-09-01 00:00:00',
                                                         '2022-11-30 23:59:00')
                                                         + 1
                                                  END ) AS INT) )) * 91 ) -
                                                  (SELECT
                                  Sum(CASE
                                        WHEN a.quantidade < 0
                                      THEN 0
                                        WHEN a.quantidade >=
                                             0 THEN
                                        a.quantidade
                                        ELSE 0
                                      END)
                                                   FROM   estoque a
                                                   WHERE  a.id_produto = p.id
                                                          AND a.id_deposito IN
                                                  (SELECT b.id
                                                   FROM   deposito b
                                                   WHERE  b.id_empresa =
                                                          1))
                                       ), 0)
                                  END, 5) > 0 THEN
                       Cast(CASE WHEN Isnull((((SELECT
                       Sum(a.quantidade)
                       FROM venda_item_produto a
                       INNER JOIN venda aa ON aa.id = a.id_venda
                       WHERE
                       Cast(aa.data AS DATE) BETWEEN
                       '2022-09-01 00:00:00' AND '2022-11-30 23:59:00'
                       AND aa.id_empresa = 1 AND p.id = a.id_produto AND
                       aa.cancelada = 'N') / ((Cast((CASE WHEN Datediff(
                       day, '2022-09-01 00:00:00', '2022-11-30 23:59:00')
                       + 1 = 0 THEN 1 ELSE Datediff(day,
                       '2022-09-01 00:00:00', '2022-11-30 23:59:00') + 1
                       END) AS INT))) *91) - (SELECT Sum(CASE WHEN
                       a.quantidade < 0 THEN 0 WHEN a.quantidade >= 0
                       THEN
                       a.quantidade ELSE 0 END) FROM estoque a WHERE
                       a.id_produto =
                       p.id AND a.id_deposito IN (SELECT b.id FROM
                       deposito b
                       WHERE b.id_empresa = 1 ))), 0) < 0 THEN 0 ELSE
                       Isnull((((SELECT Sum(a.quantidade) FROM
                       venda_item_produto a INNER JOIN venda aa ON aa.id
                       = a.id_venda WHERE Cast(aa.data AS DATE) BETWEEN
                       '2022-09-01 00:00:00' AND '2022-11-30 23:59:00'
                       AND aa.id_empresa = 1 AND p.id = a.id_produto AND
                       aa.cancelada = 'N' ) / ((Cast((CASE WHEN Datediff(
                       day, '2022-09-01 00:00:00', '2022-11-30 23:59:00')
                       + 1 = 0 THEN 1 ELSE Datediff(day,
                       '2022-09-01 00:00:00', '2022-11-30 23:59:00') + 1
                       END) AS INT))) *91) - (SELECT Sum(CASE WHEN
                       a.quantidade < 0 THEN 0 WHEN a.quantidade >= 0
                       THEN
                       a.quantidade ELSE 0 END) FROM estoque a WHERE
                       a.id_produto =
                       p.id AND a.id_deposito IN (SELECT b.id FROM
                       deposito b
                       WHERE b.id_empresa = 1 ))), 0) END AS INT) + 1
                       ELSE
                         CASE
                           WHEN Isnull(( ( (SELECT Sum(a.quantidade)
                                            FROM   venda_item_produto a
                                                   INNER JOIN venda aa
                                                           ON aa.id = a.id_venda
                                            WHERE  Cast(aa.data AS DATE) BETWEEN
                                                   '2022-09-01 00:00:00' AND
                                                   '2022-11-30 23:59:00'
                                                   AND aa.id_empresa = 1
                                                   AND p.id = a.id_produto
                                                   AND aa.cancelada = 'N') / ((
                                                  Cast(( CASE
                                                           WHEN Datediff(day,
                                                  '2022-09-01 00:00:00',
                                                  '2022-11-30 23:59:00')
                                                  + 1 = 0 THEN 1
                                                           ELSE Datediff(day,
                                                  '2022-09-01 00:00:00',
                                                  '2022-11-30 23:59:00')
                                                  + 1
                                                         END ) AS INT) )) * 91 )
                                         -
                                                         (SELECT
                                         Sum(CASE
                                               WHEN a.quantidade < 0
                                             THEN 0
                                               WHEN a.quantidade >= 0
                                             THEN
                                               a.quantidade
                                               ELSE 0
                                             END)
                                                          FROM   estoque a
                                                          WHERE
                                         a.id_produto = p.id
                                         AND a.id_deposito IN
                                             (SELECT b.id
                                              FROM   deposito b
                                              WHERE  b.id_empresa = 1))
                                              ), 0) < 0 THEN 0
                           ELSE Isnull(( ( (SELECT Sum(a.quantidade)
                                            FROM   venda_item_produto a
                                                   INNER JOIN venda aa
                                                           ON aa.id = a.id_venda
                                            WHERE  Cast(aa.data AS DATE) BETWEEN
                                                   '2022-09-01 00:00:00' AND
                                                   '2022-11-30 23:59:00'
                                                   AND aa.id_empresa = 1
                                                   AND p.id = a.id_produto
                                                   AND aa.cancelada = 'N') / ((
                                                  Cast(( CASE
                                                           WHEN Datediff(day,
                                                  '2022-09-01 00:00:00',
                                                  '2022-11-30 23:59:00')
                                                  + 1 = 0 THEN 1
                                                           ELSE Datediff(day,
                                                  '2022-09-01 00:00:00',
                                                  '2022-11-30 23:59:00')
                                                  + 1
                                                         END ) AS INT) )) * 91 )
                                         -
                                                         (SELECT
                                         Sum(CASE
                                               WHEN a.quantidade < 0
                                             THEN 0
                                               WHEN a.quantidade >= 0
                                             THEN
                                               a.quantidade
                                               ELSE 0
                                             END)
                                                          FROM   estoque a
                                                          WHERE
                                         a.id_produto = p.id
                                         AND a.id_deposito IN
                                             (SELECT b.id
                                              FROM   deposito b
                                              WHERE  b.id_empresa = 1))
                                              ), 0)
                         END
                     END AS INT)                                         AS
                'ATALIBA - Sugestão'
FROM   produto p WITH (nolock)
       LEFT JOIN produto_empresa pe
              ON pe.id_produto = p.id
       LEFT JOIN produto_departamento depa
              ON depa.id = p.id_departamento
       LEFT JOIN produto_categoria cate
              ON cate.id = p.id_categoria
       LEFT JOIN produto_subcategoria subc
              ON subc.id = p.id_subcategoria
       LEFT JOIN produto_marca marca
              ON marca.id = p.id_marca
       LEFT JOIN produto_fornecedor pf
              ON pf.id_produto = p.id
WHERE  pe.ativo = 1
-- AND pf.ID_Fornecedor = 130720
ORDER  BY p.id


text:
Q: Product manifolds in Dieudonné, Vol. 3: Reduction of proofs to open sets in $ \mathbb R^n $ In section 16.6 of his "Treatise on Analysis", Vol. 3, Jean Dieudonné introduces product manifolds. All proves of the theorems of this section are, for simplification and efficiency reasons, reduced to the case that the involved differentiable manifolds are open subsets of $ \mathbb R^{n_1}, \mathbb R^{n_2} $, etc. Dieudonné succinctly justifies this reduction with the nature of the definition of product manifolds. This argument appears first in 16.6.2 on the top of page 36.
I don't understand this argument right from the beginning, and so all the proves of this section remain vague to me. Can anyone explain the justification for the use of this reduction in this section in some more detail, please? (BTW, for 16.6.2 I found a proof without using this assumption, but not for the following numbers.) Thanks a lot in advance.

A: In essence, you're utilizing the fact that manifolds come equipped with charts and that maps defined on manifolds have corresponding local expressions obtained by composing with charts (see the very first paragraph in 16.3).

Consider a theorem of the following type:

Let $X,Y$ be smooth manifolds and $f:X\to Y$ a mapping. If $f$ satisfies some hypotheses $H$ then it satisfies some conclusion $C$.

Very often when we "reduce to open sets in $\Bbb{R}^n$" what we're taking advantage of is that the conclusion $C$ is "(local) diffeomorphism invariant", in the sense that one or more of the following is true:

*

*if $\alpha:X\to X'$ is a diffeomorphism then the same conclusion holds for $f\circ\alpha^{-1}:X'\to Y$

*if $U\subset X$ is open and $\alpha:U\to X'$ is a diffeomorphism then the same conclusion holds for $f\circ \alpha^{-1}:X'\to Y$

*if $\beta:Y\to Y'$ is a diffeomorphism then the same conclusion for $\beta\circ f:X\to Y'$

*if $V\subset Y$ is open and $\beta:V\to Y'$ is a diffeomorphism then the same conclusion holds for $\beta\circ f:X\to Y'$
and due to this, we're using the fact that manifolds come equipped with charts (which are diffeomorphisms), so that by composing $f$ on the domain and target with chart maps, we get a local representative map for $f$ between open subsets of $\Bbb{R}^{n_1}\to\Bbb{R}^{n_2}$, and then we prove the theorem there (and usually it's obvious there by inspection).
For example, $H$ could be an assumption on the specific form of the maps involved and $C$ could refer to smoothness of a map (this is clearly preserved under composition by diffeomorphisms). Another example is that $H$ could be an assumption placed on the tangent mapping $Tf_x$, and $C$ could be something like "is a local diffeomorphism". In this case, it is once again clear that any linear-algebra condition on $Tf_x$ will be preserved because $\alpha,\beta$ being diffeomorphisms means that their derivatives are linear isomorphisms.
Hopefully, the above is a general enough for you to get a rough idea of what's going on. As a specific illustration, let me consider (part of) the next theorem in Dieudonne (16.6.4)

Let $Y,X_1,X_2$ be smooth manifolds and $f_1:Y\to X_1$ and $f_2:Y\to X_2$ be two mappings. Then, the mapping $f=(f_1,f_2):Y\to X_1\times X_2$ is $C^{\infty}$ if and only if $f_1$ and $f_2$ are $C^{\infty}$.

Recall that a mapping is $C^{\infty}$ by definition if when you compose with charts on the domain and on the target, the corresponding map between open subsets of cartesian spaces is $C^{\infty}$. So, consider arbitrary charts $(V_1,\beta_1)$ on $X_1$ and $(V_2,\beta_2)$ on $X_2$ and $(U,\alpha)$ on $Y$ such that $f_1(U)\subset V_1$ and $f_2(U)\subset V_2$. Then the corresponding product chart on $X_1\times X_2$ is given by $(V_1\times V_2, \beta_1\times \beta_2)$. So, we have that

*

*$f$ is $C^{\infty}$ on $U$  (by definition) if and only if $(\beta_1\times \beta_2)\circ f \circ \alpha^{-1} = (\beta_1\circ f_1\circ \alpha^{-1}, \beta_2\circ f_2\circ\alpha^{-1})$ is $C^{\infty}$ as a mapping between open subsets of cartesian spaces.

*$f_1$ is $C^{\infty}$ on $U$ (by definition) if and only if $\beta_1\circ f_1\circ \alpha^{-1}$ is $C^{\infty}$ as a mapping between open subsets of cartesian spaces

*$f_2$ is $C^{\infty}$ on $U$ (by definition) if and only if $\beta_2\circ f_2\circ \alpha^{-1}$ is $C^{\infty}$ as a mapping between open subsets of cartesian spaces.

So far the only thing we've done is that we have composed with charts on the domain, and charts on the target, and we have specifically used the product charts on the product manifold. Now, all the maps in question are between open subsets of cartesian spaces. This is what is meant by "reducing to open subsets of $\Bbb{R}^{n}$".
For ease of notation, let me define $\tilde{f_1}:=\beta_1\circ f_1\circ\alpha^{-1}$ and $\tilde{f_2}:=\beta_2\circ f_2\circ\alpha^{-1}$, and $\tilde{f}:= (\beta_1\times\beta_2)\circ f\circ \alpha^{-1}=(\tilde{f_1},\tilde{f_2})$. So, now all we have to prove to complete the theorem is show that $\tilde{f}$ is $C^{\infty}$ if and only if $\tilde{f_1}$ and $\tilde{f_2}$ are. But I'm sure you've seen this proven before when studying differential calculus in $\Bbb{R}^n$ (or Banach spaces if you've studied from Dieudonne's first book).


text:
Q: Calculating Cache Memory Hit and Miss, and Calculating Rows in Cache I am studying an old exam for an upcoming exam, and the final questions consist of what the title describes. Now, I am familiar with assembly language instructions and I somewhat know what the code means. But, what the exam question actually wants me to do is confusing. I would really appreciate if someone could explain this question.
The question:

*

*I am given a cache-memory which has room for 512 bytes and every row is 8 bytes long. The memory is direct-mapped and an "address" is 32 bits long. Also, the cache-memory is empty from the start.
After that, I get some instructions and am supposed to explain if it becomes a cache-hit or cache-miss. It should also be assumed that the instructions are all sequential and all data that is added/modified in an instruction still exists for the next instruction.

The instructions I get are

*

*movia r8, 0xBEDA12C4

*ldw r10,  0( r8 )

*ldw r11,  8( r8 )

*stw r10, 16( r8 )

*ldw r10, 24(r8)

*ldw r18, 32(r8)

Now I would really appreciate if someone could explain the details to me:

*

*The cache-memory has room for a total of 512 bytes. What is this? Is it the total memory the cache is able to store? Also, I heard from somewhere that this is how you calculate rows in cache. For example,  512 bytes of memory and every row is 16 bytes. 512/16 = 32 rows in cache. For this example 512/8 = 64 rows. Which one is it? What does this mean!?

*It also states that every row is 16 bytes long. I've seen the example with TAG, ROW, BYTE where they try to illustrate the cache. But how do I understand the 16 bytes per row? At least it doesn't seem to take part of the length on TAG, ROW, BYTE. What is this for?

*Direct-mapped cache. I understand this somewhat. It's just a big row of slots of order which are empty or not, yeah? I found some information on this here.
http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Memory/direct.html
*Updated link: https://web.archive.org/web/20150213025748/http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Memory/direct.html

*

*Now to the main part. How do I calculate for each instruction if it will be a cache miss or hit? My guess is that the first instruction ought to be a miss, since the question said that the cache memory is empty from the start. The second instruction also must be a cache miss but from this point on I am not sure how to calculate if the instruction generates a cache hit or miss. To be honest, I am not even sure what a hit would be.

I would really appreciate if someone could show me how to calculate each step and how I know whether an instruction creates a cache hit or miss. The instructions we get for calculating this are really confusing. Thank you so much!

A: Generally you have to look at it as at a separate memory space, with only 512 bytes, addressable, readable and writable as arrays 8 bytes each. If you need byte 2, the address will be 0, you read the whole array and select byte 3 from it. If you need byte 8, the address will be 1, and you select byte 0 from the array. Such small memory have one huge advantage - it is fast. It alone can store the contents of some larger memory space, only first 512 bytes. If you store something to address 1 of larger memory space, it will go to that smaller memory instead, the address will become 0 and offset 1, internally for that small amount of memory. If you access beyond that, for example, 1000, you will have to wait more. In this case it would be just memory mapped "registers" - it would be actually faster and better in some cases, than "cache" - unfortunately for some reason processor makers generally won't let you use the cache in that way (probably marketing and support reasons - to sell other products as a separate market share, with higher price).
If you add some more space to each array to store some other value, you can store a part of address there. Without hardware support you could store there virtually anything, that second part is called tag. Now if you have some address fffff000, you can read the second space (assuming that you have the commands to do so), from address 0 - for simplicity and speed you can obtain the address from the primary memory space by masking all the bits except bits 3..8 and 0-2 (which are used to obtain offset in 8 byte array), and check the tag part from that address. One bit in that tag may be used to indicate whether there is something stored there, the other bits may be used to store the part of address from main memory. If you want to save something cached there, you set the bit indicating that the array is not "empty", and assign the upper bits of the main address there, and copy the 8 bytes from the main memory. Next time, before reading something within that range in memory, you read the tag part of the smaller memory array first, then decide whether to read from slow main memory, or from that smaller but faster part (and it would be cache hit).
If you write something with an address of (+-)x512 bytes in main memory, you would have to read the already mentioned array of 8 bytes, copy it into main memory, whole 8 bytes, and write what you want into the very same cell, and then modify the address with a new value. But you would lose the previous copy of your data in the smaller memory area (but faster). If you need the previous value again (any of those 8 bytes), you would have to copy it again from main memory (cache miss).
The same goes for all other arrays of that "cache" memory. So we have a sequence of cache checking, writing, reading and copying the data to or from main memory.
That is called 1 way associativity, for 2 ways there would be one more array (same) of 512 bytes, which can store different addresses though (with the step of 512 from main memory), the tags of those 2 arrays may be checked simultaneously, and if some array has the copy of that memory range it can return it instead of reading it from main memory. Without tag checking (extra cycles for that), the "cache" is essentially a small amount of memory.


text:
Q: Are there countably many infinities? $\aleph_0$, $\aleph_1, \aleph_2$ and so on are indexed by a natural number so shouldn't there be countably many infinities?

A: After you exhaust all the $\aleph_n$, you still have $\aleph_\omega$ which is a cardinality larger than all the $\aleph_n$'s. Then you have $\aleph_{\omega+n}$, for integer $n$, and so on.
And you have many many many more cardinals. In fact, for every ordinal $\alpha$ you have cardinal $\aleph_\alpha$. Since there are uncountable ordinals, there are at least uncountably many cardinals. But in fact, the collection of cardinals does not make a set, it is a proper class.


text:
Q: How to generate human like mouse pointer movement using Fitt's Law I was trying to generate the human like mouse movement. While finding the correct model I come to know about Fitts's law.
You can read more about the law and the reason behind the mathematical model of it here. I want to generate the human like mouse pointer data given distance between source to target and width of target object.
I am not able to come up with the good model to find the radius of circle of error and position and number of circle of error explained in the below image.
Also I am planning to use Bézier curve to achieve random curves in intermediate stages.
I believe the solution of the problem contains following steps
1) Find out the time going to take for the whole interaction, (after removing some initial extra waiting time ) using Fitts's Law.
2) Based on time and distance find the number of circle of error, and using that number also find the decreasing radius of each circle. One of the possible approach is to use log function.
3) Find out position of each circle which is random but still in the intended direction. This is one of the most confusing task. There are many possibilities but there is few particular model behind where circle of errors are placed.
4) Find out the random points inside the circle but still in intended direction.
5) Pass the (Time, X,Y) triplets to MouseMove function of selenium
I am not sure how to achieve step 3,4 and 5.
Preferred language to achieve this is Java using selenium.


text:
Q: Is the null/empty set both a subset of and disjoint from every non-empty set? For any set (nonempty or otherwise) $A, \varnothing \subseteq A$.
Two sets are said to be disjoint if they contain no elements in common, so for any nonempty set $A, \varnothing$ is disjoint from $A$.
Can the null set therefore be considered BOTH a subset of and disjoint from $A$? Doesn't that contradict the definitions of these terms?

A: Going straight to the definition: $A\subseteq B$ if whenever $a\in A$ we must have that $a\in B$. Well if $A=\emptyset$ this is true for every $B$ since there is no $a\in A$. Hence $\emptyset$ is a subset of every set.
$A$ and $B$ are disjoint if $A\cap B=\emptyset$. Clearly if $B=\emptyset$ then this is true for all $A$.
It may conflict with the English definition of the words, but math is not English. Words mean different things.

A: I think that this may answer your question.
Let $A$ be an arbitrary set.
Suppose that $A\cap \varnothing\neq \varnothing$ (suppose they are not disjoint).

Then there exists $x\in \varnothing$ such that $x\notin A$, which is a contradiction since the empty set contains no elements by definition.
Now, suppose that $\varnothing \nsubseteq A$. Again, we can see that this cannot be true since this would imply that there exists some element in $\varnothing$ which is not an element of $A$.
So in particular, the empty set is a subset of every set, and also that the empty set is disjoint with every set. Almost every time you prove something regarding the empty set, the best route to go is usually to use a proof by contradiction, since working with the empty set is almost always counter intuitive.


text:
Q: Codepen menu works fine, but doesn't work on a blank page I created a CSS/JS dropdown menu I am working on in Codepen. The menu works fine in Codepen:
https://codepen.io/jabbamonkey/pen/EXNQYB
However, when I place everything onto a blank php page ... the code doesn't work:
http://tbsmb.school/_temp.php
Any idea what is going wrong?
MENU CODE:

About

Welcome

Vision

Approach

Administration

Press

Employment

Resources

Contact

Admissions

Visit Us

Enrollment

Tuition

Fine Print

FAQ

Programs

After-School

Camp

Parent-Child

Parents-to-be

Family

Support

PTO

Ways to Give

Scholarships

Calendar

JS
$('.menu li > .sub-menu').parent().click(function() {
  var submenu = $(this).children('.sub-menu');
  if ( $(submenu).is(':hidden') ) {
    $(submenu).slideDown(200);
  } else {
    $(submenu).slideUp(200);
  }
});

STYLES
.menu { vertical-align:middle; text-align:left; padding: 0 0 0 8px; margin: 0; list-style: none; position:relative; }
  .menu li { position:relative; font-size:24px; display:inline-block; padding:0; line-height:1; vertical-align:top; margin:0; }
  .menu li a { display:block; padding:32px 25px 30px 25px; margin:0; color:#282828; text-transform:uppercase; text-decoration:none; }
  /* Hover */
  .menu li:hover > a { color: #282828; background-color:#c3def1; }

/* Sub-menu */
/* .menu li:hover > ul { display: block; } */
.menu .sub-menu { display:none; }
.menu .sub-menu { list-style: none; margin: 0; padding: 0; position: absolute; top: 86px; left:0px; z-index: 99999; background-color:#87bde4; }
    .menu ul li { float: none; margin:0; padding:0; display: block; font-size: 22px; text-align: left; }
    .menu ul li a { border:0; text-transform:none;  }
    .menu ul a { padding: 22px 16px 17px 46px !important; min-width: 280px; height: auto; line-height: 1; display: block; color:#282828; }
    .menu ul a:hover { background-color:#9ac9eb; }

/* Hide Tertiary Menus */
.menu ul ul { display:none; opacity: 0; visibility: hidden; }

A: The site has not been instructed as to WHEN this code is relevant. In codepen, the code in the javascript area is assumed to run when the code is run, unless instructed otherwise.
Use this:
$(document).ready(function () {
    $('.menu li > .sub-menu').parent().click(function() {
      var submenu = $(this).children('.sub-menu');
      if ( $(submenu).is(':hidden') ) {
        $(submenu).slideDown(200);
      } else {
        $(submenu).slideUp(200);
      }
    });
});


text:
Q: Efficient way to get index of every element in array greater than some value I have a (quite large) standard C++ array of type double, with ~50,000,000 rows and 20 columns. The array is filled with random data, according to some Gaussian distribution (if that's of any use in answering this question).
I've written an algorithm to solve a problem using this array. A significant part of this algorithm's time is spent iterating, row by row (and sometimes over the same row more than once) and returning, for each row, the index of every element in that row such that the absolute value of that element exceeds some value (also of type double).
Unfortunately, the algorithm is quite slow. As it's rather large, and the problem being solved is a bit complex for simply dumping the code here on SO, I'd like to start by tacking this issue. What is the most efficient (or, at least, a more efficient way) to grab the index of every element in a row of a multidimensional array?
What I've tried:
I've tried simply iterating through each row (with an iterator), passing each value to fabs(), and using std::distance() to get the index. I then store it in an std::set() (I don't care much about how the indices are stored, unless that is a significant speed factor, so long as they are "easily accessible").
I.e.:
                for(auto it = row.begin(); it != row.end(); ++it){

                        auto &element = *it;

                        if(fabs(element) >= threshold){
                                cache.insert(std::distance(row.begin(), it));
                        }
                }

I've also tried using std::find_if, and similarly through std::range. Neither gave measurable speed improvements (admittedly, I haven't used particularly scientific benchmarks, however I'm going for a visibly noticeable improvement).
I.e. something like this:
    auto exceeds_thresh = [](double x){ return x > threshold}

    it = ranges::find_if(row, exceeds_thresh);
    while(it != end(row)){
        resuts.emplace_back(distance(begin(row), it));
        it = ranges::find_if(std::next(it), std::end(row), exceeds_thresh)
    }

Note that, by efficiency, I'm focusing on speed

Here, 11.3, 9.8, 17.5 satisfy the condition, so their indices 1,3,6 should be printed. Note that, in practice, each array is a row in a far larger array (as above), and with far greater number of elements in each row:
double row_of_array[5] = {1.4, 11.3, 4.2, 9.8, 0.1, 3.2, 17.5};
double threshold = 8;

for(auto it = row_of_array.begin(); it != row_of_array.end(); ++it){
    auto &element = *it;

    if(fabs(element) > threshold){
        std::cout << std::distance(row_of_array.begin(), it) << "\n";
    }

}

A: You can try loop unrolling
double row_of_array[]      = {1, 11, 4, 9, 0, 3, 17};
constexpr double threshold = 8;
std::vector<int> results;
results.reserve(20);
for(int i{}, e = std::ssize(row_of_array); i < e; i += 4)
{
   if(std::abs(row_of_array[i]) > threshold)
      results.push_back(i);
   if(i + 1 < e && std::abs(row_of_array[i + 1]) > threshold)
      results.push_back(i + 1);
   if(i + 2 < e && std::abs(row_of_array[i + 2]) > threshold)
      results.push_back(i + 2);
   if(i + 3 < e && std::abs(row_of_array[i + 3]) > threshold)
      results.push_back(i + 3);
}

EDIT:
or the riskier
double row_of_array[20]    = {1, 11, 4, 9, 0, 3, 17};
constexpr double threshold = 8;
std::vector<int> results;
results.reserve(20);
static_assert(std::ssize(row_of_array) % 4 == 0, "only works for mul of 4");
for(int i{}, e = std::ssize(row_of_array); i < e; i += 4)
{
   if(std::abs(row_of_array[i]) > threshold) results.push_back(i);
   if(std::abs(row_of_array[i + 1]) > threshold) results.push_back(i + 1);
   if(std::abs(row_of_array[i + 2]) > threshold) results.push_back(i + 2);
   if(std::abs(row_of_array[i + 3]) > threshold) results.push_back(i + 3);
}


text:
Q: What is the throw statement? I know that I must pass one single argument: a throwable object. But I really don't know what kind
of keyword is throw.
It is not a Class, because we don't pass the throwable object as constructor parameter, nor is an annotation, because throwis not preceded by the @ character. And so on.
So, what is exactly the throw statement?
Thanks!

A: It's a reserved keyword, see section 3.9 of the Java Language Specification.

A: throw is used to activate an Exception.
throw new Exception("This is an exception");
You can also use Inheritance and make your own type of Exceptions and throw and handle them.

A: throw is a regular java keyword, which is used to "throw" an exceptionThrowable object.
in my opinion, throw is not more magic or mysterious than break or continue....


text:
Q: How to automatically take all available space in css grid I have trouble with understanding how CSS grid rows work. Why columns expand from left to right and rows don't?

.grid {
  position: absolute;
  height: 50vh;
  width: 30vw;
  border: 1px solid black;
  top: calc(50% - 30vh);
  left: calc(50% - 15vw);
}

.keys {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

.keys>button {
  font-size: 30px;
  text-align: center;
  line-height: 30px;
  border: 1px solid black;
}

    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>
    <button>1</button>

I would want those buttons to go all the way down without giving them specific height etc.
How to achieve that easily ?

A: Your
.keys inside your
.grid is not set to expand the entire grid
 element.
You need to ensure that all divs within the grid div are set to fill the entire container in order for the children to also do so.
Adding height: 100% to your keys container will fix this.
You need to add the following code
.keys {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
  height: 100%;
}

Alternatively, you can get rid of styling in the grid  all together, and move all of the CSS inside of it to the keys element. This way, you won't need to set height, like so
.keys {
  display: grid;
  position: absolute;
  height: 50vh;
  width: 30vw;
  border: 1px solid black;
  top: calc(50% - 30vh);
  left: calc(50% - 15vw);
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

When using fr as a dimension, it will always fill a fraction of the parent container. repeat(4, 1fr) would style the element's dimensions to 25% of the parent container, whether width or height.


text:
Q: Refresh httpget Data from server in listView I get some data via httpget in a AsyncTask. This data I put into a listview.
This works fine so far. But now I want to implement that I refresh some data that changed on the server. What I am doing right now is that I reload the whole list via httpget to get all the data again but with refreshed/changed data. But I want to refresh only the changed data of the database in the listview so it does not take so long. How could I achieve this? Thanks for your help.


text:
Q: c# Mvc 3 Tempdata Dictionary? In my mvc3 project, I keep Dictionary in Tempdata Dictionary.
TempData[ViewDataKeys.ItemsAdd] = new Dictionary<int, int>();

When Ajax request i add items to TempData[ViewDataKeys.ItemsAdd].
It is updated but when i remove items from TempData[ViewDataKeys.ItemsAdd] it is not updated.
after remove one items from TempData[ViewDataKeys.ItemsAdd] , it is null.
 private void RemoveFrom(int Uid)
    {
        if (TempData[ViewDataKeys.ItemsAdd] == null)
        {
            TempData[ViewDataKeys.ItemsAdd] = new Dictionary<int, int>();
        }
        var a= (Dictionary<int,int>)TempData[ViewDataKeys.ItemsAdd];
        a.Remove(Uid);
        TempData[ViewDataKeys.ItemsAdd] = a;
    }

        private void AddTo(int Uid)
    {
        if (TempData[ViewDataKeys.ItemsAdd] == null)
        {
            TempData[ViewDataKeys.ItemsAdd] = new Dictionary<int,int>();
        }

        var a= (Dictionary<int,int>)TempData[ViewDataKeys.ItemsAdd];
        a.Add(Uid, Uid);
        TempData[ViewDataKeys.ItemsAdd] = a;
    }

A: Whenever TempData is read the value it contains is returned and then it's removed from TempData. TempData actually uses the standard Session object but the difference is when you read a value the TempData object is removed from the session.
Generally it's only to be used for redirects or something you need to persist to the next page load.


text:
Q: Python list to .csv I create a list like this my_list=[('a','b',1,2),('a1,'b',1,2)]
i want it to dump to a .csv file with headers
my_df = pd.DataFrame(dis)
my_df.to_csv('E:\list.csv' ,header=['col1','col2','col3','col4'],index=False)

but after running my code, The csv file does not have any headers,but instead of it it is showing indexes
output:
 0 1 2 3
 a b 1 2
a1 b 1 2

A: You can define columns names in DataFrame constructor:
my_df = pd.DataFrame(dis, columns=['col1','col2','col3','col4'])
my_df.to_csv('E:\list.csv', index=False)

EDIT:
In last version of pandas, 0.22.0 your solution also working very nice, so the best is upgrade pandas:
my_list=[('a','b',1,2),('a1','b',1,2)]
my_df = pd.DataFrame(my_list)
print (my_df)
    0  1  2  3
0   a  b  1  2
1  a1  b  1  2

print(my_df.to_csv(header=['col1','col2','col3','col4'],index=False))
col1,col2,col3,col4
a,b,1,2
a1,b,1,2

EDIT: Thanks Dawid Dave Kosiński for another solution:
import csv
my_list=[('a','b',1,2),('a1','b',1,2)]
cols = ['col1','col2','col3','col4']

with open('list.csv','w') as out:
    csv_out = csv.writer(out)
    csv_out.writerow(cols)
    for row in my_list:
        csv_out.writerow(row)


text:
Q: Redirect stdout and stderr separately over a socket connection I am trying to run a script on the other side of a unix-socket connection. For this I am trying to use socat. The script is
#!/bin/bash
read MESSAGE1
echo "PID: $$"
echo "$MESSAGE1"
sleep 2
read MESSAGE2
echo "$MESSAGE2" 1>&2

As the listener for socat I have
socat unix-listen:my_socket,fork exec:./getmsg.sh,stderr

as the client I use:
echo $'message 1\nmessage 2\n' | socat -,ignoreeof unix:my_socket 2> stderr.txt

and I get the output
PID: 57248
message 1
message 2

whereas the file stderr.txt is empty.
My expectation however was that

*

*stdout from the script on the listener side would be piped to stdout on the client and

*stderr on the listener side to stderr on the client side.

That is the file stderr.txt should have had the content message 2 instead of being empty.
Any idea on how I can achieve it that stdout and stderr are transferred separately and not combined?
Thanks

A: If the input and output are just text with reasonably finite line lengths, then you can easily write muxing and demuxing commands in pure Bash.
The only issue is how socat (mis)handles stderr; it basically either forces it to be the same file as stdout or ignores it completely. At which point it is better to use one's own file descriptor convention in the handler script, with unusual file descriptors that don't conflict with 0, 1 or 2.
Let's pick 11 for stdout and 12 for stderr, for example. For stdin we can just keep using 0 as usual.
getmsg.sh
#!/bin/bash
set -e -o pipefail

read message
echo "PID: $$"  1>&11   # to stdout
echo "$message" 1>&11   # to stdout
sleep 2
read message
echo "$message" 1>&12   # to stderr

mux.sh
#!/bin/bash

"$@" \
11> >(while read line; do printf '%s\n' "stdout: ${line}"; done) \
12> >(while read line; do printf '%s\n' "stderr: ${line}"; done)

demux.sh
#!/bin/bash
set -e -o pipefail

declare -ri stdout="${1:-1}"
declare -ri stderr="${2:-2}"
while IFS= read -r line; do
  if [[ "$line" = 'stderr: '* ]]; then
    printf '%s\n' "${line#stderr: }" 1>&"$((stderr))"
  elif [[ "$line" = 'stdout: '* ]]; then
    printf '%s\n' "${line#stdout: }" 1>&"$((stdout))"
  else
    exit 3  # report malformed stream
  fi
done

A few examples
#!/bin/bash
set -e -o pipefail

socat unix-listen:my_socket,fork exec:'./mux.sh ./getmsg.sh' &

declare -ir server_pid="$!"
trap 'kill "$((server_pid))"
      wait -n "$((server_pid))" || :' EXIT

until [[ -S my_socket ]]; do :; done  # ugly

echo '================= raw data from the socket ================='
echo $'message 1\nmessage 2\n' | socat -,ignoreeof unix:my_socket

echo '================= normal mode of operation ================='
echo $'message 1\nmessage 2\n' | socat -,ignoreeof unix:my_socket \
| ./demux.sh

echo '================= demux / mux test for fun ================='
echo $'message 1\nmessage 2\n' | socat -,ignoreeof unix:my_socket \
| ./mux.sh ./demux.sh 11 12

A:
My expectation however

There is only one socket and via one socket one stream of data can be sent, not two. You can't send stdout and stderr (two streams) via one handle (I mean, without like inter-mixing them, i.e. without loosing information what data is from which stream). Also see explanation of stderr flag with exec in man socat and see man dup. Both stderr and stdout of the script redirect to the same output.
The expectation would be that stderr.txt is empty, because socat does not write anything to stderr.

how I can achieve it that stdout and stderr are transferred separately and not combined?

Use two sockets separately for each stream.
Transfer messages using a protocol that would differentiate two streams. For example a simple line-based protocol that prefixes the messages:
# script.sh
echo "stdout: this is stdout"
echo "stderr: this is stderr"

# client
... | socat ... | tee >(sed -n 's/stderr: //p' >&2) | sed -n 's/stdout: //p'


text:
Q: How to pass a go pointer as wasm context data? I'm looking at wasmer go-ext-wasm example code /go-ext-wasm/wasmer/test/imports.go learning about setting context data. I want to pass a pointer as contextData, what's the best way to do this?
//export sum
func sum(context unsafe.Pointer, x int32, y int32) int32 {
    instanceContext := wasm.IntoInstanceContext(context)
    t := *(*int)(instanceContext.Data())
    log.Print("t: ", t)
    return x + y
}

func testInstanceImport(t *testing.T) {
    imports, err := wasm.NewImports().Namespace("env").Append("sum", sum, C.sum)
    assert.NoError(t, err)

    instance, err := wasm.NewInstanceWithImports(getImportedFunctionBytes("examples", "imported_function.wasm"), imports)
    defer instance.Close()
    assert.NoError(t, err)

    bar := int(2)
    barPtr := &bar

    data := unsafe.Pointer(&bar)
    instance.SetContextData(data)
    log.Printf("bar %v, barPtr %v", bar, barPtr)
    add1, exists := instance.Exports["add1"]
    assert.Equal(t, true, exists)

    result, err := add1(1, 2)
    log.Print("Result: ", result)
    assert.Equal(t, wasm.I32(4), result)
    assert.NoError(t, err)
}

Which gives me the expected value of 2 for context in the sum function.  However when I change data := unsafe.Pointer(&bar) to data := unsafe.Pointer(&barPtr)  I get a: runtime error: cgo argument has Go pointer to Go pointer error.
It works when I run it with GODEBUG=cgocheck=0  Should I be concerned running with this flag?  Is what I'm trying to do a bad idea?  I have a struct that contains a pointer that I need to pass as contextData, is using the GODEBUG=cgocheck=0 a bad idea?


text:
Q: Cannot execute SQL insert command using Python Dictionary as column value I am utilizing Pyspark in Databricks including inserting parametrized values into a SQL Server table through a SQL command.
Inserting parameters into SQL command (Pyspark):
sql = "INSERT INTO dbo.Validation VALUES ('{}','{}','{}','{}')".format(app,date,anomaly,value)

The SQL Server table has the following columns:
app = [varchar](255)
date [date]
anomaly= [varchar](255)
value = [nvarchar](max)

Dictionary as shown below:
value = {'pt_PT.UTF-8': [88], 'lt_LT.UTF-8': [24], 'fi_FI.UTF-8': [4], 'fr_BE.UTF-8': [4], 'nl_NL.UTF-8': [4]}

Printed SQL command:
INSERT INTO dbo.Validation VALUES ('TestApp','2020-05-06','LanguageAnomaly', '{'pt_PT.UTF-8': [88], 'lt_LT.UTF-8': [24], 'fi_FI.UTF-8': [4], 'fr_BE.UTF-8': [4], 'nl_NL.UTF-8': [4]}')

Error when executing SQL command:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near
  'pt_PT'.

The issue I am encountering seems to be related to inserting the dictionary parameter "value". This maybe related to the apostrophes within the dictionary keys which the code cannot properly parse as a whole string.
How can I resolve this? This seems to work find if the dictionary key is a number value/int without quotes(').
Thanks.

A: Your problem is with quotes from dictionary in your SQL insert statement, you need to escape them by doubling them up:
sql = "INSERT INTO dbo.Validation VALUES ('{}','{}','{}','{}')".format(app,date,anomaly,str(value).replace("'", "''"))