text:
Q: How to hide "Customer matched zone ****" notifications on WooCommerce? When woocommerce debug mode is turned on, on the cart page and checkout page, there appears a notification says "Customer matched zone ***".
Is there any way that makes woocommerce not show this message with debug mode enabled?

A: As per my knowledge, you can not do this by using any WooCommerce action/filter but you may do this by using jQuery as shown below:
jQuery( ".woocommerce-message" ).each(function( index ) {
    let checkText = jQuery(this).text();
    if (checkText.indexOf("Customer matched zone") != -1) {
        jQuery(this).css("display", "none");
    }
});

A: I think you can set "woocommerce_shipping_debug_mode" option value to "no".


text:
Q: Does the matrix exponential preserve the positive-semi-definite ordering? Suppose $A$, $B$, are symmetric, real valued matrices and $B-A$ is positive-semidefinite, i.e. $A≼B$. Does that imply $e^A ≼ e^B$? Would love some intuition here.
I know for instance that $A≼cI \iff e^A ≼ e^cI$ and also for diagonal $A$ and $B$ the inequality is easy to show, but I'm not convinced that it translates into the general case.

A: To supplement Robert's counterexample, let me mention below some interesting facts about the matrix exponential, along with what may be regarded as the "correct" way of obtaining matrix exponential like operator inequalities.
Assume throughout that $A \ge B$ (in Löwner order).
The map $X \mapsto X^r$ for $0 \le r \le 1$ is operator monotone, i.e., $A^r \ge B^r$. This result is called Löwner-Heinz inequality (it was apparently originally discovered by Löwner). Now using
\begin{equation*}
  \lim_{r\to 0} \frac{X^r-I}{r} = \log X,
\end{equation*}
we can conclude monotonicity of $\log X$, so that $\log A \ge \log B$.
A quick experiment reveals that $A^2 \not\ge B^2$ in general (in fact $X^r$ for $r > 1$ is not monotone), which severely diminishes hopes of $e^X$ being monotone.
However, though $e^A \not\ge e^B$, T. Ando (On some operator inequalities, Math. Ann., 1987) showed that
\begin{equation*}
  e^{-tA} \# e^{tB} \le I,\qquad\forall t \ge 0.
\end{equation*}
Here, $X \# Y := X^{1/2}(X^{-1/2}YX^{-1/2})^{1/2}X^{1/2}$ denotes the matrix geometric mean (so basically, operator inequalities go along better with the  "right" notion of a geometric mean)

Additional remarks
Although $A^2 \ge B^2$ does not hold, it turns out that a slightly modified version $(BA^2B)^{1/2} \ge B^2$ does hold, as does $A^2 \ge (AB^2A)^{1/2}$. These inequalities are special cases of a family of such results proved by T. Furuta, and these are called Furuta inequalities, for example, we have
\begin{equation*}
 (B^rA^sB^r)^{1/q} \ge (B^{s+2r})^{1/q},\quad 0 \le s \le 1, r \ge 0, q \ge 1.
\end{equation*}

A: For example, try $$A = \pmatrix{1 & 0\cr 0 & 0\cr},\ B = A + t C\ \text{where}\ C = \pmatrix{1 & 1\cr 1 & 1\cr}$$
where $t>0$ is small.  Then $A  ≼ B$ but
$$ e^B - e^A = t \pmatrix{e   & e-1   \cr
e-1   & 1 \cr} + O(t^2)$$
so that $$ \det(e^B - e^A) = (e - (e-1)^2) t^2 + O(t^3) < 0$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: The proportion of points for ggplot2 in R I have a list of data with the address and the frequency of certain incidents happened in those addresses(samples as below:)
     Address                        Frequency
1155 6th Ave, New York, NY 10036         5
241 5th Ave, New York, NY 10016          7
171 W 57th St, New York, NY 10019        5
398-342 W 34th St,New York, NY 10001     10

I want plot those address in the map and using the frequency to determine the size of those points, here is my code and the result I got:
Code:
library(readxl)
library(ggmap)
library(ggplot2)

input <- read_excel("Add.xlsx")
geocodes <- geocode(as.character(input$Address), source = 'dsk')
mydata <- data.frame(input, geocodes)

mymap<- get_map(location = "Midtown, New York, NY", zoom = 14,
                maptype = "roadmap",scale = 2)

ggmap(mymap) +
    geom_point(data = mydata,
               aes(x = lon, y = lat, size = Frequency),
               color = "Red")

Result:

However I feel the points for my addresses with smallest frequency are so small, well I know R has adjusted automatically, but is there anyway I can adjust the proportion and make them bigger? so I can present them better.


text:
Q: Is there a way to run GCP workflows locally? Recently I started working with GCP workflows, and functions. We are using serverless framework for the functions and we can run them in our on computers with the command serverless invoke local --function <function_name> so we don't have to spend cloud executions.
What I'm looking now is if there is a way to do the same thing with GCP workflows, to run them in our own computers instead of invoking them inside the cloud.
I already read the resources from google and from many different articles but I still not find the trick (if it actually exists)

A: Today, there is no emulator for Cloud Workflows. But if you can afford to deploy your cloud functions on GCP, Cloud workflows has a generous free tier: 5000 steps for free


text:
Q: Disable Sencha script loader cache busting but only while developing/debugging I'm working with ExtJS 4.x and Sencha Architect 2.2 but this should be relevant to later versions and any application that uses the Ext.Loader class to dynamically load scripts, including Sencha Touch.
By default Ext.Loader adds a ?_dc=... cache busting parameter to make sure that the latest version of each script is loaded into the browser. When deploying to a production or beta-test environment this is a good thing as it ensures the user/tester gets the latest script each time you deploy and update, but for a development environment this is not really necessary because developers know to use browser techniques like ctrl+F5 to force a reload of all the scripts. What's more the cache busting gets in the way of debugging as breakpoints etc are lost whenever you reload the app in the browser.
Cache busting is disabled by setting disableCaching to false in the Ext.Loader configuration. For example:
Ext.Loader.setConfig({
    enabled: true,
    disableCaching: false
});

In this snippet the dynamic loading is enabled and cache busting is disabled. There are however other config options as described in the API docs here.
In Sencha Architect this code is generated for you in app.js and you can't edit it. Architect has a "Project Setting" to enable caching but in version 2.2 it doesn't work for ExtJS 4. I assume it works fine in later versions but it seems to be all-or-nothing so you have to remember to switch it off and rebuild for deploying to a non-dev environment.
What I want is to be able to:

*

*Workaround the settings bug in version 2.2 of Architect

*Enable cache busting in "production" but not in dev without having to
rebuild my app

A: Ext.Loader.setConfig() can be called multiple times with different settings and the settings are "merged" together. For me this was unclear in the documentation but fortunately it was more obvious in the source code.
The source code also shows that there is an undocumented form of setConfig where it takes a name and value instead of a config object, but as it's undocumented I'll stick with passing in an object like this:
Ext.Loader.setConfig({disableCaching: false});

Knowing that this won't affect other Ext.Loader configs that are set elsewhere in your app you can put this code anywhere after Ext is loaded, but before the Ext.onReady() is called. In Sencha Architect this can be achieved by putting it in a "JS Resource" as described here.
That solves the first part of my question, but what I also want is to be able to turn cache busting off without rebuilding, so I modified the code to check for a "debug" URL parameter like this:
if (Ext.Object.fromQueryString(document.location.search).debug) {
    Ext.Loader.setConfig({disableCaching: false});
}

Now when I want to debug my app I can use a URL that looks like:
http://myhost/.../app.html?debug=true

and the cache busting is turned off. I just omit the debug parameter for it to be turned back on.

A: If you are using Sencha Command you can wrap the line to disable cache busting in a debug block, somewhere at the beginning of your app.js
// <debug>
Ext.Loader.setConfig({disableCaching: true});
// </debug>

Now the code will be removed when built for production. If you wanted (or needed) to, you can also configure the build properties for the testing builds to keep the debug code as well.


text:
Q: Dependency Injection for Nest JS Interceptor is Undefined I have created an interceptor as shown below that I wish to use globally. I added the interceptor to my module and set it up so that nest js should handle the DI for me per NestJS Docs, however when I make a request to my service, I get an error indicating Cannot read property log of undefined so it appears that the DI is not being taken care of by NestJS.
Interceptor Code:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoggingService } from './logging.service';

@Injectable()
export class AuthInterceptor implements NestInterceptor {
  constructor(private readonly loggingService: LoggingService) { }
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next
      .handle()
      .pipe(
        map((response) => {
          this.loggingService.log('Responded successfully');
          return response;
        })
      );
  }
}

Interceptor Module:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}

My app.module.ts at the root of my application imports the AuthInterceptorModule. I am assuming I am messing something up but it is not clear to me how to fix this DI issue.

A: I was able to resolve this one on my own after finding that my LoggingService relied on another dependency that was request scoped. Since there was a request scoped dependency in my interceptor, this meant that my interceptor also had to be request scoped.
The change to the code was simple and only required that I change the AuthInterceptorModule from:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}

to
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR, Scope } from '@nestjs/core';
import { AuthInterceptor } from './auth.interceptor';
import { LoggingService } from './logging.service';

@Module({
  providers: [
    LoggingService,
    {
      provide: APP_INTERCEPTOR,
      scope: Scope.REQUEST,
      useClass: AuthInterceptor,
    },
  ],
})
export class AuthInterceptorModule {}


text:
Q: Submit form with jquery, validate before submit what im trying to do is submit a form with jquery, example submit form to www.mywebsite.com/submit/ and to get the data from there and put on div, but before to submit i need to validate if the input values is correct or not ...
This is my html form:
     <form id="Submit_Video" method="get" action="submit/">
      <input id="Title" name="Title" type="text" value="Title?"  onfocus="if(value=='Title?')value='';" onblur="if(value=='')value='Title?';" />

      <input id="Weburl" name="Weburl" type="text" value="http://" />

      <select id="Category" name="Category">
       <option value='1'>Value 1</option>
       <option value='2'>Value 2</option>
       <option value='3'>Value 3</option>
       <option value='4'>Value 4</option>
      </select>
      <input type="submit" id="vsubmit" class="input2" value="Submit" />
     </form>

I put my code here:
http://jsfiddle.net/BxZCt/
The code what i have right now the problem is when you press submit he don't check if its correct the input values or not ... hope someone can help me to show me how i can make the output of www.mywebsite.com/submit/ to be on ID video_submit_response

A: You had to bind onsumbit function, that will check the inputs for right value. Also you can validate url with HTML5 setting type to this input as type="url"

