text:
Q: React js - Laravel 5: Using csrf-token in POST method I've read some questions about Laravel's CSRF, but I still haven't found how to use it with React.
My goal is to make a POST form, where I make an AJAX call.
Here is an extract of my render( ).
render() {
return (
  <form method="post" action="logpage">
   <input type="hidden" name="csrf-token" value="{{{ csrf_token() }}}" />
   //I'm sure this doesn't have csrf_token.

   <input type="text" name ="word" value={this.state.word || ''}/>
   <button onClick={this.submit} className="btn btn-flat btn-brand waves-attach waves-effect" data-dismiss="modal" type="button">Save</button>
  </form>
  );
}

Here is the submit function.
submit(){
fetch('/words', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
  body: JSON.stringify({
    //parameters
  })
}).then((response)=>{
  console.log(response);
});
}

The problem, I assume, is that $('meta[name="csrf-token"]').attr('content') is not being sent, because the token isn't generated. However, I don't see how I can generate it on React.
Does anyone have an idea?

A: You can echo the token in Javascript like this:
<script>
    var csrf_token = '<?php echo csrf_token(); ?>';
</script>

And access it from anywhere in Javascript
'X-CSRF-TOKEN': csrf_token

I hope this works for you.

A: You can also exclude some routes from csrf protection, meaning you don't need the token when posting to those routes, but you also risk cross site forgery posts on those routes.
To exclude, open app\Http\Middleware\VerifyCsrfToken.php and you will see an $except array. Just add the route you wish to exclude to that array:
protected $except = [
  '/uploadtest'
];

I used this method when playing around with uploading files to AWS S3 store from a React Component, which avoided me needing to write a new blade template for the upload - I just put the form in the React Component, and added my POST route to the except array.
Once I got it "working" without csrf, I added it in by putting a global var definition in my blade template:
<head>
...
...
<script>
...
var csrf_token = '{{ echo csrf_token()}}';
...
</script>
</head>

and then included in in the form via the global variable - this worked! even though it 'should' be a prop, not a global variable:
<form action="/uploadtest" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="_token" value={csrf_token} />
  <input type="file" name="filename" />
  <input type="submit" value="Upload"/>
</form>

the 'better' way would be to pass the token in as a prop:
<form action="/uploadtest" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="_token" value={this.props.csrf_token} />
  <input type="file" name="filename" />
  <input type="submit" value="Upload"/>
</form>


text:
Q: Automatically georeference non-intersecting UAS photos based on contained EXIF metadata I need to know how to automatically create georeferenced rasters from multiple non-intersecting photos taken by UAS DJI Phantom 4 Pro.
All EXIF metadata is present in every photo - coordinates, height, camera angles (yaw, pitch, roll). Here is screenshot, with EXIF metadata.
I uploaded some photos, which I need to georeference: Photo 1, Photo 2, Photo 3.
Theses photos do not intersect, so it is impossible to create orthopoto with automated photogrammetry software (e.g. Agisoft Photoscan, Pix4D Mapper, Trimble INPHO). Of course, I can georeference these photos manually in desktop GIS based on underlying satellite imagery, but it is not feasible due to large number of images and time constraints.
We regularly perform monitoring flights over rivers and open water areas and take number of non-intersecting images when we observe species of interest. We need to quickly georeference these images for subsequent use as a layer in GIS for further analysis.
I realize, that this is not standard UAS scenario, but I hope there will be solution. We do not need precise georefencing, just a tough one will suffice.
I have seen something similar done with MISB-compliant video for UAS by means "Full-Motion Video" Plugin for ArcGIS.  MISB-compliant video has coordinates and camera orientation parameters which Full-Motion Video Plugin utilizes for georeferencing any single video frames: Full Motion Video (FMV) ArcMap (by Esri).
So, I am looking for something similar for UAS photos.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript - Create elements using web component class I have a web component that only works when some properties are set, when I create the component with Document.createElement() I can't pass properties then an error happens in my component.
Is it possible to create the component by creating an instance of the component class or something similar and be able to pass parameters to it's constructor?
customElements.define('x-card', class extends HTMLDivElement {
//...
}, { extends: 'div' });

A: You can create a new instance using new WCard. This requires having access to the class though.
Please note that custom element names preferrably should not start with x-.
So change your code:
export class WCard extends HTMLDivElement {
//...
}

customElements.define('w-card', WCard, { extends: 'div' });

window.WCard = WCard;

This allows you to call new on the class globally, or if your code imports the class.
const wcard = new WCard(...args);


text:
Q: Adding a NuGet Package Source that requires credentials with VS2015 I am attempting to setup a NuGet package source that requires credentials.
Here are the instructions
I have the latest version of Visual Studio 2015 with everything up to date. I am aware of how to add a package source through the UI in VS2015, but you can't specify credentials when doing it this way.
The command they are asking me to run is:
NuGet Sources Add -Name "telerik.com" -Source "https://nuget.telerik.com/nuget" -UserName "<your login email>" -Password "<your password>"

I am aware that I need a nuget.exe to run this command, but there is a way to do this directly through VS without downloading anything isn't there?
If I download the NuGet.exe, open a command prompt and navigate to it to run that command will I then be able to see it from Visual Studio's NuGet Package Manager UI and access it from Visual Studio's NuGet Package Manager Console? I am confused on how it will integrate with Visual Studio's built in NuGet Package Manager.

A: I figured out that you need to download nuget.exe to your computer, open up a command prompt and navigate to it. Then run the command to add the package source with credentials:
NuGet Sources Add -Name "telerik.com" -Source "https://nuget.telerik.com/nuget" -UserName "<your login email>" -Password "<your password>"

Restart Visual Studio and the Package Source is added to the list in both the Nuget UI and Nuget Command Line.

A: If you are using SSO and the Windows credentials fix does not work for you, just sign out of Visual Studio, then sign back in again, and then restart Visual Studio; then, the 401 NuGet package source error will be fixed.

A: We can update the file Nuget.config file entry as

<add key="Telerik" value="https://nuget.telerik.com/nuget"
UserName ="<<youremail@mail.com>>"
Password ="<<password>>" />

This let me build and run.

A: I tried the approche Blake Rivell described in his answer. It did not work for me, so I tried to use the -StorePasswordInClearText flag. (See the instruction mentioned in the question)
Then I found out the project I started working on contained a "NuGet.Config" file. The display name of the source in this file was different to the one I added via the command line (to the global "NuGet.Config" file). (Our different projects apparently use different names for it)
So it did not work, because it was not able to associate the source with credentials with the entry in my local "NuGet.Config" file.


text:
Q: Circular linked list detection algorithm So my question is that in The tortoise and rabbit/heir algorithm to detect the circular linked list, why is it necessary to increment the second faster pointer only by 2 ??
I am not able to figure that out neither did i find any answer to it here.
Incrementing the first slow pointer by 1 makes sense so that we are iterating over all the elements which we will compare with a second pointer BUT WHY THE FASTER POINTER NEEDS TO BE INCREMENTED ONLY BY 2. Why can we increment it by 3 or 4 or more ????
And is there a way to calculate what should be the no. of hops(if not 2) of faster pointer in relation to the number of elements in list ???

A: You can use 3, 4 or whatever you want but is the fastest way with 2 because let's say you are in the loop with a step of 2 first time :( D is the pointer that is going 2 steps and S is the normal pointer.
Case 1)
step 1 :x - D - x - S - x - x ...
step 2 :x - x - x - D - S - x ...
step 3 :x - x - x - x - x - SD ( match)

Case 2)
step 1: x - D - S - x this is the step 2 from case 1 and we can see that this is step 2 and we also have a match

but if you have let's say a 3 step (D should be the pointer that is going 3 steps at a time.)
Case 1)
   step 1 : x - D - x - x - S ...
   step 2 : x - x - x - x - D - S ...
   step 3 : x - x - x - x - x - x - S - D ... ( D is passing S and it needs at least another loop to meet S)

Case 2)
step 1 : x - D - x - S -..
step 2 : x - x - x - x - SD ( match)

case 3)
step 1: x - D - S - ..
step 2: x - x - x - S - D ... ( D is passing S and it needs at least another loop to meet S)

And because of that 2 is better than 3, 4 or whatever you want because all the numbers larger than 2 have a chance of 1/(N-1) to meet for the first time.
Another way to explain is this: For D and S and a step of N if the distance between S and D is N - 1 we have a match ( D goes N steps and S 1 step and than D = S), other way D is passing S so we have a 1/(N-1) chance to meet S and D the first time, and because of that if N = 2 we have 1 / 1 = 100% , if N = 3 we have 1/2 = 50%.
 Hope it helped.

A: If you use 3 or 4 as step size, you need to add checks for all special cases when advancing by 3 might result in a null at first or second node.
Also you have a possibility of any of 3 positions from the slow coinciding with the faster one in case of a cycle.
It is just more code, more conditions to handle, error prone and appears less elegant to use more than 2 without any performance gains in terms of Big O


text:
Q: How to avoid overusing interfaces when unit testing In an attempt to make my code friendly for unit testing, it seems wise to utilize depenency injection. This requires that any dependent class must implement an interface with the exact same set of methods.
I also see advice saying that I shouldn't have an interface for every class, but I don't see how I could possibly follow both pieces of advice. If I want unit testing, every single useful class must adhere to an interface.
Proof: Suppose there exists a class that does not implement any interfaces. If I am able to unit test my entire program, then no other code depends on this class. Therefore this class is useless and might as well be deleted.
Is there something I am misunderstanding? Is there a way to unit test without copy/pasting all of my classes into equivalently structured interfaces?

A: In order to write effective tests, you do need seams in your code (a place that let's you break your dependencies apart) to allow you to control any dependencies in your code. Interfaces are possibly the most obvious way to do this, but you can use other techniques such as wrapping your dependency in a method on your class under test and declaring that method as protected virtual (c#) and overriding the class for your unit tests. There is a great series of videos on YouTube around TDD that deal with design decisions when doing TDD. Search for "is TDD dead".

A: When unit testing, you usually just want to mock classes that make external calls (be it a database query or hitting an API).  Consequently, you need to have an interface for these classes.  However, a lot of times you may have random DTOs or utility classes that do small simple things and don't need to be mocked.

A: Some languages have tools that let you mock classes without writing a corresponding interface; for instance, Python allows patching arbitrary classes in test code, and the Mockito library for Java can generate a mock object from any class.
There is a school of thought that says when writing unit tests, only the "leaves", i.e. classes and methods which don't invoke other classes within the application, should be unit tested in isolation, and classes that are involved in orchestrating the behavior of other classes should be tested at the acceptance or integration level. This style of testing avoids writing unit tests that depend on mocking most of the classes in your application, and so avoids the need to write interfaces. Martin Fowler's article on mocks covers some of the differences between different styles of testing regarding mocks.


text:
Q: I/O performance in Node.js worker threads Here's an example with worker thread that takes ~600ms on local machine for synchronous I/O:
const fs = require('fs');
const { isMainThread, Worker, parentPort, workerData } = require('worker_threads');

const filename = './foo.txt';

if (isMainThread) {
    (async () => {
        console.time('!');

        await new Promise((resolve, reject) => {
            const worker = new Worker(__filename, { workerData: filename });

            worker.on('message', resolve);
            worker.on('error', reject);
            worker.on('exit', (code) => {
                if (code !== 0)
                    reject(new Error(`Worker stopped with exit code ${code}`));
            });
        });

        console.timeEnd('!');
    })().catch(console.error);
} else {
    for (let i = 0; i < 100; i++)
        fs.readFileSync(workerData);

    parentPort.postMessage('ok');
}

The same example with single thread takes ~2s for asynchronous I/O:
const fs = require('fs');

const filename = './foo.txt';

console.time('worker');

(function read(i) {
    if (i < 100) {
        fs.readFile(filename, () => read(++i));
        return;
    }

    console.timeEnd('worker');
})(0);

Obviously, synchronous blocking operation is more efficient here.
Node.js worker thread reference states:

Workers are useful for performing CPU-intensive JavaScript operations; do not use them for I/O, since Node.js's built-in mechanisms for performing operations asynchronously already treat it more efficiently than Worker threads can.

What are the grounds for this statement?
What is the difference between main and worker threads regarding I/O?
Isn't the purpose of a worker to not be limited to non-blocking asynchronous operations?
What are the circumstances under which I/O performance may be less efficient in worker threads?

A: You have found an obvious performance problem in Node.js.
I guess that you are testing it on very large files, as this is what this problem affects the most.
The problem is that readFileSync reads the whole file in one operation (one read syscall), while readFile reads in chunks of 512Kb.
I have submitted a PR to fix this, here is the discussion:
https://github.com/nodejs/node/pull/41436
With this PR readFile becomes slightly faster then readFileSync without the overhead of creating a new thread. If you add the new thread creation, the difference is even more pronounced.
Node.js is made for asynchronous IO and this is what works best.


text:
Q: How to edit the style for a Cancel Button in Sencha Framework. I have this code
I need apply a theme to a Cacel Button present in a DataPicker... any idea how to make it?
{
                xtype: 'datepickerfield',
                label: 'Start Date XXX',
                name: 'DateStart',
            //labelWidth: labelWidth,
            value: new Date(),
            picker: {
                yearFrom: yearFrom,
                yearTo  : yearTo,
                hideOnMaskTap: true

            //                toolbar: {
            //                    xtype: 'toolbar',
            //                    items: [
            //                        {
            //                            /*xtype: 'button',
            //                            text: 'Left',*/
            //                            ui: 'custom-btn-confirm',
            //                            style: 'color: #ffffff'
            //                        },
            //                        {
            //                            /*xtype: 'button',
            //                            text: 'Left Two',*/
            //                            ui: 'custom-btn-confirm',
            //                            style: 'color: #ffffff'
            //                        }
            //                    ]
            //                }

            }
        },
        {

A: You can either write custom CSS for the button by using: cls: 'myapp-cancelbutton' or you can use the predefined ui: 'cancel'


text:
Q: OSError when installing ansible with pip in CLI on Windows 10: 'OSError: [Errno 2] No such file or directory' The entire output message I get, irrespective of whether I do it with pip or pip3, or in PowerShell or bash, or with or without --user, is:
PS C:\Users\user> pip install ansible --user
Collecting ansible
  Using cached ansible-4.0.0.tar.gz (33.3 MB)
ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-i5a881am\\ansible_79b10d1774894f28be88e26c8c0385cb\\ansible_collections/amazon/aws/tests/unit/plugins/modules/placebo_recordings/cloudformation/client_request_token_s3_stack/cloudformation.CreateStack_1.json'

A: Thanks to @Zeitounator's comment to my OP, I could finally install ansible on Windows10 WSL correctly using this link.
It is essential to stress here that for achieving this one needs to install bash CLI (or rather Windows10 WSL).


text:
Q: Mostrar u ocultar div en Angular si tiene o no información un input Hola quiero mostrar u ocultar un div, dependiendo si tiene o no información desde el servidor.
Me explico, tengo un formulario que al hacer una llamada al servidor me devuelve unos datos, en esos datos hay un input que esta dentro de un div y debe mostrar la información de las corporaciones pero a veces no existen esas corporaciones entonces lo que busco es que si ese input tiene información me lo muestre y si no tiene entonces oculte el div.
Aquí mi HTML
Quiero ocultar todo el div donde esta el *ngIf

      Corporación
      <input type='text' fullWidth disabled id='corporation'>

      Empleado
      <input type='text' fullWidth [value]='corp.employee?.name' disabled id='employee'>

Y en el TypeScript tengo la siguiente función, aquí me esta mostrando en la consola cuando tiene me muestra que si tiene y cuando no, pues no
showDiv(): void{
 if (corp.employee?.name == null){
  console.log('no tengo corporación');
 }else {
  console.log('Si tengo corporación');
 }

}
Cuando no tiene corporación por defecto el valor es null
¿Cómo puedo realizar esto?

A: La directiva ngIf siempre va a esperar como argumento una expresión booleana, por lo que la función showDiv debe devolver un boolean.
Por ejemplo,
public showDiv(): boolean {
  const name = corp?.employee?.name;
  // Forzamos la variable a boolean
  // Si name existe y no es un string vacío, entonces devuelve true
  return !!name;
}

O también puedes beneficiarte de la type coercion y escribir directamente tu expresión dentro del la directiva ngIf

También tienes la alternativa de mantener una variable boolean que vayas cambiando para mostrar u ocultar tu div (
)
// Por ejemplo...
public fetchCorp() {
  this.corp = ...;
  this.showDiv = true;
}

Hay muchas formas, de conseguirlo. Puedes leer la documentación oficial de ngIf para conocer más.


text:
Q: regex to extract a specific set of numbers I need a regular expression to extract a specific set of numbers from a string. The string could contain letters, special characters and spaces.
Input examples:
This is a test 99 12 3456
This is test 2 94123456
This is test 3 357 95123456
This is test 4 35797123 456
And so on…

The regex should look for a string of 8 numbers starting with 94 or 95 or 96 or 97 or 99 followed by 6 more numbers.
example:
94<6 more numbers here>
95<6 more numbers here>
96<6 more numbers here>
97<6 more numbers here>
99<6 more numbers here>

or 11 numbers starting with 357 followed by 94 or 95 or 96 or 97 and 6 more numbers.
example:
35794<6 more numbers here>
35795<6 more numbers here>
35796<6 more numbers here>
35797<6 more numbers here>
35799<6 more numbers here>

So the output should either be 8 numbers, or 11 numbers. Less than 8 or more than 11 is not a valid output. Also anything between 8 and 11 is not valid.
Hope this makes it more clear
Thanks for your help

A: Maybe this:
(357|94|95|96)[\d ]{6,}

Which means "357" or "94" or "95" or "96" followed by at least six digits and/or spaces. I wasn't sure exactly what you want. It would be better just to post the exact input and output desired.

A: This regular expression will do it if you remove the spaces from the input first: 3579[4-9](?:\d{8}|\d{6})

A: If you're working in an environment that supports lookbehinds, you can ensure you're not matching a partial number by using a negative lookbehind and negative lookahead:
   /(?<!\d)(?:357)?9[4-79]\d{6}(?!\d)/

(?<!\d): Negative lookbehind (ensure there isn't a digit before the matching expression)
(?:357)?: Create a non-capturing group of 357 to attach an optional quantifier (match 357 zero to 1 times)
9: Match 9
[4-79]: Character set with range 4-7 and 9 (match one of these characters)
\d{6}: Match a digit exactly 6 times
(?!\d): Negative lookahead (ensure there isn't a digit after the matching expression)


text:
Q: Boost on Mac OS Undefined Symbols I am encountering problems while compiling a c++ program including boost library. The problems seem to have started occuring after I updated to Catalina, before everything worked correctly.
I use boost installed via homebrew ("brew install boost") and compile the program with g++ version 9 als installed with homebrew.
When compiling with "g++-9 -I/usr/local/include -L/usr/local/lib -lboost_serialization test.cc" the libararies are correctly found by the compiler but the following error occurs. Below I include the error message and the test program that causes it.
An interesting observation is that the name in the error message referenced as "cclgNgf3.o" changes each time I compile. So far I also got "ccmG1kWi.o" and "cc25AYXh.o".
Undefined symbols for architecture x86_64:
  "boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::save(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      void boost::archive::save_access::save_primitive<boost::archive::text_oarchive, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(boost::archive::text_oarchive&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) in cclgNgf3.o
  "boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::text_oarchive_impl(std::basic_ostream<char, std::char_traits<char> >&, unsigned int)", referenced from:
      boost::archive::text_oarchive::text_oarchive(std::basic_ostream<char, std::char_traits<char> >&, unsigned int) in cclgNgf3.o
  "boost::archive::basic_text_oprimitive<std::basic_ostream<char, std::char_traits<char> > >::~basic_text_oprimitive()", referenced from:
      boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::~text_oarchive_impl() in cclgNgf3.o
      boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::~text_oarchive_impl() in cclgNgf3.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

#include <boost/archive/text_oarchive.hpp>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
    boost::archive::text_oarchive oa{cout};
    return 0;
}

On the off chance that it might be relevant when compiling with macOS clang compiler by invoking "g++ -lboost_serialization test.cc" a following error message is printed.
test.cc:8:32: error: no matching constructor for initialization of 'boost::archive::text_oarchive'
        boost::archive::text_oarchive oa{cout};
                                      ^
/usr/local/include/boost/archive/text_oarchive.hpp:98:28: note: candidate constructor (the implicit copy constructor) not viable: requires 1
      argument, but 0 were provided
class BOOST_SYMBOL_VISIBLE text_oarchive :
                           ^
/usr/local/include/boost/archive/text_oarchive.hpp:102:5: note: candidate constructor not viable: requires at least argument 'os_', but no arguments
      were provided
    text_oarchive(std::ostream & os_, unsigned int flags = 0) :
    ^
test.cc:8:34: error: expected ';' at end of declaration
        boost::archive::text_oarchive oa{cout};
                                        ^
                                        ;
2 errors generated.

A: I built boost manually using gcc instead of clang and now it works. It would appear the brew version is built with clang and so then when I try to build my project using gcc we get the conflicts of standard libraries.


text:
Q: NodeJS botbuilder SDKv4 How can I store the values of the user input? For example I've created this dialog and I want to create an email and in the same time store them in a DB, but I am not sure where to add the functions.
Thanks
Constructor:
constructor(conversationState) {

        this.dialogStateAccessor = conversationState.createProperty(DIALOG_STATE_ACCESSOR);
        this.holidayAccessor = conversationState.createProperty(HOLIDAY_ACCESSOR);
        this.conversationState = conversationState;

        this.dialogSet = new DialogSet(this.dialogStateAccessor);
        this.dialogSet.add(new ChoicePrompt(MONTH_PROMPT));
        this.dialogSet.add(new ChoicePrompt(START_DATE_PROMPT));
        this.dialogSet.add(new ChoicePrompt(END_DATE_PROMPT));

        this.dialogSet.add(new WaterfallDialog(HOLIDAY_DIALOG, [
            this.promptForMonth.bind(this),
            this.promptForstartDate.bind(this),
            this.promptForendDate.bind(this),
        ]));
    }

TurnContext:
case ActivityTypes.Message:
                const holiday = await this.holidayAccessor.get(turnContext, null);

                const dc = await this.dialogSet.createContext(turnContext);

                if (!dc.activeDialog) {
                    if (!holiday) {
                        await dc.beginDialog(HOLIDAY_DIALOG);
                    }
                    else {
                        await turnContext.sendActivity(
                            `An email was sent to your manager for approval`);
                    }
                }

A: To start, you need to create and pass the userState store in your index.js file first.
const { ConversationState, MemoryStorage, UserState } = require('botbuilder');

[...]

const conversationState = new ConversationState(memoryStorage);
const memoryStorage = new MemoryStorage();
const userState = new UserState(memoryStorage);

[...]

const bot = new ExampleBot(conversationState, userState);

In your bot.js file, include and instantiate userState and assign a user profile:
class ExampleBot {
    constructor(conversationState, userState) {
    [...]

    const USER_PROFILE = 'userProfile';
    this.userProfile = userState.createProperty(USER_PROFILE);
    this.userState = userState;

    [...]
}

Now you can access the userState. You can do so as part of the OnTurn:
async onTurn(turnContext) {
    if (turnContext.activity.type === ActivityTypes.Message) {
        const userProfile = await this.userProfile.get(turnContext, {});
        const conversationData = await this.conversationData.get(
            turnContext, { promptedForUserName: false });
        if (!userProfile.name) {
            if (conversationData.promptedForUserName) {
                userProfile.name = turnContext.activity.text;
                await turnContext.sendActivity(`Thanks ${userProfile.name}.`);
                conversationData.promptedForUserName = false;
            } else {
                await turnContext.sendActivity('What is your name?');
                conversationData.promptedForUserName = true;
            }
            await this.userProfile.set(turnContext, userProfile);
            await this.userState.saveChanges(turnContext);
        }
    }
}

Or as part of the waterfall / step:
async someWaterfallStep(step) {
        const user = await this.userProfile.get(step.context, {});

        if (!user.name) {
            [do something]
        } else {
            await step.context.sendActivity(`Hello ${user.name}. Nice to meet you!`);
            return step.endDialog()
        }
    }

You can read more about setting user state in this doc.
Hope of help!


text:
Q: Error running flutter app in both Android studio and Xcode I am facing this issue after I have switched from beta channel to master and whenever I try to run my Flutter application in either android studio or Xcode I get this error:
2018-09-20 15:18:16.711602+0100 Runner[7370:3358571] ../../third_party/dart/runtime/vm/kernel_binary.cc: 39: error: Invalid kernel binary format version (found 5, expected 7)
2018-09-20 15:18:16.711665+0100 Runner[7370:3358571] Dumping native stack trace for thread 9e03
2018-09-20 15:18:16.735476+0100 Runner[7370:3358571]   [0x00000001056f5d64] dart::Profiler::DumpStackTrace(void*)
2018-09-20 15:18:16.735963+0100 Runner[7370:3358571]   [0x00000001056f5d64] dart::Profiler::DumpStackTrace(void*)
2018-09-20 15:18:16.736001+0100 Runner[7370:3358571]   [0x0000000000000000] Unknown symbol
2018-09-20 15:18:16.737556+0100 Runner[7370:3358571]   [0x00000001055f7378] dart::kernel::Program::ReadFromBuffer(unsigned char const*, long, bool)
2018-09-20 15:18:16.737589+0100 Runner[7370:3358571] -- End of DumpStackTrace

This is my flutter doctor:
    [✓] Flutter (Channel master, v0.9.3-pre.3, on Mac OS X 10.13.4 17E199, locale en-GB)
    • Flutter version 0.9.3-pre.3 at /Users/heyab/flutter
    • Framework revision 8b5af14f24 (17 hours ago), 2018-09-19 15:42:51 -0700
    • Engine revision 2e8e96fad1
    • Dart version 2.1.0-dev.4.0.flutter-4eb879133a

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at ....
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 9.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 9.4.1, Build version 9F2000
    • ios-deploy 1.9.2
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 24.2.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)

[✓] Connected devices (2 available)

• No issues found!

Can anyone help me please?

A: I have managed to fix this issue: by going to Build Phases -> Run Script and add:
/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
 and then untick "run script only when installing" -> Code Cleanup -> Build Project -> And perfectly working now! :)


text:
Q: Javascript toString quirk Suppose I have a simple function defined that does nothing:  function fn() { }
Now, when I run toString(fn) I get "[object Object]".  When I run toString.call(fn) I get "[object Function]".  Does anyone know why I get a more specific type when using the call method?
EDIT: This behavior is exhibited in FireFox run through FireBug console. Both toString.constructor and toString.call.constructor yield "Function()".

A: toString doesn't accept arguments, so toString(fn) is the same as just toString(), which returns an implicit global object, converted to string. toString.call(fn) calls global.toString passing function object as this, but since global.toString is a method of Object, the result is different from Function.toString.


text:
Q: Rasterio projection woes converting raster to vectorized GeoJSON polygons using GDAL and OGR Can anyone explain what I am doing wrong here: why my latitude coordinates are erroneously offset by about 20 miles when I go through this procedure:

*

*I create a raster called map_dataset using rasterio from a bitmask with
transform = from_origin(map_dataset.bounds.left, map_dataset.bounds.top, 0.1396038590137322899, 0.1396038590755779296) and proj4 = "+proj=merc  a=6378137 =b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs"

*I check this renders correctly in QGIS (I have to manually set the CRS to EPSG:3857 to display it correctly).

*I polygonize the raster with gdal_polygonize.py -b 1 -f 'ESRI Shapefile' {infile} {outfile}  ".format(infile=f,outfile='scene_data/sun/polygonize.shp' This produces shapefiles that, again, render correctly in QGIS.

*I need GeoJSON (latitude and longitude coords, not Mercator) so I convert the shapefiles to geojson using ogr2ogr -f GeoJSON  -t_srs 'EPSG:4326' {outfile} {infile}
This produces a geoJSON file with "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, BUT that latitudes are all displaced by about 20 miles north.
NOTE: if I use QGIS to export the shapefie to GeoJSON, it renders correctly. There is a difference in the data: QGIS exports the GeoJSON as MultiPolygons, ogr2ogr2 exports the features as Polygons. The CRS is the same urn:ogc:def:crs:OGC:1.3:CRS84
UPDATE
Adding -s_srs epsg:3857 works as suggested by @user30184. But something is wrong with the projection metadata produced by my rasterio file:
GDALINFO reports the following on the file created by rasterio:
Driver: GTiff/GeoTIFF
Files: scene_data/sun/sunlight_wk_25_dt_2021-06-25_day_hrs_14.96.tif
Size is 512, 512
Coordinate System is:
PROJCRS["unnamed",
    BASEGEOGCRS["unnamed ellipse",
        DATUM["unknown",
            ELLIPSOID["unnamed",6378137,298.257223563,
                LENGTHUNIT["metre",1,
                    ID["EPSG",9001]]]],
        PRIMEM["Greenwich",0,
            ANGLEUNIT["degree",0.0174532925199433,
                ID["EPSG",9122]]]],
    CONVERSION["unnamed",
        METHOD["Mercator (variant B)",
            ID["EPSG",9805]],
        PARAMETER["Latitude of 1st standard parallel",0,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8823]],
        PARAMETER["Longitude of natural origin",0,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8802]],
        PARAMETER["False easting",0,
            LENGTHUNIT["metre",1],
            ID["EPSG",8806]],
        PARAMETER["False northing",0,
            LENGTHUNIT["metre",1],
            ID["EPSG",8807]]],
    CS[Cartesian,2],
        AXIS["easting",east,
            ORDER[1],
            LENGTHUNIT["metre",1,
                ID["EPSG",9001]]],
        AXIS["northing",north,
            ORDER[2],
            LENGTHUNIT["metre",1,
                ID["EPSG",9001]]]]