A: You can use HTML5 validators with a required attribute, a pattern attribute (that take a regex) and set the type of your input to url..
The HTML5 validators are not compatible FOR IE6 to IE9 (include).
Another solution is to implement the onsubmit listener on your form to do the validation manually ...
If you need examples ask it.
Hope it helps.


text:
Q: I need help receiving the data from an api every min (looping it) Im trying to loop the part fetching the reference from the api, there really isn't an error but i couldn't find the correct way to loop it and needed help
pastebin: https://paste-bin.xyz/46617 (sorry couldn't paste the code here idk why)
I just need help looping the part fetching info and i want it to have the value of gameType and Mode form the api every x seconds


text:
Q: Search wikipedia article and retrieve description from xml via PHP I am trying to retrieve the content of searched wikipedia article content to my page. Here is my $url Pink Floyd and my code -
$curl = curl_init();
            curl_setopt( $curl, CURLOPT_HTTPHEADER, array( "Cache-Control: max-age=0",
                                                         "Connection: keep-alive",
                                                         "Keep-Alive: 300",
                                                         "Accept-Charset: ISO-8859-1,utf-8",
                                                         "Accept-Language: $wikibox_options[language]",
                                                         "Pragma: " ) );
            curl_setopt( $curl, CURLOPT_URL, $url );
            curl_setopt( $curl, CURLOPT_USERAGENT, WIKIBOX_AGENT );
            curl_setopt( $curl, CURLOPT_ENCODING, 'gzip,deflate' );
            curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 120 );
            curl_setopt( $curl, CURLOPT_TIMEOUT, 120 );
            curl_setopt( $curl, CURLOPT_MAXREDIRS, 5 );
            if ( $post ) {
                curl_setopt ( $curl, CURLOPT_POST, 1 );
                curl_setopt ( $curl, CURLOPT_POSTFIELDS, http_build_query( $post_content ) );
            }
            $result = curl_exec( $curl );
            curl_close( $curl );

But $result print nothing. Thanks in advance.

A: You could do this instead
<?php
$result = file_get_contents('https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Pink_Floyd');
 echo $result;
?>


text:
Q: Create azure website programatically in C# I want to create/update the websites/cloud services in Azure in C#. My objective is to deploy the website/cloud service in Azure without any user intervention.
Can anyone please help me to resolve below queries?

*

*Can we manage Azure websites/cloud services using C# code? If yes then how (any library/api/nuget package)?

*If it is not possible in C#, then what are other options to achieve this? I read WebDeploy(MsDeploy), powershell can do this work but I am not sure which one is best in this scenario and how to use them.

A: This completely depends on your scenario. If you have got a system to run your powershell script from, this might be a good option (https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/) You could also use the cross platform command line tools to script your deployment / web app creation. There are different other options, especially for continous deployment to a web app. You can for example connect your github repo to an existing web app and deploy from that repository.
The C# library you were looking for should be this one:
https://github.com/Azure/azure-sdk-for-net/tree/master/src/ResourceManagement/WebSite


text:
Q: Makefile - wildcard and recipe build I have the following makefile
# See gcc/clang manual to understand all flags
CFLAGS += -std=c99 # Define which version of the C standard to use
CFLAGS += -Wall # Enable the 'all' set of warnings
CFLAGS += -Werror # Treat all warnings as error
CFLAGS += -Wshadow # Warn when shadowing variables
CFLAGS += -Wextra # Enable additional warnings
CFLAGS += -O2 -D_FORTIFY_SOURCE=2 # Add canary code, i.e. detect buffer overflows
CFLAGS += -fstack-protector-all # Add canary code to detect stack smashing

# We have no libraries to link against except libc, but we want to keep
# the symbols for debugging
LDFLAGS = -rdynamic

# external libs
# par défaut les chemins classiques

LDFLAGS += -I$(HOME)/local/include
LDFLAGS += -L$(HOME)/local/lib

# Default compiler
CC=gcc

# folders
SOURCE_FOLDER=src
TESTS_FOLDER=tests
PAQUET_FOLDER=paquet
SEND_RECEIVE_DATA_FOLDER=sendAndReceiveData
CLIENT_FOLDER=client
SERVER_FOLDER=server

# folder of sources
PAQUET_FULL_PATH=$(SOURCE_FOLDER)/$(PAQUET_FOLDER)
SEND_RECEIVE_DATA_FULL_PATH=$(SOURCE_FOLDER)/$(SEND_RECEIVE_DATA_FOLDER)
CLIENT_FULL_PATH=$(SOURCE_FOLDER)/$(CLIENT_FOLDER)
SERVER_FULL_PATH=$(SOURCE_FOLDER)/$(SERVER_FOLDER)