Data axis to CRS axis mapping: 1,2
Origin = (-11682237.240229927003384,4808566.985907219350338)
Pixel Size = (0.139603859013732,-0.139603859075578)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (-11682237.240, 4808566.986) (104d56'35.96"W, 39d47'35.10"N)
Lower Left  (-11682237.240, 4808495.509) (104d56'35.96"W, 39d47'33.32"N)
Upper Right (-11682165.763, 4808566.986) (104d56'33.65"W, 39d47'35.10"N)
Lower Right (-11682165.763, 4808495.509) (104d56'33.65"W, 39d47'33.32"N)
Center      (-11682201.502, 4808531.247) (104d56'34.81"W, 39d47'34.21"N)
Band 1 Block=512x2 Type=Float64, ColorInterp=Gray

Here is the code that creates that tif:
proj4 = "+proj=merc  a=6378137 =b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs"
new_dataset = rasterio.open(
    f, 'w',
    driver='GTiff',
    height=day_shade.shape[0], width=day_shade.shape[1],
    count=1, dtype=str(day_shade.dtype),
    crs=proj4,
    transform=transform)
new_dataset.write(day_shade, 1)


text:
Q: Compact integral operator on $L^\infty(\mathbb{R})$ Consider the following operator  $\mathcal{L}: L^\infty(\mathbb{R})\rightarrow L^\infty(\mathbb{R})$:
$$
\mathcal{L}v\equiv \int_{-\infty}^{\infty} K(x,y)v(y)dy.
$$
Is this a compact operator if $K\in L^1(\mathbb{R}^2)\cap L^2(\mathbb{R}^2)\cap L^\infty(\mathbb{R}^2)$? My particular $K$ is bounded and decays exponentially fast for large $x$ and $y$.
If not, what kind of $K$ would make it compact?
If the answer is yes, does that mean it is compact on $L^\infty(\mathbb{R}^2)\cap L^2(\mathbb{R}^2)$, which is really the space I am interested in right now.
Frankly, on the one hand, I am not sure how to tackle that. On the other hand, this must be a well-known result, which I cannot find. I found this question, which almost answers:
Integral operator on $L^p$ is compact

A: In $L^1$ and $L^\infty$, information about the magnitude of the kernel (the exponential decay stated in the question) isn't enough to establish compactness: some kind of uniformity is also needed. For the operator described:
Assume that there is a constant $M$ such that for almost all $x\in\mathbb{R}$, $K(x,\cdot)\in L^1(\mathbb{R})$ and $\|K(x,\cdot)\|_1\leq M$ (that's a sufficient condition for boundeness of the operator on $L^\infty(\mathbb{R})$). Then the operator is compact iff for any $\varepsilon>0$ there exist $\delta>0$ and $R>0$ such that for a.a. $x\in\mathbb{R}$ and all $h\in(-\delta,\delta)$ we have
$$\int_{\mathbb{R}\setminus(-R,R)}|K(x,y)|\mathrm{d}y<\varepsilon\tag{1}$$
and
$$\int_{\mathbb{R}}|K(x,y+h)-K(x,y)|\mathrm{d}y<\varepsilon\tag{2}$$
These two conditions on cross-sections through the kernel require (1) uniform decay at $\pm\infty$ and (2) uniform continuity of translation.
See my paper in Proc. Amer. Math. Soc. 123 (1995), 3709-3716 for details.
On $L^\infty\cap L^2$, presumably the intended norm is the sum, maximum or similar of the $L^2$ and $L^\infty$ norms? If so, a straightforward subsequence argument shows that any kernel that gives rise to a compact operator on $L^2$ and a compact operator on $L^\infty$ will give rise to a compact operator on the intersection. The Hilbert-Schmidt condition should be enough for $L^2$ compactness in this instance.

A: If $K \in L^2(\mathbb{R}^2)$ then this is a compact hilbert-schimdt operator, as stated in wikipedia: Hilbert–Schmidt integral operator.
You can show it is compact if you approximate $K$ with polynomials.

A: I found this paper, which gives the necessary and sufficient condition on $K$ for the operator to be compact in Corollary 5.1 at the end:
S. P. Eveson, Compactness Criteria for Integral Operators in $L^\infty$ and $L^1$ Spaces, Proceedings of the American Mathematical Society 123, 1995, 3709-3716.
https://www.ams.org/journals/proc/1995-123-12/S0002-9939-1995-1291766-8/S0002-9939-1995-1291766-8.pdf


text:
Q: WebView shows blank screen the second time? I am currently working on an app that loads https://web.whatsapp.com/ whatsapp for web in desktop mode in Android WebView.
It is working fine on lollipop version but above those i.e. API 23 and above (marshmallow and above) the app loads the website only once and if the reload button is pressed it just shows a blank screen !
Here is the code working fine on android API level 21 BUT NOT ABOVE IT please help !!
public class Main_web_view_frag extends android.support.v4.app.Fragment
{

 public WebView Assignment_webView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View slide_view = inflater.inflate(R.layout.assignment_main_webview, container, false);

        Assignment_webView = (WebView)slide_view.findViewById(R.id.webView);

        Assignment_webView.getSettings().setJavaScriptEnabled(true);
        Assignment_webView.setWebViewClient(new My_web_Browser());
        Assignment_webView.loadUrl("https://web.whatsapp.com/");
        setDesktopMode(true);

        return slide_view;
    }

    private class My_web_Browser extends WebViewClient
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
             return true;
        }
    }

    public void setDesktopMode(final boolean enabled)
    {
        final WebSettings Assignment_webSettings = Assignment_webView.getSettings();

         String new_Assign_UserAgent;

        if (enabled)
        {
            new_Assign_UserAgent = Assignment_webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android", "diordnA");
        }
        else
        {
            new_Assign_UserAgent = Assignment_webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA", "Android");
        }

        Assignment_webSettings.getJavaScriptEnabled();
        Assignment_webSettings.setUserAgentString(new_Assign_UserAgent);

        Assignment_webSettings.setUseWideViewPort(true);
        Assignment_webSettings.setLoadWithOverviewMode(true);
        Assignment_webSettings.setSupportZoom(enabled);
        Assignment_webSettings.setBuiltInZoomControls(true);
        Assignment_webSettings.getJavaScriptCanOpenWindowsAutomatically();
        Assignment_webSettings.setDisplayZoomControls(false);

        Assignment_webSettings.setDatabaseEnabled(true);
        Assignment_webSettings.setDomStorageEnabled(true);
        Assignment_webSettings.setAllowFileAccess(true);
        Assignment_webSettings.setAppCacheEnabled(true);

        Assignment_webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        Assignment_webSettings.setAppCachePath(getActivity().getApplicationContext().getCacheDir().getPath());

        String appCachePath = getActivity().getCacheDir().getAbsolutePath();
        Assignment_webSettings.setAppCachePath(appCachePath);
    }

}

A: Finally got a solution !! You just need to add a useragent string to your webview to act like chrome or any other web browser.
yourWebView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");


text:
Q: Installing MPI for Windows I am trying to install MPI for Windows 8, so when I searched net I got steps for installing it on XP/7 but not for windows 8. The link is: http://swash.sourceforge.net/online_doc/swashimp/node9.html
But firstly when I have to allow mpi.exe and smpd.exe to communicate through firewall these exe files are not listed.
Secondly, when I run cmd(as administrator) and type : "smpd -install",
it says : "Unknown option: -install". I  guess the command for windows 8 is something else.
So I will be really grateful if anyone helps with it because I'm not able to proceed further.

A: Side note before I start, MPI is a standard, not a library that you install. MPICH, Open MPI, Intel MPI, MS-MPI, etc. are all implementations of that standard. When you say you're trying to do X with MPI and you're asking for help, mention which implementation (and version) you're using.
Based on your question, I'm assuming that you're trying to install MPICH, though which version is unclear. MPICH hasn't supported Windows since version 1.4.1p and even that version doesn't have any support from the MPICH team anymore as all of the Windows experts are now gone. I'd suggest that you take a look at one of the implementations that do currently support Windows. The only two I know of are MS-MPI (free) and Intel MPI (paid - Update: Now free for most users), though there are probably others out there that I don't know about. If you still have trouble after trying one of those implementations, they have their own support teams that can help you with your problem.

A: I am not sure which version of MSMPI you were talking about but here is the webpage you should download the latest MSMPI which also supports Win 8.1.
You just need to double click and follow the instructions of installer.


text:
Q: Why is my JavaScript Code not playing Music? I want that my buttons ( Home, About, Blog ) on my website plays some sound or music when someone is clicking on them. Now I tried and tried, but cant find out the error in the javascript code.
<body onload="htmlIsReady()">
<script type="text/javascript">

var audio;

var audioLink;

window.onmessage = function(event)  {
if (event.data.data) {
//Passes the audio url to the new variable
    audioLink = event.data.data;
//Created a new audio object with the received audio url
audio = new Audio('URL of AUDIO-FILE');
                }
            };

function htmlIsReady() {
window.parent.postMessage("html_is_ready", "*");
 }

//Funcion that plays the audio
function playAudio() {
 audio.play.play();
 }

</script>

 // Button that executes the function that plays the audio everytime it's
 clicked
 <button class="button" onclick="playAudio()">Play</button>

 </body>

A: You're using audio.play.play(), which should be: audio.play(). However, you also haven't provided any actual proper URL/relative filepath as the audio source and at the moment your audio variable is never actually assigned as a new Audio.

A: It's not too clear why you're using window.onmessage to obtain the url of the audio file but it won't work no matter what because event.data.data is simply wrong. To obtain the data of a posted message you have to use event.data.
Furthermore here you're assigning the data to a variable called audioLink
audioLink = event.data.data;

but don't actually use it for the instantiation of your HtmlAudioElement audio.
Lastly, audio.play.play(); is wrong. To start playback you simply use the play() method on the audio object - audio.play().
Here's a working example:

var audio;
var audioLink;

function playAudio() {
  audio.play();
}

window.onmessage = function(event) {
  if (event.data) {
    audioLink = event.data;
    audio = new Audio(audioLink);
  }
};

window.postMessage("https://www.w3schools.com/tags/horse.ogg", "*");
<button class="button" onclick="playAudio()">Play</button>


text:
Q: why doesn't this php work with google maps? I'm trying to figure out why this PHP script isn't creating the map I specify in the HTML. any ideas?
<!doctype html>

        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

        <?php
            $lat = $_POST['lat'];
            $long = $_POST['long'];

            echo "

A: Your options declaration syntax is messed up:
var options = {
    zoom: 5,
    center: latlng,
    mapTypeId = google.maps.MapTypeId.TERRAIN // ERROR
};

Should be
var options = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
};

A: You also missing a bracket on the google js link.

A: I don't use PHP so I can't tell if there's anything wrong with that code.  If you removed the PHP and hardcoded lat/lon values, does the map work?  Maybe one problem could be just what values the form is posting with the latitude and longitude.  You're not doing any sort of validation to ensure they are within acceptable bounds, e.g. +90 to -90 for latitude and +180 to -180 for longitude.


text:
Q: Debugging Redisson Subscribe Timeouts I am using Redisson 3.8.2 to connect to a replicated AWS elasticache, after a while of operation my client frequently gets timeout exceptions trying to subscribe to topics.
I've checked the load on AWS and the load on my client, AWS is barely above idle and the client has far fewer subscriptions than it should be able to support (subscriber pool * subscriptions per connection).
I have tried adjusting the subscription connection pool and subscribers per connections settings but still get the issue.
The exception is thrown at a high level, timing out waiting for the Redisson promise to sync, looking through the detail code behind the promise there is a lot happening involving at least 2 locks in the java code and async futures to subscribe and attach the listener.
Is there a way I can get more debugging information from Redisson about where is it timing out / what stage it is getting to and when it fails seeing what the state of the connection pools and the connection entries are?
org.redisson.client.RedisTimeoutException: Subscribe timeout: (7500ms)
at org.redisson.command.CommandAsyncService.syncSubscription(CommandAsyncService.java:142) ~[redisson-3.8.2.jar!/:na]
at org.redisson.RedissonTopic.addListener(RedissonTopic.java:133) ~[redisson-3.8.2.jar!/:na]
at org.redisson.RedissonTopic.addListener(RedissonTopic.java:109) ~[redisson-3.8.2.jar!/:na]


text:
Q: Is it possible to remove the rest on the line from the string in Perl? For example,
##LATER##run ${XXXXXX}/PPPPPPP /name $DDDDD, out $DDDDD, pri 30/

I wanna index ##LATER##, leave ${XXXXXX}/PPPPPPP only, and remove everything from /name to end of line.
Is it possible to do it on perl?

A: echo $yourstring|perl -pe 's/ \/name.*//'

test

A: How about this:
my $str = '##LATER##run ${XXXXXX}/PPPPPPP /name $DDDDD, out $DDDDD, pri 30/';
my ($f1, $f2, undef) = split / /, $str, 3;

suppose there is no blank character in XXXXXX.


text:
Q: Is possible to use query builder in form, filtering by other table/field value? Let's say I have two entities: A and B. These entities have a unidirectional relationship. In particular external key is into B entity and, based on the cardinality of relationship, A hasn't any "direct" attribute (property) for retrieve B objects.
Ok, now let's say I want to build a form for some B objects.
In my FormType I will do something like:
public function BuildForm(FormBuilderInterface $builder)
{
  [...]
  $builder->add('A',entity,array('class'=>'MyFooBundle:A'));
  [...]
}

Ok, now let's say I want to apply a "filter" upon A dropdown list and this filter is particular: I don't want to show any A entity that has already a relationship with B.
To me this is very tricky to reach as I know that I can use a closure and query_builder option but the problem is that query_builder, as far as I know, use class of the field to do the query. What I've tried is something like
$sub_query = $repo->createQueryBuilder('B');
$sub_query = $sub_query->select('B.A')
               ->from('MyFooBundle:B','b');

$qb = $repo->createQueryBuilder('A');

return $qb->where($qb->expr()->notIn('A.id', $sub_query->getDQL()));

Of course B.A returns the corrispective of A.id (foreign key contained in B)
However $sub_query still try to use even A into that select (as class of attribute where query_builder is applied is A)
So, coming to real question, is there an equivalent method for do what I need or "simply" have I to make this relationship bi-directional and use directly attribute included into A class?
Hope is clear

A: Base on the type of relationship which is OneToOne and A side is nullable, you can make a DQL as:
$qb = $repo->createQueryBuilder('A')
   ->leftJoin('YourBundle:BEntity', 'B', 'WITH', 'A.id = B.A_id')
   ->where('B.id IS NULL')
   ->getQuery();
$result = $qb->getResult();

The created DQL means, select all A records join with B where the B.id does not exist in A

A: Here's my example, hope that will help.
$builder->add("parent", 'entity', $this->getParentUserEntityOptions());

private function getParentUserEntityOptions() {
    return array('empty_value' => 'Select',
        'class' => 'TMSolution\UserBundle\Entity\User',
        'property' => 'username',
        'query_builder' => function(\Doctrine\ORM\EntityRepository $er ) {
    return $er->createQueryBuilder('u')
                    ->orderBy('u.id', 'ASC')
                    ->where('u.locked = 0');
    });
}


text:
Q: 530 USer cannot log in when trying to access site folder via FTP I try to log in to my Windows 2012 server via FTP:
Command:    USER ftp_*****
Response:   331 Password required
Command:    PASS **********
Response:   530 User cannot log in.
Error:  Critical error: Could not connect to server

The FTP is connected via port 22. Using FileZilla.
What I've checked:

*

*Port is open on the server

*I have entered the right username and password

*Checked Active and Passive, doesn't solve the problem

*I gave read write permission for that FTP site

*I opened the TCP port 22 in Windows firewall for outbound connections

*I've given the ftp user permission on the website folder (full permissions)

What else I can do?

A: Another FTP site was listening on the same port. I just stopped it and the other one worked.


text:
Q: What else can i do 'sleep' when the sleep() can't work well with alarm? There are many documents say "you should avoid using sleep with alarm, since many systems use alarm for the sleep implementation". And actually, I'm suffering with this problem.
So does anyone can help me that what else i can do 'sleep' when the sleep() can't work well with alarm? I have already tried 'usleep' of the Time::HiRes module, and select() function. But they didn't work either.

A: Seeing as you're being interrupted by alarms, and so can't reliably use sleep() or select(), I suggest using Time::HiRes::gettimeofday in combination with select().
Here's some code that I've not tested.  It should resist being interrupted by signals, and will sleep for the desired number of seconds plus up to 0.1 seconds.  If you're willing to burn more CPU cycles doing nothing productive, you can make the resolution much better:
...
alarm_resistant_sleep(5); # sleep for 5 seconds, no matter what
...

use Time::HiRes;

sub alarm_resistant_sleep {
  my $end = Time::HiRes::time() + shift();
  for (;;) {
    my $delta = $end - Time::HiRes::time();
    last if $delta <= 0;
    select(undef, undef, undef, $delta);
  }
}

A: You can sleep on a new process via system:
system ( "sleep", 5 );

Or did I misunderstand the question?

A: You can try AnyEvent:
use AnyEvent;

my $cv = AnyEvent->condvar;
my $wait_one_and_a_half_seconds = AnyEvent->timer(
    after => 1.5,
    cb => sub { $cv->send }
);
# now wait till our time has come
$cv->recv;

A: When using (from MySQL forum)
use Sys::SigAction qw( set_sig_handler );
eval {
  my $hsig = set_sig_handler( 'ALRM', sub { my $canceled = 1; die; }, { mask=>[ qw( INT ALRM ) ] ,safe => 0 } );
  alarm($timeout);
  ...
  alarm(0);
}

I noticed that any subsequent calls made to sleep($delay) with $timeout shorter than $delay would end up with the script execution being terminated, and the print of "Alarm clock".
The workaround I've found is to call alarm() again but with an improbably large value (3600), and cancel that alarm right after.
eval {
  alarm(3600);
  print " .... Meeeep ....";  # Some trace
  alarm(0);
};

Then I can use sleep() with no interference anymore.
Example below (live code snippet):
sub unmesswithsleep {
  eval {
    alarm(3600);
    &tracing (8, " .... Meeeep ....");
    alarm(0);
  };
}

sub lockDBTables {
  return (0) unless ($isdbMySQLconnect);
  my $stm = qq {
    LOCK TABLES
      myBIGtable WRITE
  };

  my $timeout = 60;          # This is the timer set to protect against deadlocks. Bail out then.
  eval {
    my $h = set_sig_handler( 'ALRM', sub { my $canceled = 1; die; }, { mask=>[ qw( INT ALRM ) ] ,safe => 0 } );
    alarm($timeout);
    my $res = $dbmyh->do($stm) + 0;
    alarm(0);  # Reset alarm
  };

  if ( $@ =~ m/Die/i ) {
    $isdbTabledlocked = 0;
    &tracerr (0, "FATAL: Lock on Tables has NOT been acquired within ${timeout}s. Lock is set to <$isdbTabledlocked>.");
    &unmesswithsleep();   # MUST be called each time alarm() is used
    return (0);
  } else {
    $isdbTabledlocked = 1;
    &tracing (2, "  Good: Lock on Tables has been acquired in time. Lock is set to <$isdbTabledlocked>.");
    &unmesswithsleep();   # MUST be called each time alarm() is used
    return (1);
  }
  # Can use sleep() now.
}

A: try
print "Start\n";
select undef, undef, undef, 1;
print "End\n";

This will sleep for 1 second.

A: It sounds like your code that sleeps is being interrupted by some code that sets an alarm. This is by design so you're seeing the expected behavior. In other words an alarm *should always interrupt a sleep call.
If you're looking for a pure perl way to sleep without being interrupted by an alarm you can do this by installing your own alarm signal handler. This way when your code gets an alarm it won't interrupt your processing.
However, an important caveat is that this will delay any alarm that was set by other code. The other code will receive the alarm late; after your code completes. This means that if you want to play well with others you're better off using one of the other solutions.
Here is an example:
#!/usr/bin/perl

use POSIX;
use strict;
use warnings;

# set an alarm
print "Setting alarm\n";
alarm 1;

my $old_alarm;
my $snoozed;
{
  # store the previous alarm handler (if any)
  $old_alarm = $SIG{ALRM};

  # override the alarm handler so that we don't
  # get interrupted
  local $SIG{ALRM} = sub {
    print "got alarm; snoozing\n";

    # record the fact that we caught an alarm so that
    # we can propagate it when we're done
    $snoozed++;
  };

  # sleep for a while.
  for (1 .. 3) {
    print "z" x $_ ,"\n";
    sleep 1;
  }
}

# replace the old sleep handler;
$SIG{ALRM} = $old_alarm
 if $old_alarm;

# if we had to snooze fire an immediate alarm;
if ($snoozed) {
  POSIX::raise(POSIX::SIGALRM);
}

The documentation you reference hints at but does not describe a different symptom. The main thing you need to worry about when sleep is implemented via alarm is having your alarm reset when someone calls sleep.
*Apparently there are some versions of perl (e.g.: old Win32) where an alarm doesn't interrupt sleep.


text:
Q: Typing for dynamically generated class methods I wrote a tiny, compact, minimal logger for Python apps that are little more than slightly large scripts.  It has colors (which are very important), and allows you to define a custom level (a custom log.<level_name> and color) by just adding a new tuple to the list of levels passed to the Logger constructor.
However, since the methods are defined on the resulting class instance dynamically, Pylint in VS Code can't find the methods when I invoke them.
Is there any way, e.g. with type hints, to tell Pylint/all static-analysis tools about these methods or at least have them not worry about them?
Here's the class's source:
class Logger:
    def __init__(self, levels):
        max_level_len = max(len(l) for l, _ in levels)
        for level, color in levels:
            l = level.rjust(max_level_len)
            func = eval(f"lambda msg: print('\x1b[1m{color}{l}:{color} ' + msg + '\x1b[0m')")
            setattr(self, level, func)

Usage:
log = Logger(
    [
        ("info", "\x1b[94m"),
        ("exec", "\x1b[96m"),
        ("warning", "\x1b[93m"),
        ("error", "\x1b[91m"),
        ("critical", "\x1b[91m"),
        ("fatal", "\x1b[91m"),
        ("success", "\x1b[92m"),
        ("debug", "\x1b[95m"),
    ]
)

log.info("Test")
log.critical("Test")

A: When you say "find the methods" - you mean the log.info methods?
Thats probably because your Logger class isn't inheriting from anything, so doesn't have those methods.
Probably a better approach than what you are trying is to define a formatter. Something like this-
colors = {
    'default': 'aaaa',
    logging.DEBUG: 'bbbb',
}

class ColoredFormatter(Formatter):
  def __init__():
    super().__init__(fmt="%(levelname)s <whatever else you want>")

  def formatMessage(record):
    record.msg = f"{colors[record.level]}record.msg{colors['default']}"
    super().formatMessage(record)

handler = StreamHandler()
handler.setFormatter(ColoredFormatter)
logging.basicConfig(handlers=[handler])


text:
Q: How to cast a forwarded parameter pack? I'm replacing a printf(/*heterogenous pack of arguments*/) by LogMessage(/*arguments*/).
However, I'm getting

Error C2665   'swprintf_s': none of the 2 overloads could convert all
  the argument types

template<class ...T>
auto DwarfCuda::LogMessage(T&&... args) -> void
{
    wchar_t updatedMessage[256];
    swprintf_s(updatedMessage, forward<T>(args)...); //C2665
    if (LogMessageChangedCallback != nullptr)
        LogMessageChangedCallback(updatedMessage);
}

It works for many examples but not with this one:
LogMessage( " GPU Max Clock rate: %.0f MHz (%0.2f GHz)\n",
    deviceProp.clockRate * 1e-3f, deviceProp.clockRate * 1e-6f);

Why can't this work (shouldn't the cast happen in the first place) ? How to do this correctly ?

A: The problem was in the call of LogMessage: the format string must be a wstring, hence the absence of L in L" GPU Max Clock rate: %.0f MHz (%0.2f GHz)\n" triggered the bug.


text:
Q: Scheduling a meeting of N people Problem: There are N people and S slots. Each person has a list of slots in which he is busy.
We have to find an algo to find a slot in which all of them are free.
I already know an algo whose complexity is O(NS). Need a better algo.
You are free to maintain different data-structures dynamically (they will be updated whenever a meeting is scheduled) which can be used to finally find a free slot.

A: Keep a slotcounter for each slot. for each persons busy slot add one to that slots slotcounter; for all peoples busy slots.
Any slotcounter which is still zero after accounting for all peoples busy slots is a a counter for a slot in which all people are free. Probably an O(k) algorithm.
Instead of counting you could set up a bitmask/bitset where person N's bitmask has bit S set in all positions where they are busy. A bitwise OR of all the peoples bitmasks will have zero bits corresponding to all the free slots.
UPDATE:
The way you state the problem, you don't have to track the people just keep an array of slot occupancy indicators. Initially all are marked free; as you go through each persons busy slots mark the appropriate occupancy indicator as busy. When you are done, any of the arrays indicators that are still free is your answer.

A: Edit:
Algo will work assuming we have a sorted list of slots for each person

*

*Now you have N-lists of size S (maximum) each. Merge sort this list: http://en.wikipedia.org/wiki/Merge_algorithm

*Typical merge sort (using heap) will result in complexity NlogK, where N is the total # of elemets in all 'K' lists. However, if your version, each element in the N-lists are bounded to be between 0 and s-1. Therefore, the complexity is also bounded by S*log(N). Iterating through the N-lists with a heap size of maximum 'N', bounded by S-iterations. Makes sense?

So, overall complexity = N*log(S) + S*log(N)
This is assuming the original list is sorted, else complexity goes up to N(SlogS)

A: Generate a bitmask of size S with the bits set for when S is busy. Bitwise OR all bitmasks together, then extract the bit that isn't set.

A: Bearing in mind that there might well not be a solution, the Hungarian Algorithm will provide the closest answer


text:
Q: Responsive jQuery Function The below script I am using is currently working when it comes to calling the jQuery when it hits a specific screen size. However, my window.onmousemove event is no longer working. When you hover over #hwdo-panel ul li the div .show-info will follow my cursor within the div. But when I add if ($(window).width() < 992){ to the script the div no longer follows my cursor. When I am trying to achieve is on screens higher then 992 call the window.onmousemove script and anything lower then 992 display .show-info on its own. What am I doing wrong with my below script?
if ($(window).width() < 992){
  $('#hwdo-panel ul li').hover(function(e){
   var figure = $(this).find('.show-info');
    if(figure){
        window.onmousemove = function (e) {
            var x = e.pageX,
                  y = e.pageY;
            figure.offset({ top: (y + 0), left: (x + 50)});
        }
    }
 });
}

HTML

Details

this is a test

Passion

this is a test

Courage

this is a test

Care

this is a test

CSS
 #hwdo-panel {
     position: relative;

ul {
    font-weight: 900;
    list-style: none;
    margin: 0;
    padding: 0;

    &:hover > li {
        opacity:0.1;
    }

    li {
        border-bottom: 2px solid #FFF;
        margin-bottom: 1em;
        -webkit-transition:0.5s;
                      transition:0.5s;

        &:hover{
            opacity:1;
        }

        &:last-child {
            border-bottom: none;
        }

        &:hover .show-info {
            display: block;
        }

        .show-info {
            display: block;
            top: 0;
            left: 0;
            position: relative;
            padding: 1em 0 1em 0;
            font-weight: 500;
            width: 100%;

            @media (min-width:992px) {
                display: none;
                top: 0;
                left: 0;
                position: absolute;
                background: var(--pink);
                padding: 2em;
                font-weight: 500;
                width: 30%;
                z-index: 90;
            }
        }

        h3 {
            position: relative;
            color: transparent;
            text-transform: uppercase;
            -webkit-text-stroke-width: 2px;
            -webkit-text-stroke-color: white;
            display: inline-block;
            width: 100%;
            letter-spacing: 5px;
            cursor: pointer;

            &:before {
                overflow: hidden;
                position: absolute;
                top: 0;
                left: 0;
                width: 0;
                color: var(--pink);
                content: attr(data-hover);
            }

            &:hover:before {
                width: 100%;
                transition: all 3s cubic-bezier(0.17, 0.67, 0.32, 0.87);
            }

            &:after {
                content: '+';
                position: relative;
                float: right;
                font-size: .5em;
                color: var(--white);
                -webkit-text-stroke-width: 0px;
                -webkit-text-stroke-color: transparent;
                font-weight: 500;
            }
            &:hover:after {
                color: var(--pink);
            }
        }
    }
}
}

Example

A: Right now you're only instantiating the hover handler if the window starts out at the right size, it won't update if the window resizes.  And the nested handlers means you're instantiating a new mousemove handler every time the hover state changes.
Instead, you can leave a single mousemove handler running all the time, and check the window size inside it.  Conveniently the hover state can be detected using CSS selectors, so you can skip needing to worry about specifically watching the hover events.
This is untested but should be close:
window.onmousemove = e => {
  // handle your window size check inside the mousemove handler:
  if ($(window).width() > 991) return;

  // use a CSS selector to detect the hover state:
  let figure = $('#hwdo-panel ul li:hover .show-info');

  // now do your positioning
  if (figure) {
    figure[0].offset({
      top: e.pageY,
      left: e.pageX
    })
  }
}


text:
Q: Who designs databases in web development? In the context of web development, who designs databases? Despite a whole host of information associating back-end web dev with server-side processing, data modeling, and the like, the database design aspect of the equation seems to be mysteriously absent.
I am not talking about who sets up the physical database, I'm referring to who designs the logical model of the database, conducts user-story interviews to get information on what fields are needed, what those field specifications are, and etc...
I've realized that the (PROPER) design of a database is no small task (I'm reading this 672 pager) and could easily be an entire profession. However, searching up and down the internet has led to surprisingly little results for who is expected to handle this task in the context of web dev.