# sources files
# On prend tout
PACKET_SOURCES = $(wildcard $(PAQUET_FULL_PATH)/*.c)
SEND_RECEIVE_DATA_SOURCES = $(wildcard $(SEND_RECEIVE_DATA_FULL_PATH)/*.c)
CLIENT_SOURCES = $(wildcard $(CLIENT_FULL_PATH)/*.c)
SERVER_SOURCES = $(wildcard $(SERVER_FULL_PATH)/*.c)

# objects

PACKET_OBJECTS=$(PACKET_SOURCES:.c=.o)
SEND_RECEIVE_DATA_OBJECTS=$(SEND_RECEIVE_DATA_SOURCES:.c=.o)
CLIENT_OBJECTS=$(CLIENT_SOURCES:.c=.o)
SERVER_OBJECTS=$(SERVER_SOURCES:.c=.o)

# another things

# Default target
all: clean server client

client: $(CLIENT_OBJECTS) $(PACKET_OBJECTS); \
        $(CC) $(CFLAGS) $(CLIENT_OBJECTS) $(LDFLAGS);

server: $(SERVER_OBJECTS) $(PACKET_OBJECTS); \
        $(CC) $(CFLAGS) $(SERVER_OBJECTS) $(LDFLAGS);

$(PACKET_OBJECTS): $(PACKET_OBJECTS); \
        $(CC) $(CFLAGS) -lz $(PACKET_OBJECT) $(LDFLAGS);

tests: $(PACKET_OBJECTS) $(TESTS_OBJECTS); \
        $(CC) $(CFLAGS) -lcunit $(LDFLAGS);

.PHONY: clean

clean:
    @rm -f *.o

I got this message :

make: Circular src/paquet/packet_implem.o <-
  src/paquet/packet_implem.o dependency dropped. \
                  gcc -std=c99  -Wall  -Werror  -Wshadow  -Wextra  -O2 -D_FORTIFY_SOURCE=2  -fstack-protector-all  -lz  -rdynamic -I/home/jy95/local/include -L/home/jy95/local/lib; /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In
  function _start': (.text+0x20): undefined reference tomain'
  collect2: error: ld returned 1 exit status Makefile:71: recipe for
  target 'src/paquet/packet_implem.o' failed make: ***
  [src/paquet/packet_implem.o] Error 1

What I want :
1) Build the dependancies (PACKET_SOURCES) and (SEND_RECEIVE_DATA_SOURCES)
2) Build the client and the server with the dependancies from step 1
3) The executable "client" will be at the root of the folder.
How can I correct my errors ?

A: Use -c to generate objects without trying to make an executable, that way you don't need a main
$(PACKET_OBJECTS): $(PACKET_OBJECTS); \
        $(CC) -c $(CFLAGS) -lz $(PACKET_OBJECT) $(LDFLAGS);

I think you might also need a rule like this for your SERVER_OBJECTS
.c.o:
        $(CC) -c $(CFLAGS) -lz $< -o $@

A: The problem occurs in this rule:
$(PACKET_OBJECTS): $(PACKET_OBJECTS); \
        $(CC) $(CFLAGS) -lz $(PACKET_OBJECT) $(LDFLAGS);

That says that every target in the expansion of $(PACKET_OBJECTS) depends on  every target in the expansion of $(PACKET_OBJECTS).  That gives a great many dependency cycles, and in particular it gives you one-element cycles of object files depending on themselves.
In fact, this rule is problematic in several other ways:

*

*the recipe does not, in fact, create any of the rule's designated targets

*instead, it attempts to link the object files (see next) together into an executable, assigning the default name to the result (perhaps a.out).

*The recipe references an undefined variable $(PACKET_OBJECT).  I suppose that this is probably a misspelling of $(PACKET_OBJECTS).  If instead you mean current target among those given in $(PACKET_OBJECTS), then that would be spelled $@.

*not only do the object files certainly not each have themselves as prerequisites, they also do not have each other as prerequisites.  The dependencies for each object should be their corresponding sources.

*If you indeed mean for this rule to be used to build your object files then the recipe does not need to specify libraries to link in (e.g. -lz), and probably should not do so.

Chances are reasonably good that you could simply delete that rule altogether and thereby be better off.  You might want to add -lz to your LDFLAGS; otherwise it would just be lost.
Additionally,

*

*You probably want to move the -I$(HOME)/local/include option: it does not belong in LDFLAGS, and will not serve its purpose there.  If you need it, then put it instead in your CPPFLAGS, or maybe in CFLAGS or even INCLUDES.

*Your various rules that build executable targets should provide options that specify the name of the target to build.  You can spell that as "-o $@",

*It is unconventional to include your clean target as a prerequisite of all.  It will always rebuild everything from scratch if you run make without specifying a target.  Most people prefer to do that only on demand.

*Your all target does not build a target named "all", so it, too, should be declared .PHONY.
Very likely there's more, but I'll leave that for you to sort out.


text:
Q: Selenium - arrow Down and Enter not possible? i try to automate a site with the below code -
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time

link = "https://www.bcassessment.ca/"
options = Options()
options.add_argument("start-maximized")
options.add_argument('window-size=1920x1080')
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
srv=Service(ChromeDriverManager().install())
driver = webdriver.Chrome (service=srv, options=options)
waitWebDriver = WebDriverWait (driver, 10)
driver.get (link)
waitWebDriver.until(EC.element_to_be_clickable( \
  (By.XPATH, "//input[@id= 'rsbSearch']"))).send_keys("106 Maple")
driver.find_element(By.XPATH, "//input[@id= 'rsbSearch']").send_keys(Keys.ARROW_DOWN)
driver.find_element(By.XPATH, "//input[@id= 'rsbSearch']").send_keys(Keys.ENTER)
time.sleep(500)

The textinput to the field works fine - but then its necessary to press the Down-Key and afterwards the Return-Key to get the search-result. But this is not working with Selenium.
Why is that and what is necessary to do so i get to the search result (eg. press down and enter)?

A: I see manually after entering the searching string you need to click on the search input, then to press down arrow, wait until suggested result is presented, then press down key again and then press the Enter key.
Also, I see
So please try this, it should work
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time

link = "https://www.bcassessment.ca/"
options = Options()
options.add_argument("start-maximized")
options.add_argument('window-size=1920x1080')
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
srv=Service(ChromeDriverManager().install())
driver = webdriver.Chrome (service=srv, options=options)
waitWebDriver = WebDriverWait (driver, 10)
driver.get (link)
waitWebDriver.until(EC.element_to_be_clickable( \
  (By.XPATH, "//input[@id= 'rsbSearch']"))).send_keys("106 Maple")
searc_input = driver.find_element(By.XPATH, "//input[@id= 'rsbSearch']")
searc_input.click()
time.sleep(0.1)
searc_input.send_keys(Keys.ARROW_DOWN)
time.sleep(0.4)
searc_input.send_keys(Keys.ARROW_DOWN)
time.sleep(0.4)
searc_input.send_keys(Keys.ENTER)


text:
Q: Calling servlet's init and destroy method withing service method I was reading about servlet's life-cycle and got this doubt. Can we call servlet's init and destroy method inside overridden servlet's service method like calling any other java method? Will this affect container's actual flow ?

A: You certainly can call init and destroy from the service method. Depending on what those methods do, i.e. if they actually destroy the servlet, this is probably unwise.
Say, for example, I have a request that comes in and encounters a problem. I think the easiest way to solve this is to call destroy and then init to "restart" the servlet.
My restart takes non-zero time, another request comes in during that time. This request encounters a problem. It also decides to restart the servlet.
You see where this is going...
I would recommend against fiddling with the servlet lifecycle methods and leave that to the container. If you must call those methods then be very wary of thread synchronisation.
As far as affecting the "container's actual flow" - the container has no way of knowing you called the method and that is why requests keep flooding in. The container will be obliviuous to you calling those methods.

A: Yes, you can call them, but there is no need to do this. This method used by Servlet containers.
You should use this method if you need to for example initialize internal state.

A: Methods init() and destroy() defaulty are empty and you should override them to take/release resources (for example).
You can call them and it will not affect servlet lifecycle.

A: you can call those methods no problem.But they are life cycle methods.Whatever the operations performed by the container that is servlet class instantiation and destroy will not happen at that time.
Whenever called by the container only those operations will happen(object instantiation and destroy)


text:
Q: How to bulk replace  element to ? I need to change all images of a static website and provide WebP support. So every file-name.jpg file has file-name.webp alternative in the same folder.
I want to turn every

into
<picture>
  <source srcset="file-name.webp" type="image/webp">

</picture>

I don't want to manually change all the photos by going through all the pages one by one. Is there a way to bulk replace all existing  elements while keeping all class and attributes?

A: I wrote a simple python script that does this work for you (I wrote it from my mobile, if you see some errors tell me).
import re, os

files = os.listdir()
for file in files:
    if file.endswith('html'):
        pattern = r''
        with open(file, 'r') as f:
            html = f.read()

        finds = re.findall(pattern, html)

        for f in finds:
            orCode = '
            newCode = '<picture>\n <source srcset="' + f[0].split('.')[0] + '.webp" type="image/webp">\n\n</picture>'
            html = html.replace(orCode, newCode)

        with open(file, 'w') as f:
            f.write(html)


text:
Q: Retrieve the no. of followers of those persons who retweeted a tweet using Rails Input: Any 2 tweets of a particular twitter handle.
Output: Find out who retweeted them. Then display 10 retweeters in the descending order of their no. of followers.
I have to build a UI for the same in Rails.
Any help, how should I start off with?

A: Not sure exactly what are you asking in the context of Rails, but this might help you get started.
Twitter API Documentation for retweeted_by
It accepts the ID of a tweet and returns a collection of retweeters. You can set the limit of retweeters as well by passing in some optional parameters.  More details in the documentation.


text:
Q: Swift Combine making serial sequence in order Here is the simple playground code that shows the two subscriptions in reverse order. How can I modify code so it will always print out 555? Currently it prints randomly 0 or 555 since operations are async. Please bear in mind that it is a concept, not an actual problem to solve, so putting all into one sink will not be a solution. Thanks
import Combine

class Foo {

    let subject = PassthroughSubject<Void, Never>()
    var myProperty = 0

    var bag = Set<AnyCancellable>()

    init() {
        subject
            .sink { _ in print(self.myProperty) }
            .store(in: &bag)

        subject
            .map { _ in 555 }
            .assign(to: \.myProperty, on: self)
            .store(in: &bag)

        subject.send()
    }
}

let testClass = Foo()

A: PassthroughSubject makes no guarantees about the order in which it will send values to its subscribers. You can't force an order, and the order could change in a future version of Combine.
One solution to store myProperty in its own subject, and subscribe to that subject to get the +555 values:
import Combine

class Foo {

    let subject = PassthroughSubject<Void, Never>()
    private var _myProperty = CurrentValueSubject<Int, Never>(0)
    var myProperty: Int { _myProperty.value }

    var bag = Set<AnyCancellable>()

    init() {
        _myProperty
            .sink { _ in print(self.myProperty) }
            .store(in: &bag)

        subject
            .map { _ in 555 }
            .assign(to: \.value, on: _myProperty)
            .store(in: &bag)

        subject.send()
    }
}

let testClass = Foo()


text:
Q: Sparql, how to merge different results I am trying to create a SPARQL query to find all the people that Jim knows, then to find which people the knowers of Jim know and then the same thing like a chain.
For example I have that:
Jim knows Clare and Antoine
Clare knows Jim and David
Antoine knows David and Clare
David knows Clare

So the results are then:
result1: Clare, Antoine
result2: Jim, David, David, Clare
result3: Clare, David, Clare, Clare, Jim, David

More or less I have made something like a tree.
What I want is to merge result1, result2 and result3 into result4. So the result4 will be:
result4: clare, antoine, jim, david, david, clare, clare, david, clare, clare, jim, david.

and then to use DISTINCT to remove the duplicates. How can I achieve this please?
SELECT  ?Result1 ?Result2 ?Result3
WHERE{
    {
        base:Knows  dc:Names        _:BN1 .
        _:BN1       dc:FName        "Jim";
                dc:KnownFName           ?Result1 .
    }
    .
    {
        base:Knows  dc:Names        _:BN2 .
        _:BN2       dc:FName        ?Result1;
                dc:KnownFName           ?Result2 .
    }
    .
    {
        base:Knows  dc:Names        _:BN3 .
        _:BN3       dc:FName        ?Result2;
                dc:KnownFName           ?Result3 .
    }
}

A: Let's say your example is represented as follows:
<http://example.com/person/1> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .
<http://example.com/person/1> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/3> .
<http://example.com/person/2> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/1> .
<http://example.com/person/2> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/4> .
<http://example.com/person/3> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/4> .
<http://example.com/person/3> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .
<http://example.com/person/4> <http://xmlns.com/foaf/0.1/knows> <http://example.com/person/2> .

<http://example.com/person/1> <http://www.w3.org/2000/01/rdf-schema#label> "Jim" .
<http://example.com/person/2> <http://www.w3.org/2000/01/rdf-schema#label> "Clare" .
<http://example.com/person/3> <http://www.w3.org/2000/01/rdf-schema#label> "Antoine" .
<http://example.com/person/4> <http://www.w3.org/2000/01/rdf-schema#label> "David" .

Then you can use SPARQL's UNION feature to achieve what you want by merging the result of three separate queries. It can be expressed more succinctly using SPARQL property paths:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT DISTINCT * WHERE {
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/rdfs:label ?knowsName .
} }
UNION
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/foaf:knows/rdfs:label ?knowsName .
} }
UNION
{ SELECT * WHERE {
<http://example.com/person/1> foaf:knows/foaf:knows/foaf:knows/rdfs:label ?knowsName .
} }
}

You can also get the full transitive closure of the knows predicate via a single property path expression:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT * WHERE {
<http://example.com/person/1> foaf:knows+/rdfs:label ?knowsName .
}

...if your triplestore supports SPARQL 1.1. Otherwise you would have to use reasoning or repeated queries to get the full closure.


text:
Q: Change DB State with an Submit Button I want add to my Laravel 5 Website and Button where change the value after submit.
Here my Example code:
<form method="POST" >
<input type="hidden" value="3" name="{{$sale->state}}">
 <button type="submit" name="button" class="btn btn-success">FE</button>
</form>

Dont work but i just playing a little bit. Any one an good Idea how can make this Action?
I want that the Button click make an change from Status delivered to complete = In my DB Table sale and state must change the state value from 1 to 3.
Many Thanks

A: The name of your input must be the name of the model attribute (that reflects in database table column).
Try this (if your column name is state):
<input type="hidden" value="3" name="state">
By using name="{{$sale->state}}" as name attribute, you're passing the value of state attribute from your $sale object.


text:
Q: Script de backup do cPanel movendo arquivos para pasta errada Euj tenho este script para backup full do cPanel que funciona bem:  (https://github.com/pietromalerba/cPanel-Full-Backup-Script).
Eu segui exatamente as configurações da orientação, criei duas pastas /backups/backup_daily e /backups/backup_monthly e os cron jobs correspondentes.
O problema é que o backup mensal está sendo sempre movido para a pasta do backup diário.
E mesmo que eu mova manualmente o arquivo de backup mensal para a pasta correta dele, quando o script roda novamente o arquivo volta ser movido para a pasta diária, misturando-se assim com os demais arquivos, incorretamente.
Eu achoque o problema está na linha 47 do backup.sh:
find $HOME -type f -name "backup-*" -exec mv {} $BACKUP_FOLDER/ \;
Alguém saberia me dizer como consertar isso?

A: Resolvido mudando a linha 47 para:
find $HOME/* -maxdepth 0 -type f -name "backup-*" -exec mv {} $BACKUP_FOLDER/ \;


text:
Q: how we can check this integral $\displaystyle\int_{0}^{1}\left(\frac{\sin x}{x}\right)^2{\rm d}x$ converges? This is home work problem, Please Help me How can I check the convergence of the integral  $$\displaystyle\int_{0}^{1}\left(\frac{\sin x}{x}\right)^2{\rm d}x$$

A: The integral is well defined on any interval $(a,1)$ for $0<a<1$, so the question is, does it get freaky as $a\to 0^+$.
It is well-known (and easy to prove) that for $x\in(0,\pi/2)$,
$$\sin x < x < \tan x$$
And so
$$(\cos x)^2< \left(\dfrac{\sin x}{x}\right)^2 < 1 $$
Giving,
$$ \int_0^1(\cos x)^2 dx < \lim_{a\to 0^+}\int_a^1 \left(\dfrac{\sin x}{x}\right)^2 dx < 1 $$
This shows that the integral has a value in $\left(\dfrac{1}{4}(2+\sin(2)), 1\right)$


text:
Q: Listen for terminal session "close" event In a terminal I start a background process A, which in turn starts a process B. Process B writes to the terminal (process A has passed B the correct TTY file descriptor).
What I am afraid of, is if the user (in some cases, me) closes the terminal window without sending process A or B a SIGINT. What could then happen is that process B will still attempt to write to the terminal even though it's been closed by the user. Worse, the user could open a new terminal window and it might assume the same identity / file descriptor that the other terminal had and then subsequently get written to by process B.
Basically, I am looking for a way to "listen" for terminal session events like terminal sessions being closed.
Is it possible to listen for such events inside a Node.js process? Perhaps there is a corresponding handler similar to process.on('SIGINT')?
I was guessing maybe the SIGTERM event was the event to listen to, but now after experimenting with the code, don't think that is it.

A: You should look for SIGHUP (see also all possible signals):
var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  setTimeout(function () { //simulate a long request
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
  }, 4000);
}).listen(9090, function (err) {
  console.log('listening http://localhost:9090/');
  console.log('pid is ' + process.pid);
});

process.on('SIGHUP', function () {
  fs.writeFileSync(`${process.env.PWD}/sighup.txt`, `It happened at ${new Date().toJSON()}`);
  server.close(function () {
    process.exit(0);
  });
});


text:
Q: Weird effect when using receiveShadow I'm trying to get receiveShadow to work on a cube. Not only it doesn't work, but when I set cube.receiveShadow = true, the light on the cube shows weird dark borders (links to images below).
There's no other object and I've pretty much only have a cube, a plane, and a spotlight in the scene.
    let geometry = new THREE.BoxGeometry(5,5,5);
    let material = new THREE.MeshLambertMaterial({color: 0x11bb22});
    let cube = new THREE.Mesh(geometry, material);
    cube.castShadow = true;
    //cube.receiveShadow = true
    scene.add(cube);

    light = new THREE.SpotLight(0xffffff, 2, 100, Math.PI/4, 0.1, 0);
    light.position.y = 10;
    light.castShadow = true;
    light.shadow.bias = 0.001;
    light.shadow.mapSize.width = 2048;
    light.shadow.mapSize.height = 2048;
    scene.add(light);

    renderer = new THREE.WebGLRenderer();
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFShadowMap;
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

With castShadow=false
With castShadow=true
Thanks!

A: Thanks, setting the bias to 0 did the trick. both 0.001 and -0.001 cause weird effects where the shadow does not look realistic.


text:
Q: How to notify search engines that my site is down for some time? My site will be down for next few days. Is there any way to so that search engines knows about this and don't do any -ve action towards reputation and pagerank of website.

A: I believe that you should return a status of 503 (Service Temporarily Unavailable).  This tells the bots that there is a temporary condition.
This, of course, assumes that by down, you mean that the domain is available but the content is not.  If, on the other hand, you are not going to have domain availability, I am unsure what the correct course of action would be.


text:
Q: How can I be notified of an index being updated on DynamoDB? I have a table (key=username, value=male or female) and an index on the values.
After I add an item to the table, I want to update the counts of males and females. However, after a successful write, as the index is a Global Secondary Index, the count query is not consistent.
Is there a way (dynamo db Streams, Lambda, ...) to monitor when the index is up to date?
Note that Im not looking for a solution that involves something else (keep count of increments in redis or ...), what I describe here is a simplified problem to especially ask a question about how can I monitor an index in dynamo.
Thanks!

A: I am not sure if there is any mechanism currently provided to check this but, you can easily solve this problem by adding a single line of code to your query.
ConsistentRead = True

DynamoDB has a parameter when set as true will make sure that you get latest updated value.
Now, when you add/update the item and then query the data add ConsistentRead option in it, this will ensure that you will have latest count value.
Here is the reference link.
If you are able to accomplish using other technique then please do share it.
Hope that helps.


text:
Q: Site with different authentication for site students and staff in Django? I am trying to create a Django web app with two types of users, Students and Staff. The problem is Students must login with their full name and id number (where name is non-unique, and id number operates as password), but I do not believe there is a way for Django to allow name to be non-unique (USERNAME_FIELD constant must be unique). Staff have a different login, they can login with regular username and password (username must be unique). Also, because there are two types of users, I do not know what to put for the AUTH_USER_MODEL constant in settings.py, since there can only be one model for this. What is the best way to set up the app without running into these problems?

A: If I understood your question properly, you want to keep the usernames of students "non-unique" and you want to differentiate them with unique passwords (Id number).
Django doesn't allow this because it is not a good practice. Why don't you consider keeping "Id number" and "name" as a password (which is again not a good practice to keep "name" as a password but will work in Django)?
Otherwise, if you want to do what you are trying to do, then you can code your own method for authentication instead of using Django's inbuilt method. This may not be that secure but I think your approach itself is not secure so this might work for you.


text:
Q: Как изменить стиль блока в фиксированном виде?

Блок

nofloatings - не фиксированный блок
floating - фиксированный
.nofloating {background: white;}
.floatings {}
Что прописать в css что-бы .floating не наследовал фон именно в таком виде расположения в коде floatings ->nofloatings


text:
Q: NoMethodError in SessionsController#create Ok, I'm learning R on R from the Pragmatic Bookshelf text Agile Webdevelopment with Rails 4th ed.
I'm at page 212 and I'm getting this error....NoMethodError in SessionsController#create and app/controllers/sessions_controller.rb:7:in 'create'
I'm pulling my beard out over here, I've spent days trying to track this down. Here is the create code this is pointing to...
def create
  if user = User.authenticate(params[:name], params[:password])
    session[:user_id] = user.id
    redirect_to admin_url
  else
    redirect_to login_url, :alert => "Invalid user/password combination"
  end
end

Can any Guru out there assist?

A: Sounds like you need the following in your user model (page 203 on my book.)  If that is not the issue, please provide your user model too.
def User.authenticate(name, password)
  if user = find_by_name(name)
    if user.hashed_password == encrypt_password(password, user.salt)
      user
    end
  end
end


text:
Q: Avoid std::bad_alloc. new should return a NULL pointer I port a middle-sized application from C to C++. It doesn't deal anywhere with exceptions, and that shouldn't change.
My (wrong!) understanding of C++ was (until I learned it the hard way yesterday) that the (default) new operator returns a NULL pointer in case of an allocation problem. However, that was only true until 1993 (or so). Nowadays, it throws a std::bad_alloc exception.
Is it possible to return to the old behavior without rewriting everything to using std::nothrow on every single call?

A: Include the header <new>. It contains a "no-throw" version of new you can use like this:
#include <new>

int main() {
    int* p = new(std::nothrow) int;
    if (p) {
        delete p;
    }
}

Edit:
I admit I missed the last sentence of the question. But to be honest, I think that tweaking "plain new" to have pre-Standard behaviour isn't a good idea either. I'd look into some kind of automated search & replace to turn each new into new(std::nothrow).

A: You could overload operator new:
#include <vector>

void *operator new(size_t pAmount) // throw (std::bad_alloc)
{
    // just forward to the default no-throwing version.
    return ::operator new(pAmount, std::nothrow);
}

int main(void)
{
    typedef std::vector<int> container;

    container v;
    v.reserve(v.max_size()); // should fail
}

A: Sorry, but as for my opinion you should NOT do this and return to old new behavior.
This is because you simply can't avoid exceptions anyway.
WHY?
Consider about new call which should allocate class with constructor calling some initialization code which needs to construct anything temporary which is dynamic. Alas, you are going to have exception. No matter if you use std::nothrow. This is only one scenario among number of them.
In Scott Meyers book Effective C++ it was discussed in details as far as I remember. But I'm not sure if all the cases are reviewed (but I suggest enough of them).

A: Just try it out :
1.Define a function which you want to invoke on out of memory condition.
2.Pass this function to set_ new _handler function so when new fails this function will be called.

A: Your compiler likely has a commandline switch to enable/disable this behaviour.


text:
Q: Как сделать так чтобы один флекс котейнер наезжал на другой? Как сделать так чтобы один флекс котейнер наезжал на другой?
Что то вроде этого

A: Уже нашёл статейку
https://www.internet-technologies.ru/articles/nalozhit-elementy-drug-na-druga-s-pomoschyu-css.html
Если кратко чтобы наезжал пишите наезжающему флексу
   .megadub {
   position: absolute;
   top: 200px;
   left: 60px;
 }


text:
Q: Which is faster: Union or Concat? Which is faster: Union or Concat?
I don't care about the order of the elements.
Enumerable.Union Method
Enumerable.Concat Method

A: Union removes duplicates. Concat does not.
So, they produce different results if the sources either contain any items in common, or have any internal duplicates.
If you can guarantee there are no duplicates, or if there are few and you don't care about having them in your output, Concat will be faster since there's no need to test each value against what has already been yielded.
However, if there are many duplicates and you don't need them, the extra processing in Union to remove the dupes may be offset by the savings in your code that consumes the results.

A: What was said above is right. Here is just a little addition for some special cases:
If you have to concatenate for example two lists and if you need full speed, consider using yield. Of course this is a lot less flexible and comfortable than Union or Concat in Linq. Therefore it makes only sense in special cases.
This property for example will provide the same as List1.Concat(List2)
public IEnumerable<MyObject> AllObjects
{
    get
    {
        foreach (MyObject o1 in List1)
            yield return o1;

        foreach (MyObject o2 in List2)
            yield return o2;
    }
}

A: Do you only care about execution speed? How long does it take you to process an element when you receive it?
Concat is simpler - it doesn't need to perform any processing itself, or buffer the results that it's already returned. However, it will produce more results if there are any elements in the intersection. If you're going to take a long time to process each result, Concat may end up effectively being slower.


text:
Q: Pandas: To create a new column based on two column values Learning column comparison.
How to create a new column based on two columns?
I can do two conditions fruit or vegetable. But for the third condition, couldn't do. :(
df
    basket1     basket2
0   fruit       fruit
1   vegetable   vegetable
2   vegetable   both
3   fruit       both

The result
Newdf
    basket1    basket2    total
0   fruit      fruit      fruit
1   vegetable  vegetable  vegetable
2   vegetable  both       Unknown
3   fruit      both      fruit

Thanks a lot for your help!

A: Update
Revisiting this, DataFrame.apply is slow AF. Let's look at some other options and then compare.
Other options to DataFrame.apply

*

*numpy.where
This method can be applied when we only have two options. In your case, this is true as we return df.a when df.a == df.b or df.a == 'fruit' and df.b == 'both'. The syntax is np.where(condition, value_if_true, value_if_false).
In [42]: df['np_where'] = np.where(
    ...:     ((df.a == df.b) | ((df.a == 'fruit') & (df.b == 'both'))),
    ...:     df.a,
    ...:     'Unknown'
    ...: )

*numpy.select
You would use this option if you had multiple conditions. The syntax for this is np.select(condition, values, default) where default is an optional parameter.
In [43]: conditions = df.a == df.b, (df.a == 'fruit') & (df.b == 'both')

In [44]: choices = df['a'], df['a']

In [45]: df['np_select'] = np.select(conditions, choices, default='Unknown')

Note that for the purposes of demonstration I have created two conditions even if the outcomes yield the same result.
Comparing the options
As you can see, all three methods have the same outcome.
In [47]: df
Out[47]:
           a          b   np_where  np_select   df_apply
0      fruit      fruit      fruit      fruit      fruit
1  vegetable  vegetable  vegetable  vegetable  vegetable
2  vegetable       both    Unknown    Unknown    Unknown
3      fruit       both      fruit      fruit      fruit

But how do they compare in terms of speed? To check this, let's create a newer, larger DataFrame. We're doing this to see how our options perform with larger amounts of data.
In [48]: df_large = pd.DataFrame({
    ...:     'a': np.random.choice(['fruit', 'vegetable'], size=1_000_000),
    ...:     'b': np.random.choice(['fruit', 'vegetable', 'both'], size=1_000_000)
    ...: })

In [49]: %timeit df_large['np_where'] = np.where(((df_large.a == df_large.b) | ((df_large.a == 'fruit')
    ...:  & (df_large.b == 'both'))), df_large.a, 'Unknown')
379 ms ± 64.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [50]: %timeit df_large['np_select'] = np.select(((df_large.a == df_large.b), ((df_large.a == 'fruit'
    ...: ) & (df_large.b == 'both'))), (df_large.a, df_large.a), default='Unknown')
580 ms ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [51]: %timeit df_large['df_apply'] = df_large.apply(total, axis=1)
40.5 s ± 6 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

Wow! As you can see DataFrame.apply is much slower than our other two options and np.where edges out np.select.
Conclusions

*

*Use np.where if you have only two choices

*Use np.select if you have multiple choices

*Don't use DataFrame.apply (especially for large data sets)!

Resources

*

*https://stackoverflow.com/a/19913845/5491375

*https://stackoverflow.com/a/31173785/5491375 (has some fast options if you're only interested in a single column)

Create your own function and use DataFrame.apply
In [104]: def total(r):
     ...:     if r.a == r.b:
     ...:         return r.a
     ...:     elif (r.a == 'fruit') and (r.b == 'both'):
     ...:         return r.a
     ...:     return 'Unknown'
     ...:

In [105]: df = pd.DataFrame({'a': ['fruit', 'vegetable', 'vegetable', 'fruit'], 'b': ['fruit', 'vegetable', 'both', 'both']})

In [106]: df
Out[106]:
           a          b
0      fruit      fruit
1  vegetable  vegetable
2  vegetable       both
3      fruit       both

In [107]: df['total'] = df.apply(total, axis=1)

In [108]: df
Out[108]:
           a          b      total
0      fruit      fruit      fruit
1  vegetable  vegetable  vegetable
2  vegetable       both    Unknown
3      fruit       both      fruit

A: df["total"] = df.apply(lambda x: x.a if (x.a == x.b) or ((x.a == 'fruit') and (x.b == 'both')) else 'Unkonwn', axis = 1)

Output
           a          b      total
0      fruit      fruit      fruit
1  vegetable  vegetable  vegetable
2  vegetable       both    Unkonwn
3      fruit       both      fruit

A: Here's solution using np.select
df['total'] = np.select([df['a']==df['b'], (df['a']=='fruit')&(df['b']=='both')], [df['a'], 'fruit'], 'Unkown')

Output:
    a          b           total
0   fruit      fruit       fruit
1   vegetable  vegetable   vegetable
2   vegetable  both        Unknown
3   fruit      both        fruit

A:
data.csv

basket1,basket2
fruit,fruit
vegetable,vegetable
vegetable,both
fruit,both

code.py

import pandas as pd

df = pd.read_csv('data.csv')
for i, r in df.iterrows():
    if df.at[i, 'basket1'] == df.at[i, 'basket2']:
        df.at[i, 'total'] = df.at[i, 'basket1']
    else:
        df.at[i, 'total'] = 'something else'

Output:
     basket1    basket2           total
0      fruit      fruit           fruit
1  vegetable  vegetable       vegetable
2  vegetable       both  something else
3      fruit       both  something else


text:
Q: Finding limit involving floor function. Finding $\displaystyle \lim_{x\rightarrow 0}x^2\bigg(1+2+3+\cdots \cdots +\bigg\lfloor \frac{1}{|x|}\bigg\rfloor \bigg)$, where $\lfloor x \rfloor $ is a floor function of $x$
Attempt: put $\displaystyle x = \frac{1}{y}$
so $\displaystyle \lim_{y\rightarrow \infty}\frac{1+2+3+\cdots \cdots \lfloor y \rfloor }{y^2}$
could some help me

A: The sum rewrites $1+2+ \dots +\lfloor y\rfloor = \frac{\lfloor y\rfloor (\lfloor y\rfloor +1)}{2}$. Therefore, the studied function is asymptotically equivalent to $\frac{1}{2} \left(\frac{\lfloor y\rfloor}{y}\right)^2$, which tends towards $1/2$ at infinity.

A: We know that $y - 1 \lt \lfloor y \lfloor  \le y$. From here, $\frac {(y-1)y} 2 \lt \frac {\lfloor y\rfloor (\lfloor y\rfloor +1)} {2} \le \frac {y(y + 1)} 2 $ therefore, using the squeezing theorem, the limit is $\frac 1 2$


text:
Q: What is the precise relationship between Langlands and Tannakian formalism? As anyone who's been reading the forums closely can see, I've been averaging a question a day about Tannakian formalism for the past few days. It's quite an interesting concept!
In any case, I wish now to relate it to yet another topic of which I have only a tenuous grasp: the Langlands program. As I understood more and more about Tannakian formalism, it seemed more and more like it has something to do with Langlands. A google search confirms this. There are several sources that group these two things together. Here is a sample:
http://www.claymath.org/cw/arthur/pdf/automorphic-langlands-group.pdf
http://www.institut.math.jussieu.fr/~harris/Takagi.pdf
But my understanding of Langlands is weak. I'm certainly familiar with Class Field Theory, and to some limited extent with Taniyama-Shimura. I always found Langlands difficult to penetrate. But now that I know that there is a relationship between Langlands and Tannakian formalism, I am hopeful that this will give me a bird's eye view of Langlands.
So the question is: Does Tannakian formalism simplify the statement of Langlands, or at least motivate it? Does it have to do with the motivic Galois group (defined to be the group predicted from Tannakian formalism on the category of numerical motives)? How precisely is Tannakian formalism used in Langlands?
In light of these ideas, I ask a secondary question: is there a relationship between the standard conjectures and Langlands? (does one imply the other?)

A: Though there are several automorphic papers discussing the Tannakian outlook (notably Ramakrishnan's article in Motives (Seattle 1991, AMS) and Arthur's A note on the Langlands group, (referred to above) there is as yet no formulation of Langlands correspondence between Galois representations and automorphic representations as an equivalence of Tannakian categories. There are (at least) two outstanding fundamental questions on the Tannakian aspects of the Langlands correspondence.
1) What is the definition of the category of automorphic representations for any number field?
here one means automorphic representations for GL, any $n \ge 0$.
2) How to endow the category in 1) with a tensor structure so as to render it Tannakian?
here the postulated Tannakian group is the "Langlands Group" which is much larger
than the motivic Galois group (not all automorphic representations correspond to Galois
representations..only algebraic ones do - see work of Clozel and more recent work of Buzzard-Gee).
An interesting point: Arthur's paper postulates the Langlands group as an extension of the usual
Galois group by a (pro-) locally compact group whereas the motivic Galois group is an extension
of the usual Galois group by a pro-algebraic group. An illustration of the difference is provided
by the case of abelian motives; the Langlands group is the abelianisation of the Weil group
whereas the motivic group is the Taniyama group (see references below).
But the Tannakian outlook, despite its present inaccessibility, has already made a profound impact.  See Langlands paper "Ein Marchen etc" (where the Tannakian aspect was first written out with many consequences for the Taniyama group (Milne's notes)) as well as
 Serre's book Abelian l-adic representations for many references.
Nothing seems to be known regarding the second question. However, see (page 6 of) these comments of Langlands:
"Although there is little point in premature speculation about the form that the final theory connecting automorphic forms and motives will take, some anticipation of the possibilities has turned out to be useful. Motivic $L$-functions, in terms of which Hasse-Weil zeta functions are expressed, are introduced in a Tannakian context.
....
An adequate Tannakian formulation of functoriality and of the relation between automorphic representations and motives ([Cl1, Ram]) will presumably include the Tate conjecture ( [Ta] ) as an assertion of surjectivity. The Tate conjecture itself is intimately related to the Hodge conjecture whose formulation is algebro-geometrical and topological rather than arthmetical. ..."
The references here are to Clozel and Ramakrishnan's papers and then Tate's paper for the Tate conjecture.
This is just a rough answer from a novice..for a precise and detailed answer, let us wait for the experts!


text:
Q: Analyzing order book data in python I'm pretty new in financial data analyzing with python. I have a clean data with ask and bid order books like this:
In:
df.loc ['2022-03-18 00:00:00' , 'LOB_Bid']

Out:
200.000000|1|578.750000|1|586.500000|1|6490.000000|3|7396.000000|3|7859.000000|1|8000.000000|1|8391.000000|1|9050.000000|4|9679.000000|2|9984.000000|1|10184.000000|1|10284.000000|1|10700.000000|1|10786.000000|2|10882.000000|2|10888.000000|1|11111.000000|1|11136.000000|1|11611.000000|2|11686.000000|1|11712.000000|1|11750.000000|1|11800.000000|5|11818.000000|2|11911.000000|1|12000.000000|203|12002.000000|2|12075.000000|1|12096.000000|9|12113.250000|1|12213.750000|2|12223.000000|1|12234.000000|1|12255.000000|1|12282.500000|5|12303.000000|1|12329.000000|1|12345.750000|4|12355.500000|6

(Actually it's so much longer)
How I can use this data in my analysis? How I can extract useful data from that for predicting price?
Could you please kindly guide me?
Thanks
I want to use this data in classification and analysis. But I don't have any idea about it.


text:
Q: Chrome extension content script - .click() not working I've been trying for hours and I can't get this working. I've written a content script that executes when the user loads a page. The click() method just simply won't work when I try click an element. I've tried multiple ways and it always works from the console, but not when I load the page.
The element I want to click:
Megpörgetem

manifest.json - content script part
{
  "content_scripts": [
    {
      "matches": ["*://*.bonuszbrigad.hu/bonuszkerek"],
      "js": ["plugin/jquery-3.2.0.min.js", "js/page_wheel.js"],
      "run_at": "document_end"
    }
  ],
}

page_wheel.js
function spinWheel() {
    var spinButton = $("#startButton");

    if (spinButton.text() === "Már pörgettél") {
        return "wait";
    }

    else if (spinButton.text() === "Megpörgetem") {
        console.log("spin is available");

        spinButton.on("click",
            function () {
                console.log("inside click action");

                var popupLogin = $("#popup_login");
                console.log(popupLogin);

                if (popupLogin === null) {
                    return "login"
                } else {
                    return "success";
                }
            }
        );

        spinButton.trigger("click");
    }
}

When I load the page, the console logs show that it managed to enter

*

*spinButton.on("click", function (){...});
But there weren't any actual clicks made on the website. When I test the click method in the console, both of the below solutions work:

*

*$("#startButton").click()

*document.getElementById("startButton").click();
Also I see the same console logs - when executing click method from the console - but this way it's actually working.
Does anyone have an idea what is the problem? :/

A: I got this problem. In my case, I realized that there were HTML DOM and script load synchronizes. So when you call the click event, it was still fulfill loaded. So I added the script that invokes the click event into the window.load and it worked.
My script looks like below:
window.onload = function () {
  const btn = document.getElementById('J_LinkBuy')

  if (btn !== null) {
    btn.dispatchEvent(new MouseEvent('click'))
  }
}

A: Solution 1: You can use onclick attribute on any HTML tag and use it to call JavaScript functions.
 Click me

Solution 2: Use jquery click event function.

Remember, the jquery click should be called only after the target html
element is generated. the click call won't work or else

$(css_selector).click();


text:
Q: Laravel "Creating default object from empty value" yet Everything is set well no typo error and I don't think I have wrong connection between MVC yet I'm getting an error

"Creating default object from empty value"

I can't locate the exact reason of this problem.
The View file:
@extends('layouts.app')

@section('header')

@lang('messages.paypalsettings')

@endsection
@section('content')
<form action="{{route('admin.paypal.save')}}" method="POST">
  {{ csrf_field() }}

            @lang('messages.merchant_email')
            <input type="text" class="form-control" id="merchant_email" name="merchant_email" value="{{$paypal->merchant_email}}">

            @lang('messages.sandbox')
            <select id="sandbox" name="sandbox" class="form-control">
                <option value="1">Yes</option>
                <option value="{{$paypal->sandbox}}">No</option>
            </select>

            @lang('messages.api_username')
            <input type="text" class="form-control" id="api_username" name="api_username" value="{{$paypal->api_username}}">

            @lang('messages.api_password')
            <input type="text" class="form-control" id="api_password" name="api_password" value="{{$paypal->api_password}}">

            @lang('messages.api_secret')
            <input type="text" class="form-control" id="api_secret" name="api_secret" value="{{$paypal->api_secret}}">

            @lang('messages.currency_code')
            <input type="text" class="form-control" id="currency_code" name="currency_code" value="{{$paypal->currency_code}}">

    <button type="submit" class="btn btn-primary">@lang('messages.save')</button>

</form>
@endsection

The controller side
namespace AppExample\Http\Controllers;

use Illuminate\Http\Request;
use AppExample\models\Paypal;
use AppExample\models\PaypalSettings;
use AppExample\User;
use App\Invoice;
use App\Item;
use Auth;
use Lang;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Srmklive\PayPal\Services\ExpressCheckout;
use AppExample\IPNStatus;

class PayPalController extends Controller
{
    /**
     * @var ExpressCheckout
     */
    protected $provider;

    public function __construct()
    {
        $this->middleware('auth');
        //$this->provider = new ExpressCheckout();
    }

    public function paypalsettings(){
       $paypalsettings = PaypalSettings::find(1);
        if(!$paypalsettings){
          $paypalsettings = new PaypalSettings;
          $paypalsettings->sandbox = '';
          $paypalsettings->merchant_email = '';
          $paypalsettings->api_username = '';
          $paypalsettings->api_password = '';
          $paypalsettings->api_secret = '';
          $paypalsettings->currency_code = '';
        }
        return view('paypal.index')->with('paypal', $paypalsettings);
    }

public function save_paypalsettings(Request $request){
    $merchant_email = $request->merchant_email;
    $sandbox = $request->sandbox;
    $api_username = $request->api_username;
    $api_password = $request->api_password;
    $api_secret = $request->api_secret;
    $currency_code = $request->currency_code;
    $paypalsettings = PaypalSettings::find(1);

    // The error starts here:
    $paypalsettings->merchant_email = $request->merchant_email;

    $paypalsettings->sandbox = $sandbox;
    $paypalsettings->api_username = $api_username;
    $paypalsettings->api_password = $api_password;
    $paypalsettings->api_secret = $api_secret;
    $paypalsettings->currency_code = $currency_code;
    $paypalsettings->save();

    // $paypalitems = Paypal::find(1);
    // $paypalitems->item_number = $item_number;
    // $paypalitems->item_name = $item_name;
    // $paypalitems->amount = $amount;
    // $paypalitems->save();
    return back();
}

    public function paypal_items(){
       $paypal = Paypal::find(1);
        if(!$paypal){
          $paypal = new Paypal;
          $paypal->item_number = '';
          $paypal->item_name = '';
          $paypal->amount = '';
        }
        return view('paypal.index')->with('paypal', $paypal);
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function getExpressCheckout(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $cart = $this->getCheckoutData($recurring);

        try {
            $response = $this->provider->setExpressCheckout($cart, $recurring);

            return redirect($response['paypal_link']);
        } catch (\Exception $e) {
            $invoice = $this->createInvoice($cart, 'Invalid');

            session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
        }
    }

    /**
     * Process payment on PayPal.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getExpressCheckoutSuccess(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $token = $request->get('token');
        $PayerID = $request->get('PayerID');

        $cart = $this->getCheckoutData($recurring);

        // Verify Express Checkout Token
        $response = $this->provider->getExpressCheckoutDetails($token);

        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            if ($recurring === true) {
                $response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
                if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
                    $status = 'Processed';
                } else {
                    $status = 'Invalid';
                }
            } else {
                // Perform transaction on PayPal
                $payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
                $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
            }

            $invoice = $this->createInvoice($cart, $status);

            if ($invoice->paid) {
                session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
            } else {
                session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
            }

            return redirect('/');
        }
    }

    /**
     * Parse PayPal IPN.
     *
     * @param \Illuminate\Http\Request $request
     */
    public function notify(Request $request)
    {
        if (!($this->provider instanceof ExpressCheckout)) {
            $this->provider = new ExpressCheckout();
        }

        $post = [
            'cmd' => '_notify-validate'
        ];
        $data = $request->all();
        foreach ($data as $key => $value) {
            $post[$key] = $value;
        }

        $response = (string) $this->provider->verifyIPN($post);

        $ipn = new IPNStatus();
        $ipn->payload = json_encode($post);
        $ipn->status = $response;
        $ipn->save();
    }

    /**
     * Set cart data for processing payment on PayPal.
     *
     * @param bool $recurring
     *
     * @return array
     */
    protected function getCheckoutData($recurring = false)
    {
        $data = [];

        $order_id = Invoice::all()->count() + 1;

        if ($recurring === true) {
            $data['items'] = [
                [
                    'name'  => 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id,
                    'price' => 0,
                    'qty'   => 1,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success?mode=recurring');
            $data['subscription_desc'] = 'Monthly Subscription '.config('paypal.invoice_prefix').' #'.$order_id;
        } else {
            $data['items'] = [
                [
                    'name'  => 'Product 1',
                    'price' => 9.99,
                    'qty'   => 1,
                ],
                [
                    'name'  => 'Product 2',
                    'price' => 4.99,
                    'qty'   => 2,
                ],
            ];

            $data['return_url'] = url('/teacher/{id}/success');
        }

        $data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
        $data['invoice_description'] = "Order #$order_id Invoice";
        $data['cancel_url'] = url('/');

        $total = 0;
        foreach ($data['items'] as $item) {
            $total += $item['price'] * $item['qty'];
        }

        $data['total'] = $total;

        return $data;
    }

    /**
     * Create invoice.
     *
     * @param array  $cart
     * @param string $status
     *
     * @return \App\Invoice
     */
    protected function createInvoice($cart, $status)
    {
        $invoice = new Invoice();
        $invoice->title = $cart['invoice_description'];
        $invoice->price = $cart['total'];
        if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
            $invoice->paid = 1;
        } else {
            $invoice->paid = 0;
        }
        $invoice->save();

        collect($cart['items'])->each(function ($product) use ($invoice) {
            $item = new Item();
            $item->invoice_id = $invoice->id;
            $item->item_name = $product['name'];
            $item->item_price = $product['price'];
            $item->item_qty = $product['qty'];

            $item->save();
        });

        return $invoice;
    }
}

The Model Side
namespace AppExample\models;

use Illuminate\Database\Eloquent\Model;

class PaypalSettings extends Model
{
  protected $table = 'paypal_settings';

    protected $fillable = [
      'sandbox', 'merchant_email', 'api_username', 'api_password', 'api_secret', 'currency_code'
    ];

    public function paypal(){
      return $this->belongsTo('AppExample\models\Paypal');
    }

    public function subscription(){
      return $this->belongsTo('AppExample\models\Subscription');
    }

}

The Route side
Route::get('admin/paypal/edit', 'PaypalController@paypalsettings')->name('admin.paypal.edit');
Route::post('admin/paypal/save', 'PaypalController@save_paypalsettings')->name('admin.paypal.save');

The full error message:

"ErrorException (E_WARNING) Creating default object from empty value"

The error starts with the first line $paypalsettings->merchant_email = $request->merchant_email;
Var Dump:

var_dump($paypalsettings); line 35 under $paypalsettings = new
PaypalSettings;

object(AppExample\models\PaypalSettings)#793 (26) { ["table":protected]=> string(15) "paypal_settings" ["fillable":protected]=> array(6) { [0]=> string(7) "sandbox" [1]=> string(14) "merchant_email" [2]=> string(12) "api_username" [3]=> string(12) "api_password" [4]=> string(10) "api_secret" [5]=> string(13) "currency_code" } ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(false) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(0) { } ["original":protected]=> array(0) { } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } }

A: Replace your paypalsettings function with the following function:
public function paypalsettings(){
       $paypalsettings = PaypalSettings::find(1);
        if(is_null($paypalsettings)){ //change over here
          $paypalsettings = new PaypalSettings;
          $paypalsettings->sandbox = '';
          $paypalsettings->merchant_email = '';
          $paypalsettings->api_username = '';
          $paypalsettings->api_password = '';
          $paypalsettings->api_secret = '';
          $paypalsettings->currency_code = '';
        }
        return view('paypal.index')->with('paypal', $paypalsettings);
    }

A: public function save_paypalsettings(Request $request){
    $merchant_email = $request->merchant_email;
    $sandbox = $request->sandbox;
    $api_username = $request->api_username;
    $api_password = $request->api_password;
    $api_secret = $request->api_secret;
    $currency_code = $request->currency_code;
    $paypalsettings = PaypalSettings::find(1);

    // The error starts here
    $paypalsettings->merchant_email = $request->merchant_email;

    $paypalsettings->sandbox = $sandbox;
    $paypalsettings->api_username = $api_username;
    $paypalsettings->api_password = $api_password;
    $paypalsettings->api_secret = $api_secret;
    $paypalsettings->currency_code = $currency_code;
    $paypalsettings->save();

    return back();
}

This line $paypalsettings = PaypalSettings::find(1);  returns null because the model (id: 1) doesn't exist yet
The next line, you do $paypalsettings->merchant_email = $request->merchant_email;
But since $paypalsettings is null, what you really do is null->merchant_email = 'test@test.com';
I don't exactly know what you're trying to achieve. But the model must exists and tested or created at this moment.
May I recommend you to take a look on how works CRUD ? https://appdividend.com/2018/02/23/laravel-5-6-crud-tutorial/


text:
Q: How to get keypoint "within the homography"? Referring to this answer to this question:

What is happening is that you're considering all the keypoints
  detected in the second image for the calculation of repeatability and
  actually only the keypoints within the homography should be used.

I don't understand how to get the

keypoints withing the homography

Someone can explain how to do it?
EDIT:
Actually looking at the code of evaluation.cpp I think that this operation is already performed. In fact, looking at:
float overlapThreshold;
bool ifEvaluateDetectors = thresholdedOverlapMask == 0;
if( ifEvaluateDetectors )
{
    overlapThreshold = 1.f - 0.4f;

    // remove key points from outside of the common image part
    Size sz1 = img1.size(), sz2 = img2.size();
    filterEllipticKeyPointsByImageSize( keypoints1, sz1 );
    filterEllipticKeyPointsByImageSize( keypoints1t, sz2 );
    filterEllipticKeyPointsByImageSize( keypoints2, sz2 );
    filterEllipticKeyPointsByImageSize( keypoints2t, sz1 );
}
else
{
    overlapThreshold = 1.f - 0.5f;

    thresholdedOverlapMask->create( (int)keypoints1.size(), (int)keypoints2t.size(), CV_8UC1 );
    thresholdedOverlapMask->setTo( Scalar::all(0) );
}

Consider that thresholdedOverlapMask=0 by default. So the part inside the if discard the point outside the homography. Is that correct?

A:
keypoints withing the homography
Those are points that considered as inliers for the result Homograph Matrix. In other words:

Supposing you are using an estimation technique like RANSAC to get your Homograph Matrix, some of your points will be used to construct this Homograph. The others are just a noise(outliers). You need to know which of your points that are not noise and that were used to construct this Homograph.

How to do that in OpenCV?
The cv::findHomography function has the following signature:
Mat findHomography(InputArray srcPoints, InputArray dstPoints, int method=0, double ransacReprojThreshold=3, OutputArray mask=noArray() );

The parameter OutputArray mask is what you are looking for. You can use it like this:
std::vector<uchar> homograph_mask;
auto H= cv::findHomography(set_of_points, other_set_of_points, cv::RANSAC, RANSAC_THRESHOLSD, homograph_mask);
std::vector<std::pair<cv::Point,cv::Point>> points_within_the_homograph;
points_within_the_homograph.reserve(homograph_mask.size());
for(size_t i=0; i < homograph_mask.size();++i){
    if(homograph_mask[i]==static_cast<uchar>(1)){
         points_within_the_homograph.emplace_back(set_of_points[i],other_set_of_points[i]);
    }
}
points_within_the_homograph.shrink_to_fit();

points_within_the_homograph will contain a set of pairs of matched points that are within the Homograph (inliers).


text:
Q: MS Access converting row information to column I've spent hours trying to figure this one out. This is for a manufacturing plant.
A person on the plant floor logs their activities on different machines using a computer system which produces data like this:
Empnbr  Datestamp   Shift   Machnbr Time
00090   6/30/2010   1   0354    11:10
00090   6/30/2010   1   S       12:00
00098   6/30/2010   1   0920    7:00
00098   6/30/2010   1   0143    7:30
00098   6/30/2010   1   S       15:00
00101   6/30/2010   1   0920    7:00
00101   6/30/2010   1   0247    7:30
00101   6/30/2010   1   0147    7:40
00101   6/30/2010   1   S       15:00
00107   6/30/2010   1   0585    7:00
00107   6/30/2010   1   0143    12:00
00107   6/30/2010   1   S       15:00
00109   6/30/2010   1   0920    7:00
00109   6/30/2010   1   0154    7:30
00109   6/30/2010   1   0154    9:00
00109   6/30/2010   1   0154    9:43
00109   6/30/2010   1   0254    10:49
00109   6/30/2010   1   0154    12:30
00109   6/30/2010   1   S       15:00
00111   6/30/2010   1   0591    5:00
00111   6/30/2010   1   S       17:00
00114   6/30/2010   2   0585    15:00
00114   6/30/2010   2   S       23:00

The report I'm trying to write needs the information in such a form
Empnbr      Datestamp      Shift      Time Start       Time End       Machine

This will allow me to calculate the amount of time spent on each machine per person per day. Basically, Access needs to see an employee number, datestamp, and shift and take the first time it sees. Then needs to take the next time it sees and attribute that time to the machine on the first entry. This continues to happen until Access comes across a machine "S" which means signout.
Now time to take some Advil for this headache -- thanks for your help!

A: I would use a temporary table.  When you want to display the report use VBA code to go through your input table, build the report data, and populate the temporary table.  Then display your report using the data in the temporary table.  The function to populate the reporting table would look something like this:
Public Sub BuildReportTable()
    Dim prevEmp As Integer
    Dim prevDate As Date
    Dim prevTime As Date
    Dim prevMachine As String
    Dim prevShift As Integer
    Dim rs As Recordset

    'Empty report table
    CurrentDb.Execute "delete from tblHourReport"

    'Open the data table
    Set rs = CurrentDb.OpenRecordset("tblHours", dbOpenDynaset)
    If Not rs.EOF Then rs.MoveFirst

    'Loop over each data record and create the report record
    prevEmp = 0
    Do While Not rs.EOF
        If prevEmp <> 0 And prevMachine <> "S" Then
            DoCmd.SetWarnings False
            DoCmd.RunSQL "insert into tblHourReport values (" _
                & prevEmp & ", '" _
                & prevDate & "', '" _
                & prevMachine & "', " _
                & prevShift & ", '" _
                & prevTime & "', '" _
                & rs!Time & "');"
            DoCmd.SetWarnings True
        End If
        prevDate = rs!Date
        prevShift = rs!shift
        prevEmp = rs!employee
        prevTime = rs!Time
        prevMachine = rs!machine
        rs.MoveNext
    Loop
End Sub

A: Is there any reason why a grouping query would not suit? For example:
SELECT Empnbr, Datestamp, Shift, Machnbr,
       Min(CDate([datestamp] & " " & [Time])) AS TimeStart,
       Max(CDate([datestamp] & " " & [Time])) AS TimeEnd
FROM MachineLog
GROUP BY Empnbr, Datestamp, Shift, Machnbr

EDIT re comment
Perhaps:
SELECT m.Empnbr, m.Datestamp, m.Shift, m.Machnbr,
     Nz((SELECT Max(CDate([datestamp] & " " & [Time]))
         FROM MachineLog x WHERE x.Empnbr=m.Empnbr
         AND x.Machnbr<m.Machnbr),CDate([datestamp] & " 08:00")) AS st,
     Max(CDate([datestamp] & " " & [Time])) AS TimeEnd
FROM MachineLog m
GROUP BY m.Empnbr, m.Datestamp, m.Shift, m.Machnbr


text:
Q: Working with csv file in python3 programme shows "TypeError: a bytes-like object is required, not 'str'" typeError with csv file in python3I tried to write a python3 programme that writes and edit data in csv file,but it is showing TypeError: a bytes-like object is required, not'str'
screenshot of the output in the terminal is attached.I don't know what this means and what is wrong.Someone help me fix it.the code is below:
import csv
import datetime
import shutil
from tempfile import NamedTemporaryFile

def get_length(file_path):
    with open("data.csv", "r") as csvfile:
    #some csv file data.csv is created in the same directory
        reader = csv.reader(csvfile)
        reader_list = list(reader)
        return len(reader_list)

def append_data(file_path, name, email, amount):
    fieldnames = ['id', 'name', 'email', 'amount', 'sent', 'date']
    #the number of rows?
    next_id = get_length(file_path)
    with open(file_path, "a") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({
                "id": next_id,
                "name": name,
                "email": email,
                "sent": "",
                "amount": amount,
                "date": datetime.datetime.now()
            })

#append_data("data.csv", "some name", "address@mail.com", 123.456)

def edit_data(edit_id=None, email=None, amount=None, sent=None):
    filename = "data.csv"
    temp_file = NamedTemporaryFile(delete=False)

    with open(filename, "rb") as csvfile, temp_file:
        reader = csv.DictReader(csvfile)
        fieldnames = ['id', 'name', 'email', 'amount', 'sent', 'date']
     writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    writer.writeheader()
    for row in reader:
        #print(row['id'] == 4)
        if edit_id is not None:
            if int(row['id']) == int(edit_id):
                row['amount'] = amount
                row['sent'] = sent
        elif email is not None and edit_id is None:
            if str(row['email']) == str(email):
                row['amount'] = amount
                row['sent'] = sent
        else:
            pass
        writer.writerow(row)

    shutil.move(temp_file.name, filename)
    return True
return False

edit_data(8, 9992.32, "")
edit_data(email='address@mail.com', amount=19.90, sent='10')

A: On Python 3 when using csv readers and writers you need to open your file open("data.csv", "r", newline=""). Using rb is compatible with Python 2.x only. You also need to setup similar settings for your NamedTemporaryFile.
The following should help:
import csv
import datetime
import shutil
from tempfile import NamedTemporaryFile

fieldnames = ['id', 'name', 'email', 'amount', 'sent', 'date']

def edit_data(edit_id=None, email=None, amount=None, sent=None):
    filename = "data.csv"

    with open(filename, "r", newline="") as csvfile, \
        NamedTemporaryFile(delete=False, mode="w", newline="") as temp_file:

        reader = csv.DictReader(csvfile, fieldnames=fieldnames)
        writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
        writer.writeheader()

        for row in reader:
            #print(row['id'] == 4)
            if edit_id is not None:
                if int(row['id']) == int(edit_id):
                    row['amount'] = amount
                    row['sent'] = sent
            elif email is not None and edit_id is None:
                if str(row['email']) == str(email):
                    row['amount'] = amount
                    row['sent'] = sent
            else:
                pass
            writer.writerow(row)

    shutil.move(temp_file.name, filename)

edit_data(email='address@mail.com', amount=19.90, sent='10')


text:
Q: Users without permission able to access folder through URL I'm very new to SharePoint 2010, and I've been working on a workflow for folder permissions that replaces all permissions so that only a certain group is given Contribute access to the folder. This seems to work as it should - users who aren't in that certain group seem to be given Limited Access as a default, and so can't see the folder when they enter the document library.
However, the problem is that when they access the folder through a direct URL, they're able to see the folder instead of getting "Access Denied".
Additionally, in the workflow, I also have it set so that non-Folder items inherit permissions from the folder. When users who aren't in the group type in the URL to these documents within the folders, they're correctly shown "Access Denied".
So the permissions seem to work correctly for documents within the folders (so that they're inaccessible even with a direct URL), but somehow a user who shouldn't have permission is able to access the folders themselves with a direct URL (so they see the folder itself, but not the contents within). I've tried removing the groups with Limited Access entirely so that the user's "check permissions" for the folder is none, but they're still able to access it through URL.
Any advice? I'm pretty confused as to why this is happening, and how I can fix it.

A: If you really dont want Limited access feature in your site, deactivate the Limited-access user permission lockdown mode feature. And check if you still face that issue.

A: I tried asking around in other forums, and was told that this happens with folders by design, and using document sets instead would be a good workaround. The document sets seem to be working so far, so I think that's what I'll use. Thanks for everyone's help!
Source: https://social.msdn.microsoft.com/Forums/sharepoint/en-US/3ebdb5e2-5d42-4817-a779-ad575407503e/sharepoint-folders-with-unique-permissions-accessible-via-url?forum=sharepointgeneralprevious&prof=required


text:
Q: Apache poi-3.10-FINAL-20140208.jar download link Can somebody send me a direct link to download this file please: poi-3.10-FINAL-20140208.jar? I am only seeing the .zip files on the internet and not the .jar files.

A: You'll want to start at the Apache POI Download page. From there, you'll see the link to download the Binary Distribution. Pick your preferred archive format (zip or tar), and follow the link to your nearest mirror. Download the resulting archive, and unpack.
Inside the binary distribution, you'll find all the POI jars, including their dependencies


text:
Q: Use the same instance of Object0 in different methods of Object1? I'm trying to make a program that uses Robot but want to be able to set some parameters for that instance to use (delay between actions) every time it is used by the methods but cannot seem to figure it out.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.*;
import org.sikuli.script.*;

public class Functions {
    static Robot robot;
    static Screen screen;

    public static void main(String[] args) throws Exception, IOException, AWTException, InterruptedException {
        Robot robot = new Robot();
        robot.setAutoDelay(50);
    }

    public static void build(Monkey monkey) throws Exception {
        robot.mouseMove(monkey.getX(), monkey.getY());
        robot.getAutoDelay();
    }
}

I've tried having
Robot robot = new Robot();
robot.setAutoDelay(50);

in the build method but then I would need to assign a new Robot for every method (I assume). Is there another way?


text:
Q: Prove that $\sum_{i = n - b}^{a - m} {a - i \choose m}{b + i \choose n} = {a + b + 1 \choose m + n + 1}$ Restrictions on the variables for this identity are as follows: $a \geq m \geq 0$ and $n \geq b \geq 0$.
I have not gotten far with this, but these are my very rudimentary thoughts: We need to define a special element, somehow, and then carve up the $m + n$ remaining elements to be chosen out of the remaining pool of $a + b$ elements by writing $a + b = a - i + b + i$. From the $a - i$ pile, we choose $m$ things. From the $b + i$ pile, we choose $n$ things. My problem is, what is going on with this special element? How is it being defined so as to split things in this precise way?
A hint would be great for the moment.

A:
Combinatorial story

You have been tasked to pick $m+n+1$ books from a bookshelf of $a + b + 1$.
You wonder of all the possibilities you could pick.
Simple combinatorics tells us the answer is ${a+b+1}\choose{m+n+1}$.
However, you see another solution.
You could pick a book in the middle and then take $m$ books of the left of it and $n$ books of the right of it. But you wonder, which books in the middle can you pick?
$$ \sum_{\text{middle book place}} [\text{$m$ books on left}]\times[\text{$n$ books on right}] $$
Now, let's fill in this more concretely. Let's say the middle book is in the $j^{\text{th}}$ position. The middle book can essentially be anywhere. Now, the ways you can pick $m$ books on left will be $\text{# books on left} \choose m$. Likewise for $n$ books on right. The books on the left of $j$ will be $j-1$ many, books on the right will be $a+b+1-j$. However, notice that when there are less than $m$ books on the left, there are no ways to pick, so we don't need to count them in the index. Same for $n$ on the right. Now we can change the index. I've taken care of each change with a new line :). The last line is in my opinion the most tricky, but try and denote the shift with $i = -j + a + 1$. I worked out the shift, almost by cheating, since I know what I wanted to mold the answer to be. One could argue there is another final step, noting that addition is commutative and so we can swap the end points of summation.
\begin{align}
&\sum_{j = 1}^{a+b+1} {{\text{# books on left} \choose {m}}  \cdot {{\text{# books on right} \choose {n}}} }\\
= &\sum_{j = 1}^{a+b+1} {{j-1 \choose {m}}  \cdot {{a+b+1-j \choose {n}}} } \\
= &\sum_{j = m+1}^{a+b+1-n} {{j-1 \choose {m}}  \cdot {{a+b+1-j \choose {n}}} } \\
= &\sum_{i = a - m}^{n-b} {{a-i \choose {m}}  \cdot {{b+i \choose {n}}} } \\
\end{align}
In my opinion, combinatorial story is a very powerful method of understanding combinatorics. Another common technique is to prove it by pure messy unadulterated algebra (not the good kind). I was going to originally prove it with both methods for comparison, but the latter was too messy for me.

A: You can prove this statement using lattice walks from $(0,0)$ to $(m+n+1, a+b-m-n)$ with $(1,0)$ and $(0,1)$ steps. There are
$$
\binom{a+b+1}{m+n+1}
$$
such walks.
Classify such walks based on the highest $y$-coordinate where they touch the vertical line $x=n$. Counting this way we get the sum
$$
\binom{n}{n}\binom{a+b-n}{m}+\binom{n+1}{n}\binom{a+b-n-1}{m}+\dotsb+\binom{a+b-m}{n}\binom{m}{m}
\tag{1}
$$
since we go from the point $(0,0)$ to $(n,k)$ for $0\leq k\leq a+b-m-n$ and then we are forced to go one unit right and then go from $(n+1,k)$ to $(m+n+1, a+b-m-n)$.
But the sum in (1) is exactly
$$
\sum_{i = n - b}^{a - m} {a - i \choose m}{b + i \choose n}
$$
as desired.


text:
Q: Why does violet (purple) color contain red component? We see rainbow color on short-wavelength side as violet or purple:

And this color is obviously contain R component from RGB.
How can this happen, if only blue pines can percept this color, while red pines are on the opposite side of the band?


text:
Q: a continuous map from a closed interval to a closed interval Suppose $f$ is a continuous map from $[0,1]$ to $[0,1]$ such that $f(0)=0 $ and $f(1)=1$,can we conclude that $f$ is a surjective map?

A: Yes, this follows by intermediate value property.
See https://en.wikipedia.org/wiki/Intermediate_value_theorem

A: Yes, $f[[0,1]]$ is connected and the only connected subset of $[0,1]$ that contains $0$ and $1$ is $[0,1]$: if $0 < p < 1$ is not in $f[[0,1]]$, then $f^{-1}[[0,p)]$ and $f^{-1}[(p,1]]$ would disconnect $[0,1]$.


text:
Q: How to parse the html content in php code? How can I parse the content of each header in the below code separately.
$str="

Java

Java is a platform independent object oriented programming language

Html

HTML is a markup language for describing web documents

Php

Php is simple

          ";

A: Using DOMDocument & XPath it is quite straightforward.
$str="

Java

Java is a platform independent object oriented programming language

Html

HTML is a markup language for describing web documents

Php

Php is simple

";

$dom=new DOMDocument;
$dom->loadHTML( $str );
$xp=new DOMXPath( $dom );
$col=$xp->query('//h1|//h2|//h3');
foreach( $col as $node ) echo $node->nodeValue;


text:
Q: How to fix the navbar toggle button not displaying items in Bootstrap 5.2 I have bootstrap 5.2.3 installed as an npm dependency in my angular application.
I am trying to add a toggle button in my navbar to display a list of list items when the page size is reduced.

      App Name

    <button class="navbar-toggler" type="button"
            data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false"
            aria-label="Toggle navigation">

    </button>

        <ng-container *ngFor="let app of appList">

              {{app.name}}

        </ng-container>

      {{ notify }}

  <router-outlet></router-outlet>

I have consulted Bootstrap's official documentation and tried to reverse-engineer my code using their template but the application refuses to display the list of items.
The only time it displays it is when I set my .navbar-toggler element's class to .show but this keeps the list open by default.