A: It depends what is the database used for.
In many applications (web apps or not), the database is intimately tied to that application because it serves as the persistent store for it. Then the database is conceptually part of the application so is designed together (and you presume that no other program would significantly access or update that database). BTW, persistence could be achieved by other means than a database, e.g. plain textual files, binary files (notably indexed files à la GDBM), git (or other VCS) repositories, directories or file trees, raw disk partitions, dedicated hardware (e.g. flash), remote file systems, checkpointing techniques. For databases designed for and with one application, you should care about common retrieval & update patterns and design the database schema (and indexing!) with them in mind.
In some situations the database is by itself a major and independent asset, and is designed a priori to be used by several different applications (and even future ones). Then it should be designed independently (and much more carefully).
In particular some web apps are just web interfaces to existing databases.
In many cases (think of some wiki as an example), the data is more important and more valuable than the application(s) using it. You may care about how to make it future proof and be able to evolve it easily (e.g. by using or defining textual & versatile -preferably standardized and documented- formats to backup and restore it).

I've realized that the (PROPER) design of a database is no small task...

Read also about NoSQL, document-oriented databases, key-value databases, knowledge management, knowledge representation and reasoning, ontologies, expert systems, business rules approach, ERP, CMS. Perhaps consider using REDIS, MongoDB, etc..

A: Your question is not only pertinent to webapps, but to all kinds of apps that use a database backend.
In my experience

*

*The design of the database is the combined work of developers and DBAs.

*Developers make rough, or often very good, database designs. It all depends on the experience of the programmers.

*Often developers create tables in their development database and a conceptual model is reverse-engineered from it.

*Often conceptual ER diagrams are discussed with other team members, often clients. In this stage obvious conceptual errors are detected and hopefully figured out and fixed.

*The DBA's work is to review such a design, and fine-tune it to detect violations of normal forms.

*Also the DBA enforces naming conventions of tables and columns

*Also the DBA envisions possible performance bottlenecks and tries to understand how the data will be queried in order to create appropriate indexes later.

*The revisions/checking/fixing cycle between developer/app designer and DBAs goes through several iterations until the model is mature enough to generate a physical model.

*Usually a database design tool is used in all but very small databases to help this process.

Bottom-line:

*

*Developers know the business and problem domain better than DBAs, so they very much do most of the initial design and, depending on the experience of the developer such a design can be very close to the final design.

*The DBA's role is mostly to ensure NF, naming conventions, performance considerations, to correct obvious errors and finally to generate a physical model, then a database specific script, and to run these to create the database.

*I'd say it's 80% developer and requirement analysis work and 20% DBA work.
UPDATE:
There are 3 kinds of DBAs:

*

*development DBAs that know data-modeling, are SQL experts and can write stored procedures, they usually are former developers;

*production DBAs that specialize in installing, performance tunning, backups and restoring, etc.,

*and jack-of-all-trades DBAs that have worked doing all those things and as such can do most (they are very few).

Most DBAs are production DBAs, which is good beause they are the guys who recover lost databases from failed disk arrays in the wee hours of the night. But they don't participate actively in the design process.


text:
Q: How do I populate a dropdown value on a webpage that will enable another dropdown for web automation via Javascript For RPA, I am trying to use Javascript to set a value in dropdown (A) which will enable dropdown(B). I can set the value of the dropdown (A), however it doesn't enable dropdown (B).
Is there something else I need to do, for it to recognize that I set the value in dropdown (A) and it should enable dropdown (B)?
Here is what I am using to set the value in dropdown (A):
function ExecuteScript()
{
document.querySelector('selector').value="value";
}


text:
Q: Matrices with unknown elements Now trying to solve matrices.
If
$$A = \left[\begin{array}{rrr}
-1&b\\
c&-1\\\end{array}\right]$$
What are the elements b and c so that $$A^{2}=2A^{T}$$
How to solve this kind of exercise? What are the step by step instructions for this kind of exercise?

A: Hint
$1)$ $A^2=A\cdot A$
$2)$ $A^T = \left[\begin{array}{rrr}
-1&c\\
b&-1\\\end{array}\right]$
$3)$ $2A^T = \left[\begin{array}{rrr}
-2&2c\\
2b&-2\\\end{array}\right]$

A: After you solve for both A2 and 2AT, you can set each index equal to each other and solve for b and c that way.
-2 = bc + 1
2c = -2b
And so on with all the indexes. Since each term will contain b and c, use substitution to solve for one then the other.


text:
Q: Is there a significantly faster way to buffer than arcmap? I hope this question is appropriate here and I apologize if it is more of a discussion question than a specific technical problem.
I have to buffer 150,000 polygons for a real estate project.  While it's not impossibly slow, it got me wondering about 'the fastest way to geoprocess'.
What packages, tips, or tricks could be used to make this faster?
Does anyone have an idea how arcmap, arcpy, shapely, postgres compare in performance time?
EDIT: After asking around, I heard 'arcpy is slow!' a lot.

A: You could also look at using the OGR library, it has python bindings so you could create an ArcGIS buffer tool pretty easily.
I find ArcGIS/ArcPy slow in general, so try and avoid it as much as possible.
I would also endorse using PostGIS, it eats this kind of processing for breakfast and isn't difficult to setup


text:
Q: Convert Base64 to image file with javascript Does anyone know of any simple javascript that I can use to turn a base64 string into an image (jpg format preferably), so that I can save the image to a file?  This is for a signature pad application.  I can get the signature into a base64 format, but need to save the signature as an image file to use for embedding into a Crystal Report.

A: I have tried this method in a JSP page to print the image from a base64 string, I guess this should hold good for javascript too. Do not have sample data for now to verify, but here's how I would try it.
var oImg=document.createElement("img");
var baseString = null;    //the base64 string you have
var imsc = 'data:image/jpg;base64, '+baseString;
oImg.setAttribute('src', imsc);
document.body.appendChild(oImg);


text:
Q: Scrapy crawler not processing XHR Request My spider is only crawling the first 10 pages, so I am assuming it is not entering the load more button though the Request.
I am scraping this website: http://www.t3.com/reviews.
My spider code:
import scrapy
from scrapy.conf import settings
from scrapy.http import Request
from scrapy.selector import Selector
from reviews.items import ReviewItem

class T3Spider(scrapy.Spider):
    name = "t3" #spider name to call in terminal
    allowed_domains = ['t3.com'] #the domain where the spider is allowed to crawl
    start_urls = ['http://www.t3.com/reviews'] #url from which the spider will start crawling

    def parse(self, response):
        sel = Selector(response)
        review_links = sel.xpath('//div[@id="content"]//div/div/a/@href').extract()
        for link in review_links:
            yield Request(url="http://www.t3.com"+link, callback=self.parse_review)
#if there is a load-more button:
        if sel.xpath('//*[@class="load-more"]'):
            req = Request(url=r'http://www\.t3\.com/more/reviews/latest/\d+', headers = {"Referer": "http://www.t3.com/reviews", "X-Requested-With": "XMLHttpRequest"}, callback=self.parse)
            yield req
        else:
            return

    def parse_review(self, response):
        pass #all my scraped item fields

What I am doing wrong? Sorry but I am quite new to scrapy. Thanks for your time, patience and help.

A: If you inspect the "Load More" button, you would not find any indication of how the link to load more reviews is constructed. The idea behind is rather easy - the numbers after http://www.t3.com/more/reviews/latest/ suspiciously look like a timestamp of the last loaded article. Here is how you can get it:
import calendar

from dateutil.parser import parse
import scrapy
from scrapy.http import Request

class T3Spider(scrapy.Spider):
    name = "t3"
    allowed_domains = ['t3.com']
    start_urls = ['http://www.t3.com/reviews']

    def parse(self, response):
        reviews = response.css('div.listingResult')
        for review in reviews:
            link = review.xpath("a/@href").extract()[0]
            yield Request(url="http://www.t3.com" + link, callback=self.parse_review)

        # TODO: handle exceptions here

        # extract the review date
        time = reviews[-1].xpath(".//time/@datetime").extract()[0]

        # convert a date into a timestamp
        timestamp = calendar.timegm(parse(time).timetuple())

        url = 'http://www.t3.com/more/reviews/latest/%d' % timestamp
        req = Request(url=url,
                      headers={"Referer": "http://www.t3.com/reviews", "X-Requested-With": "XMLHttpRequest"},
                      callback=self.parse)
        yield req

    def parse_review(self, response):
        print response.url

Notes:

*

*this requires dateutil module to be installed

*you should recheck the code and make sure you are getting all of the reviews without skipping any of them

*you should somehow end this "Load more" thing


text:
Q: How to add signature on a interactive pdf using adobe acrobat xi pro? How to add signature on a interactive pdf using adobe acrobat xi pro ?

A: You can find signature options in the menu pane that defaults to the right side of Acrobat. From Tools|Fill&Sign|Comment, select Fill&Sign, and then select "Place Signature" from the menu pane below it. You will be prompted to create a new signature.


text:
Q: Quantum Operators: An Identity I came across the following neat property:

For an operator $\hat{A}$ which is a linear combination of creation
  and annihilation operators, we have: $$ \langle e^{\hat{A}} \rangle = e^{\langle \hat{A^2} \rangle/2}.$$

Any help in approaching the proof of this identity would be appreciated.

A: I expect this to be a result of the Wick theorem. If you are considering an equilibrium situation with a quadratic Hamiltonian all odd moments will vanish. Thus you remain with even powers of your operator. If you now count the number of possible contractions you should get the correct result.
P.S.: I just tried and it works indeed. Note the helpful identity
$$ \frac{(2n-1)!!}{(2n)!} = \frac{1}{n! 2^n}$$
(SPOILER ALERT)
What $\left< \cdot \right>$ actually means is
$$ \left< B \right> \equiv \frac{1}{\mathcal{Z}} \text{Tr} \left\lbrace e^{- \beta H } B\right\rbrace$$
for some operator $B$, $\beta = 1/(k_B T)$, and $\mathcal{Z} = \text{Tr}\ e^{- \beta H }$. If your Hamiltonian now takes the form
$$ H = \sum_{nm} a^\dagger_n h_{nm} a_{m},$$
then you can prove the Wick theorem. Let $\alpha_m$ be either a bosonic creation or annihilation operator. I'll spare you the details but you will find that
$$\left< \alpha_1 \alpha_2 \cdots \alpha_{2n} \right> = \sum\limits_{\substack{\text{all possible} \\ \text{pairings}\ \pi}}
\left< \alpha_{\pi(1)}\alpha_{\pi(2)} \right>\cdots \left< \alpha_{\pi(2n-1)}\alpha_{\pi(2n)} \right>$$
and $\left< \alpha_1 \alpha_2 \cdots \alpha_{2n+1} \right> = 0 $. This is all you need for the proof:
$$\left< e^{A} \right> \overset{(1)}{=} \sum_{n=0}^\infty \frac{1}{n!} \left< A^n\right>
\overset{(2)}{=} \sum_{n=0}^\infty \frac{1}{(2n)!} \left< A^{2n}\right> \overset{(3)}{=} \sum_{n=0}^\infty \frac{(2n-1)!!}{(2n)!} \left< A^2\right>^n \overset{(4)}{=} \sum_{n=0}^\infty \frac{1}{n!2^n} \left< A^2\right>^n \overset{(1)}{=} e^{\left< A^2\right>/2} . $$
(1) Series expansion.
(2) All odd powers vanish.
(3) There are $(2n-1)(2n-3)(2n-5) \cdots (2n-2n) = (2n-1)!!$ ways of forming $n$ pairs of $\left<A^2 \right>$ by the means of the Wick theorem.
(4) The identity from above.
I didn't check if it holds for fermions as well. There might be a similar identity but the Wick decomposition will change.

A: Hint: OP's formula follows from a Wick-type theorem
$$ \tag{1} T(f(\hat{A})) ~=~ \exp\left(\frac{1}{2}\hat{C}\frac{\partial}{\partial\hat{A}}\frac{\partial}{\partial\hat{A}} \right):f(\hat{A}): $$
between time-ordering $T$ and normal ordering $::$. Here
$$\tag{2} \hat{C}~=~T(\hat{A}\hat{A})~-~:\hat{A}\hat{A}:$$
is a contraction. See e.g. this Phys.SE post and links therein.


text:
Q: Binding Canvas.Size to parent UserControl and then setting Canvas.Size in code I have a wpf Canvas in a grid in a UserControl named 'root' and I bind the Width and Height of the canvas as follows:
Width="{Binding ElementName=root, Path=ActualWidth}"
Height="{Binding ElementName=root, Path=ActualHeight}"

On the canvas all kinds of DrawingVisual are drawn.
In code behind I set the Width end Height of my Canvas equal to ContentBounds.Right and ContentBounds.Bottom so that every DrawingVisual that I add to the canvas will be visible.
This seems to work all right but I am confused about the binding mentioned.
This is a one-way binding from the usercontrol's actual size to the size of the canvas.
Does the setting of Width and Height in code behind overrule this binding?
When I remove the binding the canvas is displayed equally as well, but the control is also used in other places and situations and might be needed then.

A:
Does the setting of Width and Height in code behind overrule this binding?

Yes. Programmatically setting the value of a target property that has a one-way binding applied to it will clear the binding.


text:
Q: Мнение WindowsXP vs. Windows 7 Доброго времени суток. Не исключаю холивар, но, тем не менее, хотелось бы услышать ваше мнение в пользу выбора установки WindowsXP или Windows 7 на рабочий компьютер.Характеристики:Блок питания: IN-WIN IP-S450HQ7-O 450WМатеринская карта: P8H61-M LE LGA1155Процессор: Intel Core i5-2400 Sandy Bridge (3100MHz, LGA1155, L3 6144Kb)DDR: Kingston KVR1333D3N9K2 2x2 Gb DDR3 1333 МГцЗадачи, которые будут выполняться: браузерные флеш-игры, видео-захват, обработка видео.
A: WIN 7 работает намного стабильнее чем WIN XP, чем WIN VIsta.Собственно 7ка это улучшенная Vista без глюков и косяков.Работает быстрее чем XP и Vista. Более дружелюбна и нареканий за 2,5 года не вызывала.64х пашет на ура.Собственно ставь 7ку и не парься.браузерные флеш-игры, видео-захват,обработка видео.Вот тут только ты в характеристиках не указал видео, собственно для обработки видях, нужна видео нормальная, оператива и быстрый винт.


text:
Q: Substring compiles but code doesn't work When I use the code below, it compiles but the rest of the code doesn't seem to work.  When I take out the Substring part of it, it does.
-Steps
String theDate, theWeekDay;
if (ToTime(Time[0]) == ToTime(0, 0, 0))
{
   theDate=ToDay(Time[0]).ToString().Substring(0,3);
   theWeekDay=Time[0].DayOfWeek.ToString().Substring(4,8);
   DrawTextFixed("day",theWeekDay, TextPosition.BottomRight);
   DrawText("day"+Convert.ToString(ToDay(Time[0])),
   theWeekDay+" "+theDate,0, Low[0]-TickSize*20, Color.Blue);
}

A: You haven't given enough information to solve your problem, but if you're just trying to get the day of the week name in the abbreviated format, use this instead:
theWeekDay = Time[0].ToString("ddd");

A: Unless you have omitted part of the code, your assignment does not take place within a class definition or a method.

A: You're going to have to provide more than just this snippet of code. What is the Time object you're accessing via an indexer? Have you debugged this to see if Time[0] actually has a value? My guess here would be that Time[0] doesn't return a value that DayOfWeek can work with hence Substring(0,3) is being running against either an empty string or a null value


text:
Q: elseif not working message doesn't show `

$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);

if (!preg_match("/^\w+$/",$username)) {
    $error = true;
    $username_error = "Username cant contain space and special characters";
}
if(strlen($password) < 6) {
    $error = true;
    $password_error = "Password must be minimum of 6 characters";
}

$result = mysqli_query($connection, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");

if ($row = mysqli_fetch_array($result)) {
    $_SESSION['usr_id'] = $row['id'];
    $_SESSION['usr_name'] = $row['name'];
if ($row['id'] == 1) {
    header("Location: priv8/ididthis.php");
} else if ($row['id'] >= 1) {
    header("Location: index.php");
} else {
    $errormsg = "Incorrect username or Password!";
}

can u see what's wrong with my code ? the $errormsg doesn't showing when the username or the password is wrong..
`

Login

            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

            <input type="text" name="username" class="login-field" value="" placeholder="username" id="login-username">

            <?php if (isset($username_error)) { echo $username_error; } ?>

            <input type="password" name="password" class="login-field" value="" placeholder="password" id="login-pass">

            <?php if (isset($password_error)) { echo $password_error; } ?>

            <input class="btn btn-primary btn-large btn-block" type="submit" name="login" value="Sign in"/>

            </form>

            <?php if (isset($errormsg)) { echo $errormsg; } ?>

            Lost your password?

A: The problem is that your error message is inside this block
if ($row = mysqli_fetch_array($result)){
    if ($row['id'] == 1) {...}
    else if ($row['id'] >= 1) {...}
    else {
        $errormsg = "Incorrect username or Password!";
    }
}

This means that the error message is never shown because row id will always be 1 or >=1.  To fix, move the error message out, like this:
if ($row = mysqli_fetch_array($result)){
    if ($row['id'] == 1) {...}
    else($row['id'] >= 1) {...}
}
else {
    $errormsg = "Incorrect username or Password!";
}


text:
Q: How do we remove Salesforce Header in a Lightning Page? I want to remove Salesforce Header Tabs from a lightning page. Can we do that?

The component code is as below:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global"> body here.</aura:component>

A: You can't. It will always appear as long as you're in the Lightning Experience. If you're using a Lightning App, it wouldn't ordinarily appear.

A: You can't remove the Salesforce header from the Lightning Experience but as @sfdcfox mentioned you can create your own Lightning application with a dedicated URL.

*

*Using the Developer Console or your favorite IDE create a Lightning Application (let's call it myApp for example).

*Place your components in the myApp.app markup.

*Access your app via this url:
https://.lightning.force.com/c/myApp.app

A: Navigating to Lightning app (Standard app) does give you the full page experience, but the caveat is now you cannot use tags like e:forceeditrecord.
And using the Standalone app will do no good, as the Salesforce tabs do not go away.


text:
Q: van der pol equation Consider the van der Pol equation below:
$(x'')+a(x^2-1)(x')+(x)=0$
I need to :

*

*Find an equilibrium point and linearize this equation near it

*Find solutions of the linearized equation depending on a

A:
     $$ \frac{d^2x}{dt^2} - a(1 - x^2)\frac{dx}{dt}+ x = 0 $$
let $\frac{dx}{dt} = y $ . which yields the two dimensional first order system:
$$\frac{dx}{dt} = y $$
$$\frac{dy}{dt} = -x + a(1 - x^2)y $$
The linearized system is easy to write down in this case:
$$\frac{dx}{dt} = y $$
$$\frac{dy}{dt} = -x + ay $$
clearly (0,0) is the equilibrium point
a plot of the equation near the origin with a as parameter . (You can play around with this quite a bit). The red solution curve is the Van der Pol Equation, the blue solution curve is the linearized system. It is spiraling out from the origin , but without a limit cycle.


text: Q: Ordinal, Categorical, or Interval I have a dataset with 1 continuous variable(y),  2 categorical variables(x1, x2) and one variable that has the unique values (0,1,5,9,13) that stand for miles (x3).  I want to run a regression of y on x1, x2 and x3. I am really concerned about how to treat x3. I am guessing I can't treat it as a categorical variable because 13 miles is more than 5 miles. So would it be Ordinal or Interval? If I wanted to run a regression how does one go about doing this (conceptually)? I can run it in R once I know what I am going for.


text:
Q: Alterar `id` de elemento  javascript ou jquery Preciso alterar o id de um formulário em HTML com javascript em tempo de execução.
Estou tentando com JQuery e Javascript, mas não está funcionando.
jQuery(this).prev("form").attr("form", "form_modulo");

ou
document.getElementById('form').id = 'form_form_modulo';

Nenhum dos dois funciona, quando vou ver o código da pagina ainda está o valor antigo

A: Você pode tentar algo como:
$('#meu_form').attr('id','novo_id');

A: Para alterar o ID podes mudar a propriedade do objeto DOM ou o atributo do elemento HTML. São coisas diferentes, expliquei mais sobre isso aqui nesta outra resposta.
Mudar propriedade:
(Referiste esta maneira na resposta, e está correta. É uma das maneiras)
// JavaScript nativo
document.getElementById('form').id = 'form_form_modulo';
// jQuery:
$('#form').prop('id', 'form_form_modulo');

Mudar atributo:
// JavaScript nativo
document.getElementById('form').setAttribute('id', 'form_form_modulo');
// jQuery:
$('#form').attr('id', 'form_form_modulo'):

Ambos fazem o que queres, mas mudando só a propriedade isso não vai ser visível no HTML quando inspecionas com as ferramentas dev.
Li nos comentários que tentaste
function SalvarBotoes() {
  alert($('#form').attr('id'));
  $('#form').attr('id', 'form_modulo');
  alert($('#form').attr('id'));
  form.submit();
}

A razão disso dar undefined é porque a ultima chamada a $('#form') já não vai dar nada exatamente porque mudaste o ID e esse seletor já não encontra nenhum elemento com esse ID. Terias de ter:
function SalvarBotoes() {
  var $form = $('#form');
  alert($form.attr('id'));
  $form.attr('id', 'form_modulo');
  alert($form.attr('id'));
  $form[0].submit();
}

A:

$(document).on('click', '#texto', function(){
  alert($(this).attr('id'));
  $(this).attr('id', 'NewID');
  alert($(this).attr('id'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="texto">TEXTO</button>

Segue o exemplo


text:
Q: Apache - allow proxy, block direct port call I have a VPS that acts as a proxy for ssh-tunneled webservers. Right now you can call:
http://myserverdomain.com:1234 and you are connecting into server1
http://myserverdomain.com:2345 and you are connecting into server2
I added apache config with lines:
ProxyPass /server1 http://localhost:1234/
ProxyPassReverse /server1 http://localhost:1234/

And I can access that server by calling http://myserverdomain.com/server1
(I have to change relative URLs tho, but that's another story)
The problem is I'd like to block direct call by port number, so nobody can discover all the tunneled webservers that are currently connected just by scanning http://myserverdomain.com for open ports.
I tried setting iptables with iptables -A INPUT -p tcp --destination-port 1234 -j DROP but it blocked my apache proxy as well (if I understood correctly, that's because iptables work on lower level than apache server - please correct me if I'm wrong).
If so, how can I achieve my goal of blocking port from calling it directly, but not the apache proxy redirect?

A: If you have both the tunnels and Apache in the same machine, just use 127.0.0.1:1234 and 127.0.0.1:2345 for the tunnels.
Otherwise, with iptables in the machine where you have the tunnels:
iptables -I INPUT -p tcp --dport 1234 -J DROP
iptables -I INPUT -p tcp -s 127.0.0.1 -J ACCEPT
iptables -I INPUT -p tcp -s $APACHE_IP -J ACCEPT

should work


text:
Q: Output a list of duplicate values ID's and non duplicate values using Python I have a huge dataset held in a csv file which holds 2 columns in excel of data which I need to print out the row ID of which ones have the same results (regardless of the order of numbers) and another list of results that are not the same. Some cells have more than 2 integers in them. I am trying to use Python to do this, I've also read around and Panda seems to be the way forwards. Please note I am new to Python and cannot seem to find a simple script to do this (only ones that delete duplicates).
So for example the required output would give me
Duplicated Row ID's: 1, 3.
Unique Row ID's: 2, 4.
 A        B            C
ID      Col1         Col2
-----------------------------
1    ["1", "3"]   ["3", "1"]
2    ["1", "2"]   ["9", "2"]
3    ["8", "0"]   ["0", "8"]
4    ["3", "7"]   ["1", "3"]

A: First if necessary convert string repr to lists:
import ast

df['ColA'] = df['ColA'].apply(ast.literal_eval)
df['ColB'] = df['ColB'].apply(ast.literal_eval)

Then sorting both columns lists and compare by Series.eq, last filter by DataFrame.loc with boolean indexing, ~ is for invert mask:
m = df['ColA'].apply(sorted).eq(df['ColB'].apply(sorted))
dup = df.loc[m, 'ID']
print (dup)
0    1
2    3
Name: ID, dtype: int64

un = df.loc[~m, 'ID']
print (un)
1    2
3    4
Name: ID, dtype: int64

For improve performance is possible convert lists to DataFrames and compare, only necessary same lengths of lists in both columns and in all rows:
df1 = pd.DataFrame(np.sort(df['ColA'].tolist(), axis=1), index=df.index)
df2 = pd.DataFrame(np.sort(df['ColB'].tolist(), axis=1), index=df.index)
print (df1)
   0  1
0  1  3
1  1  2
2  0  8
3  3  7

m = df1.eq(df2).all(axis=1)
print (m)
0     True
1    False
2     True
3    False
dtype: bool


text:
Q: How to customise Content Query Webpart to get this view I would like to customise the Content Query Webpart  like i normally do with DWP but i
know its a different approach.
All i want to do is to get the title name and turn it into a link and when you click the title link i want it come up with a a custom page that i would create and pass some querystring parameters to it.
Something like this
e.g
<xsl:value-of select="@Title"/>

the openDialog is the
SP.UI.ModalDialog.showModalDialog();

Any ideas would be appreciated.

A: In that case you'll have to either modify or create a new XSLT Template in the ItemStyle.xsl file, which you find in the /Style Library/XSLT Style Sheets/ItemStyle.xsl
In the template you can insert javascript as follow: