text:
Q: how to get a ViewModel from another ViewModel in ZK-Framework I have two ViewModels in my MVVM app. the one is bind to main window and another to popup window which appears after click on the button. in the popup window I need binding to the selected entity from main window. how can I access this entity in MainViewModel from PopupViewModel?

A: ZK has the concept of the event queue and global commands for communication between multiple ViewModels so we can use that to pass the current selected entity to the ViewModel of a popup window.
Using this zk mvvm demo page:
(see docs)
I added to the listbox a global command which fires out the current selected reminder of the main ViewModel which needs to be shown by a popup window:
    <listbox id="list" multiple="true" rows="6"
        model="@load(vm.reminders)"
        selectedItem="@bind(vm.selectedReminder)"
        onSelect="@global-command('refresh', reminder=vm.selectedReminder)">

Then I added to the bottom of the page a popup window with a second ViewModel:
    <window id="info" visible="false" width="120px" border="normal" position="parent"
     apply="org.zkoss.bind.BindComposer"
    viewModel="@id('vm') @init('org.zkforge.zktodo2.ui.ViewModelPopup')"
    >
You have selected <label value="@load(vm.currentReminder.name)"/>
</window>
<button label="More info" onClick="info.doPopup()"/>
</zk>

The pop up Viewmodel has a method which accepts the global command which takes the entity as a parameter:
public class ViewModelPopup  {

    protected Reminder currentReminder = new Reminder();

    public Reminder getCurrentReminder() {
        return currentReminder;
    }

    public void setCurrentReminder(Reminder currentReminder) {
        this.currentReminder = currentReminder;
    }

    @GlobalCommand @NotifyChange("currentReminder")
    public void refresh(@BindingParam("reminder") Reminder reminder ){
        this.setCurrentReminder(reminder);
        return;
    }

}

So now whenever you select an item in the listbox the refresh method is fired on the popup ViewModel passing into it data taken from the main ViewModel. Whenever you hit the "More info" button at the bottom of the page to show the popup window it displays the name of the current selected entity.
The documentation which I followed to do this is at:
(docs1)
(docs2)
The instructions to run that sample app are on the readme at (Docs3)

A: Do you have a list of entities in your mainwindow? if that is the case, from the view model of your main window you need to put your selected entity in a map and pass it as a param for createComponents just like this:
//In the view Model of the main window
Map arg = new HashMap();
arg.put("selectedEntity", SelectedEntity);
Executions.createComponents("/myPopup.zul", null, arg);

Now in the popup view model, you simply retrieve the value of your Entity in the Init method:
    //PopupView model
    @Init
    public void init(@ExecutionArgParam("selectedEntity") SelectedEntity newEntity)           {

    entity = newEntity;

}

you can notice that the string in ExecutionArgParam is the key you put in the map.


text:
Q: CSP with javascript in "document.location" Our application is being updated to comply with new CSP (Content Security Policy) rules.
E.g. Inline event handlers are replaced with addEventListener(), and inline styles replaced with CSS.
However, in some instances document location is set to a javascript expression, like so...
document.location = 'javascript:someFunction()';

...which causes the following error...
"Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' 'strict-dynamic' 'unsafe-inline'

My question: What is an equivalent way of re-writing this so that it complies with CSP rules?

A: It is blocked by unsafe-inline. Please consider either:

*

*If someFunction() returns an valid URI, you can write document.location = someFunction(); as @ControlAltDel mentions.

*If it does not, you can just call someFunction().

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get mypy to use types from typings directory, but not report errors from the typings directory? I want mypy to check the directory src
src uses a 3rd party library without typing and not in typeshed. So I made a typings directory with type stubs for this 3rd party library. But it's a big library and I can't make complete typing for all of it, so I just made typing for the API that I use.
If I use mypy src, it doesn't find the typings. It reports problems because of that.
If I use mypy src typings, it doesn't report the problems in src, but it reports problems in typings.
I want it to use typing information from typings to check src, but not report errors from typings.


text:
Q: Auto-conversion of 'trivial' answers doesn't allow subsequent comment editing I just wrote a short answer to this question. It was automatically converted to a comment because it was 'trivial'. I don't really agree with this, but ok.
However, the answer linked to a URL, and this broke the markdown when the comment conversion took place, since URL linking using numbered references isn't supported in comments. Not great, but ok...
I tried to fix the comment, editing it to use comment link syntax, but apparently that's not possible. Weirdly, I see my edited text in the answer box for that page, even though it's no longer an answer, and even though my edited text is not reflected in the rendered comment.
Seems like state propagation between answers and auto-converted comments is a little broken. If it's now a comment, shouldn't my answer box be blank? And shouldn't I be able to edit the comment? And if you're going to convert my text to a comment, shouldn't the link syntax be fixed as part of the process?

A: I wasn't able to reproduce the inability to edit a freshly converted answer -> comment, but I was able to reproduce the answer editor still having the original text.  This is due to a saved draft not being cleared.
As for fixing the link during comment conversion, that's more difficult and probably not worth the development effort.
We'll get a fix for the stale draft pushed out, but unless someone can reproduce the editing issue, I'll have to mark this as status-norepro.


text:
Q: Seaborn pairplot not showing KDE After upgrading to matplotlib 2.0 I have a hard time getting seaborn to plot a pairplot.  For example...
sns.pairplot(df.dropna(), diag_kind='kde') returns the following error TypeError: slice indices must be integers or None or have an __index__ method.  My data doesn't have any Nans in it.  Infact, removing the kde option allows the function to run.
Any idea what is happening?

A: Check the data type of the relevant variables.  The error indicates that at least one of them is not an integer.  It might be a float. If so, you'll need to recast the variable as an integer.  Be careful if you have some very long numbers as these can round down when converting to an integer - see this question here for more information.
(Note, this works for me in Python 2.7, not sure if 3.+ is different).

A: Looks like the problem was with statsmodels (which seaborn uses to do KDE).  I reinstalled statsmodels and that cleared up the problem.


text:
Q: actionscript 3 sleep? I have a simple actionscript function
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
addEventListener(Event.ENTER_FRAME, frameLooper);

function frameLooper(event:Event):void {
    if(myArray.length > 0) {
        text1.appendText(myArray.shift());
    }else{
        removeEventListener(Event.ENTER_FRAME, frameLooper);
    }
}

And I want to have it sleep after calling the framelooper so it is a little bit slower. How could I do this?
btw, I'm fairly new and found this code on a tutorial, it's a text typing effect, if there is a better way of doing this please let me know.

A: Use a Timer:
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
var timer : Timer = new Timer (1000, myArray.length);
timer.addEventListener (TimerEvent.TIMER, frameLooper);
timer.start();

function frameLooper(event:Event):void {
    text1.appendText(myArray.shift());
}

This will execute the frameLooper on every second for exactly as many times as the length of the array.

A: I'm not saying this is better than the timer method, just an option
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
addEventListener(Event.ENTER_FRAME, frameLooper);

const WAIT_TIME:int = 10;
var i:int = 0;
function frameLooper(event:Event):void {
    if(myArray.length > 0) {
        if(i==0){
            trace(myArray.shift());
            i = WAIT_TIME;
        };
    } else {
        removeEventListener(Event.ENTER_FRAME, frameLooper);
    }
    i--;
}


text:
Q: tk UI hang when inserting text from large file on separate thread Even when run in a seperate thread my UI hangs while a large file is being loaded into a Text widget. Is it just because the application is under heavy load or is there a way I can keep the UI functional while this is happening. Im loading several text files in different widgets so the hang up is longer than desired.
from tkinter import *
import threading

i = 'large/text/file/400,000+lines'
root = Tk()

txt = Text(root)
txt.grid()

def loadfile():
    with open(i, 'r') as f:
        a = f.readlines()
        txt.insert('end', ' '.join(a))
        #for line in a:
         #   txt.insert('end', line)

def threadstarter():
    startit = threading.Thread(target=loadfile())
    startit.start()

btn = Button(root, text= 'start', command=lambda: threadstarter())
btn.grid()

root.mainloop()

Tested on several machines with plenty of resources.

A: What Bryan is saying is that you need to launch a thread like this:
from tkinter import *
import threading

i = 'large/text/file/400,000+lines'
root = Tk()

txt = Text(root)
txt.grid()

def loadfile():
    with open(i, 'r') as f:
        txt.insert('end', f.read())

def threadstarter():
    startit = threading.Thread(target=loadfile)
    startit.start()

btn = Button(root, text= 'start', command=threadstarter)
btn.grid()

root.mainloop()

A: In order to invoke loadfile in a separate thread with positional/keyword arguments, use the args and kwargs arguments to threading.Thread like so:
def threadstarter():
    startit = threading.Thread(target=loadfile, args=(42,), kwargs={'a': 'foo'})
    startit.start()

... which would invoke loadfile(42, a='foo') in the thread.


text:
Q: Better way for choosing next best max id for a shard I have a use case for range based shard in mysql i.e
---------------------
shard   | upperbound
---------------------
1       | 500
2       | 1000
3       | 1500

Meaning Shard1 has 1- 500 users and shard2 has 501-1000 users and so on. So that latter point on user base grow, will keep on adding new shards.
The user table looks like below:
-----------------------------
id   | name | email | contact
-----------------------------
1    |Test  |t@t.com|xxxxx
501  |Test1 |t@t.com|xxxxx
101  |Test2 |t@t.com|xxxxx
1001 |Test3 |t@t.com|xxxxx

So user with name Test resides in shard1, user with name test2 resides in shard2 and user with name Test3 resides in shard3 and so on.
When a new user registration happens, Based on the open shards lets say (Shard4 and Shard5 is open for registration) then it first does a select on the user  table with range to get the next max possible Id and increment by 1 and stores it. Problem with this approach is when two different people tries to register and from code select returns same id for the two different people/thread as both the user registration can't be in same transaction.
Is there any other better way for choosing the next id for a shard using range ?

A: select max(id) from t for update

Should hold the lock on the max id till the transaction completes.


text:
Q: How to preview/display an image after uploading at the side of the upload button in Vue.js (Element.ui)? I am working on displaying/previewing an image after uploading it. I am trying to upload an image and then make an axios/AJAX call.
Please find the code below:
HTML code:
        User Name
           <input v-model="person_name" placeholder="Edit Me">

        Display Pic
           <input type="file" name="file" />

Javascript Code --> AJAX/FETCH call to the API
            var formData = new FormData();
            var fileField = document.querySelector("input[type='file']");

            formData.append('username', this.person_name);

            formData.append('File', fileField.files[0]); // getting the file attached

            const body = formData;

            const init = {
                method: 'POST',
                body
            };

            fetch('http://..xyz....com', init)
                .then((response) => {
                return response.json(); // or .text() or .blob() ...
            })
                .then((text) => {
                // text is the response body
            })
                .catch((e) => {
                // error in e.message
            });
        },

How do I display or preview the picture/photo as an avatar or something after uploading the pic.

A: As far as I understand your question you can preview the uploaded image before sending it to the server. You can attach an @change event listener on your input type='file' to listen to the change event and then access the image uploaded by event.target.files[0]. Then change the src of the img tag with the uploaded image src.
Live Demo Here
You can also send it to server immediately after uploading it in the preview() method or you can use upload button to send it to the server.
Your Vue Template:
<template>

    <input type=file @change="preview">

    <button @click="upload()">Upload</button>

 {{ uploaded }}

</template>

Script:
data: () => ({
  imgSrc: '',
  uploaded: ''
}),

methods: {
  preview(e) {
    var pic = document.getElementById('image')
    let imgSrc = URL.createObjectURL(e.target.files[0]);
    this.imgSrc = imgSrc
  },
  upload() {
    this.uploaded = this.imgSrc;
  }
}


text:
Q: Escaping parenthesis in PowerShell Invoke-Expression Below is a one-line script I am writing that is causing problems when I try to add an open-paran within invoke-expression.
Within the script, the file map.txt contains 800 lines of 3 digit numbers. The script is intended to change the name of existing files that start with 001..400 (unique/non-repeating) by prefixing a new (unique) three digit number and space before the existing file. To do this, the a three-digit number is extracted from map.txt to find the file I want renamed (using invoke-expression "ls $line1 (*" and the next line in map.txt is the number that should be prefixed to the existing file. So, if the first two lines of map.txt are 001 and 008, the file, 001 (additional characters).ext (parentheses are part of file name) will be changed to 008 001 (additional characters).ext
It will execute if I remove the open-paran within invoke-expression. However, without the open-paran within invoke-expression, when the map.txt file comes to a number pair of 008 021, it will try to rename the 008 001 (additional characters).ext that has already been renamed. Adding the open-paren makes files names unique regardless of name changes that have already occurred and the script should execute as desired. That is, if I can figure out how to include an open-paren within invoke expression. I could probably do a work around with a few lines of regex and -match but if I can find a quick solution to include the open-paran with invoke-expression, it would be ideal.
Thanks for your help.
for ($i=0; $i -lt 800; $i=($i+"2")) {$line1=(get-content ..\map.txt | select -index $i); $line2=(get-content ..\map.txt | select -index ($i+"1")); $old=(invoke-expression 'ls $line1 (*'); $fileold=($old.basename+$old.extension); $filenew=($line2+" "+$fileold); mv "$fileold" "$filenew"}

A: To make Invoke-Expression 'ls $line1 (*' or Invoke-Expression "ls $line1 (*" work as intended, quote the line you want to pass to ls with different quotes, like Invoke-Expression 'ls "$line1 (*"' or Invoke-Expression "ls '$line1 (*'".

Furthermore, I would like to recommend the following code optimization to you:
$numbers = Get-Content -Path "..\map.txt"
for ($i = 0; $i -lt 400; $i++) {
    Get-Item -Path "$($numbers[2*$i]) (*" | ForEach-Object -Process {Rename-Item -Path $_.Name -NewName "$($numbers[2*$i+1]) $($_.Name)"}
}

And if you want to squeeze that into one line, you can do it like this:
$n=gc ..\map.txt;for($i=0;$i-lt400;$i++){gi "$($n[2*$i]) (*"|%{rni $_ "$($n[2*$i+1]) $($_.Name)"}}


text:
Q: access elements inside webbrowser tool I am working on a windows form application, and I was wondering how to access elements inside the webbrowser. Say for example there is an element like this <button class="btn btn_Roll">Roll Dice</button> how do I get that elemenet and perdorm a click action?
I know you can acccess elements by id like so
HtmlDocument document = webBrowser1.Document;
HtmlElement example = document.GetElementById("some_id_here");

How is it done with class?

A: try:
var element = this.objWebBrowser.Document.GetElementsByTagName("button").
                  Cast<HtmlElement>().Where(e =>
                                            e.GetAttribute("class")).
                                            FirstOrDefault();

if(element == null) return;

element.InvokeMember("click");


text:
Q: Function Pointer to a non-static member function? Is it possible to use a function pointer to point at a non-static member function? I would like to point at a member function that uses non-static objects and variables from the class...static member functions cannot do this...
I have a member function that points at one of four static member functions. The problem is that the data to be used by each of the four member functions is non-static so the static member functions will not access them...
Can I point at non-static member functions?
Also, the class instance is a pointer...here is my code:
class CRoutine{
int m_index;
    ...
        BOOL (*CallRoutine(char opcode))(DWORD, float, float, float);
        static BOOL Update(DWORD, float, float, float);
        static BOOL Transition(DWORD, float, float, float);
        static BOOL Revert(DWORD, float, float, float);
        static BOOL Sequence(DWORD, float, float, float);
    ...
    };
    BOOL (*CRoutine::CallRoutine(char opcode))(DWORD, float, float, float)
    {
        switch ( opcode )
        {
        case 0:
            return &CRoutine::Update;
        case 1:
            return &CRoutine::Transition;
        case 2:
            return &CRoutine::Revert;
        case 3:
            return &CRoutine::Sequence;
        default:
            return &CRoutine::Update;
        }
    }
    BOOL CRoutine::Update(DWORD AnimSetIndex, float time, float tTime, float shift)
    {
        MessageBox(NULL, L"Updating", L"Routine #1", MB_OK);
         CRoutine::m_index++; // Error thrown here...
return true;
    }
    BOOL CRoutine::Transition(DWORD AnimSetIndex, float time, float tTime, float shift)
    {
        MessageBox(NULL, L"Transitioning", L"Routine #2", MB_OK);
        return true;
    }
    BOOL CRoutine::Revert(DWORD AnimSetIndex, float time, float tTime, float shift)
    {
        MessageBox(NULL, L"Reverting", L"Routine #3", MB_OK);
        return true;
    }
    BOOL CRoutine::Sequence(DWORD AnimSetIndex, float time, float tTime, float shift)
    {
        MessageBox(NULL, L"Sequencing", L"Routine #4", MB_OK);
        return true;
    }

The error thrown above is:
error C2597: illegal reference to non-static member 'CRoutine::m_index'

A: Yes as long as you can modify the type in which it is stored.
Using the std::function abstract you can bind to anything that meets a certain signature (ie take x return y). be it functor, lambda, bound member function or free function.
struct bar{
     void foo(){
          std::cout << "HI" << std::endl;
    }
};

int main(){

    bar b;
    //using std::function instead of a func*
    std::function<void()> func(
                 std::bind(&bar::foo, &b));

    func();
}

Note the use of std::function require C++11, boost has a very similar version too that can be used with C++98


text:
Q: Unable to ssh to router running DDWRT I am trying to ssh to a DLink router running DDWRT:
ssh admin@192.168.1.1
Connection closed by 192.168.1.1

I tried to alter the ssh ports on the router to 2222:
ssh admin@192.168.1.1 -p 2222
ssh: connect to host 192.168.1.1 port 2222: Connection refused

Which is a different result. I am somehow unable to connect. What could be the problem?

A: It was possible to connect using telnet and a custom port.
The version of DD-WRT that is used (DD-WRT v24-sp2 (03/25/13) std (SVN revision 21061)) is unable to handle ssh connections.
There is currently no stable version that supports ssh.
@MariusMatutiae
How would you suggest to secure the telnet connection? Does the provided root password suffice?
Thanks to all for the help.

A: From the DD-WRT online manual:

If you want to use user/password to login using SSH use user "root" with the password you set in the webinterface

So, you cannot use admin, you must use user root. And that's besides having enabled sshd in the GUI, as already suggested by @Darius.
Edit:
To be clear: I have  control of 4 DD-WRT routers. On all of them, with the command
 ssh IP_Address -p port_number

the connection is refused. The connection is established if and only if I use:
 ssh root@IP_Address -p port_number

The reason is simple: if I do not provide the user name root, the system will try to log me in the router with the same username I am currently using, which, in my case, is just my first name. And, of course, such an account does not exist on any of my routers.
This being said, a connection also requires three conditions: that sshd has been enabled through the GUI, that the password provided is the same as that of the administrative account used to access the GUI, and that the port coincides with that chosen at the time of the enabling the sshd daemon.
There is, luckily, nothing else to do. And, by the way, change the authentication method to a cryptographic key ASAP.


text:
Q: Windows 10 update appears to have broken GHC I have the latest Haskell Platform (8.0.2) and it appears that the forced update of Windows10 (1703) has broken GHC. There is a ticket (#13411) about this, and it seems like I need to replace the gcc.exe file in my build.
Where do I find the appropriate gcc.exe file and where do I put it (assuming standard installation of the Haskell Platform)?

A: GCC should be in mingw\bin in your installation directory, e.g.
C:\Program Files\Haskell Platform\8.0.2\mingw\bin\gcc.exe

The appropriate binary can be found in your linked repository. The one meant for GHC 8.0.X should suite you fine. Be sure to use the x64 one if you've installed the 64bit variant of the platform, and x86 otherwise.

A: As of 20 April 2017 1700 UTC this seems like the process:

*

*Download the version of GHC 8.0.2 with the Windows 10 patch (As described here.).

*Open the archive file.  Windows 10's native archive browser does not understand the .tar.xz format so you will need something like 7-Zip to open it.

*Find the "gcc.exe" file under \ghc-8.0.2\mingw\bin\ and copy it over the file in C:\Program Files\Haskell Platform\8.0.2\mingw\bin\.


text:
Q: AWS Glue Spark job does not scale when partitioning DataFrame I am developing a Glue Spark job script using Glue development endpoint which has 4 DPUs allocated. According to Glue documentation 1 DPU equals to 2 executors and each executor can run 4 tasks. 1 DPU is reserved for master and 1 executor is for the driver. Now when my development endpoint has 4 DPUs I expect to have 5 executors and 20 tasks.
The script I am developing loads 1 million rows using JDBC connection. Then I coalesce the one million row partition into 5 partitions and write it to S3 bucket using the option maxRecordsPerFile = 100000. The whole process takes 34 seconds. Then I change the number of partitions to 10 and the job runs for 34 seconds again. So if I have 20 tasks available why is the script taking the same amount of time to complete with more partitions?
Edit: I started executing the script with an actual job, not development endpoint. I set the amount of workers to 10 and worker type to standard. Looking at metrics I can see that I have only 9 executors instead of 17 and only 1 executor is doing something and the rest are idle.
Code:
...

df = spark.read.format("jdbc").option("driver", job_config["jdbcDriver"]).option("url", jdbc_config["url"]).option(
    "user", jdbc_config["user"]).option("password", jdbc_config["password"]).option("dbtable", query).option("fetchSize", 50000).load()

df.coalesce(17)

df.write.mode("overwrite").format("csv").option(
    "compression", "gzip").option("maxRecordsPerFile", 1000000).save(job_config["s3Path"])

...

A: This is highly likely a limitation of the connections being opened to your jdbc data source, too few connections reduce parallelism too much may burden your database. Increase the degree of parallelism by tuning the options here.
Since you are reading as a data frame, you can set the upper lower bound and the partition columns. More can be found here.
To size your DPUs correctly, I would suggest linking the spark-ui, it could help narrow down where all the time is spend and the actual distribution of your tasks when you look at the DAG.


text:
Q: Problem with c# events I need to implement Pause and Resume events of a MP3 player inside the same button click event. following is the code i have tried and its not working,Can any one give me the solution
private void button3_Click(object sender, EventArgs e)
{
    if (button3.Text == "Pause")
    {
        CommandString = "pause mp3file";
        mciSendString(CommandString, null, 0, 0);
        Status = true;
        button3.Text = "Resume";
    }
    if (button3.Text == "Resume")
    {
        CommandString = "resume mp3file";
        mciSendString(CommandString, null, 0, 0);
    }
}

A: You are changing the button3.Text property within the first if statement.
When the second if statement is tested it is true (both if statements are running with each button click when the Text property is "Pause")
Use if, else to run one code block or another.
Use if, else if  statements if you want a test to be run on the second code block also.
You should also take account of the possibility that neither of these cases is true.
if (button3.Text == "Pause")
{
    CommandString = "pause mp3file";
    mciSendString(CommandString, null, 0, 0);
    Status = true;
    button3.Text = "Resume";
}
else if(button3.Text == "Resume")
{
    CommandString = "resume mp3file";
    mciSendString(CommandString, null, 0, 0);
    button3.Text = "Pause";
}

A: at first glance it won't work properly 'cause in 2 case
if (button3.Text == "Resume")
{
    CommandString = "resume mp3file";
    mciSendString(CommandString, null, 0, 0);
}

you missed the line:
button3.Text = "Pause";

Actually it's not a good idea to check the button state by its text property. As a simple solution you need to have a boolean flag to check against it.

A: you have two if consecutive if statements. You need just one if/else statement.
change your code to:
    if (button3.Text == "Pause")
    {
        CommandString = "pause mp3file";
        mciSendString(CommandString, null, 0, 0);
        Status = true;
        button3.Text = "Resume";
    }
    else if (button3.Text == "Resume")
    {
        CommandString = "resume mp3file";
        mciSendString(CommandString, null, 0, 0);
    }

A: The problem is:
By the time you get to the second if statement, you have changed the Text of the button, hence both statements are being run...
Here is a quick test:
        if (button1.Text == "Pause")
        {
            label1.Text = label1.Text + " saw pause ";
            button1.Text = "Resume";

        }
        if (button1.Text == "Resume")
        {
            label1.Text = label1.Text + " saw resume ";
            button1.Text = "Pause";
        }

returns: label1 saw pause saw resume.
There are two ways to fix this:
You could insert a 'return;' statement within each if statement:
private void button3_Click(object sender, EventArgs e)
{

    if (button3.Text == "Pause")
    {
        CommandString = "pause mp3file";
        mciSendString(CommandString, null, 0, 0);
        Status = true;
        button3.Text = "Resume";
        return;
    }
    if (button3.Text == "Resume")
    {
        CommandString = "resume mp3file";
        mciSendString(CommandString, null, 0, 0);
        button3.Text = "Pause";
        return;
    }
}

Or secondly, you could capture the value of the button text once:
private void button3_Click(object sender, EventArgs e)
{
    String value = button3.Text;
    if (value == "Pause")
    {
        CommandString = "pause mp3file";
        mciSendString(CommandString, null, 0, 0);
        Status = true;
        button3.Text = "Resume";

    }
    if (value == "Resume")
    {
        CommandString = "resume mp3file";
        mciSendString(CommandString, null, 0, 0);
        buton3.Text = "Pause"; // As mentioned before, this is required too.
    }
}

Hope that helps.
Steve


text:
Q: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 359: invalid start byte First time poster, bear with me...
#!/usr/bin/python
import sys, os
count = 0
filename = "data2.txt"
file = open(filename, "r")

s1 = input("What do you want to search for? ")
search = s1.lower()

words = search.split()

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

def countlines():  #count length of file
    with open(filename, 'r') as f:
        count = 0
        for line in f:
            count += 1
        return count
total = countlines()
totp1 = total + 1

with open(filename) as f:
  currpos = 0
  for line in f:
    currpos += 1
    line2 = line.lower()
    if currpos < totp1:
      if len(search.split()) == 2:
        if line2.find(words[0]) != -1 and line2.find(words[1]) != -1:
          print(line)
      if len(search.split()) == 1:
        if line2.find(search) != -1:
          print(line)
          #restart_program()
      if search == "quit":
        print('Exiting')
        break
      if search == "exit":
        print('Exiting')
        break
    if currpos == total:
      restart_program()

When I run this code on Repl.it it runs without issue and does just what its supposed to do.  However when I run it on my laptop (Arch) I get this error:
    Traceback (most recent call last):
  File "./search", line 23, in <module>
    total = countlines()
  File "./search", line 20, in countlines
    for line in f:
  File "/usr/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 359: invalid start byte

Any Help appreciated.  If in missed any required details just ask.  Thank you!


text:
Q: Appium Android: How to test pdf displayed inside WebView In Android, I want to test PDF which contains terms and conditions, but this displayed inside WebView. I am able to switch to WebView, I am using below code.
String strWebContextName = getContexts().stream().filter(ctx -> ctx.contains("WEBVIEW_")).findAny().orElse(null);
if (Objects.nonNull(strWebContextName)) {
((AndroidDriver) getBaseMobileDriver()).context(strWebContextName);
}

Then locate the script tag and get the content
@FindBy(xpath = "//script[@type="text/javascript" and contains(text(),"_init")]")
private WebElement webElementPdfPath;

String htmlCode = (String) ((JavascriptExecutor) getBaseMobileDriver()).executeScript("return arguments[0].innerHTML;", webElementPdfPath);

After this I don't know how to proceed? Please help

A: In my experience with verifying PDF's in a WebView is that there is only limited you can search for with selectors. I'm used to only class or type attributes of the PDF container. I have never been able to search for specific text in an PDF with XPath (PDF's are also not part of the HTML but more an extension which opens the document).
Try a simpler XPath: //script[@type='text/javascript']. This way you know the PDF is opened, but that's all.
I've done this with desktop browsers as well. For browsers, there is no way to identify inner PDF elements, but only limited to: //embed[@type='application/x-google-chrome-pdf']. If I needed to verify the PDF with conditions I've used SikuliX image recognition for instance.


text:
Q: Does datetime account for the Calendar (New Style) Act of 1750? In September of 1752, in accordance with the Calendar (New Style) Act of 1750, 11 days were skipped in September 1752. This can be seen with the Unix cal command.
$ cal 9 1752
September 1752
Su Mo Tu We Th Fr Sa
1 2 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

After learning this factoid, I wondered if Python's datetime class accounted for this at all. After some quick toying around, it appears as if it does not...
>>> datetime.datetime.now() - datetime.datetime(1752, 9, 14)
datetime.timedelta(96550, 47314, 535334)
>>> datetime.datetime.now() - datetime.datetime(1752, 9, 2)
datetime.timedelta(96562, 47318, 183610)

By my understanding, if Sept. 14, 1752 was 96550 days ago, than Sept. 2, 1752 should be 96551 days ago (because the 3-13 were skipped).
I also appears as if the calendar class also does not account for the skip
>>> calendar.prmonth(1752, 9)
   September 1752
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

It is likely inconsequential in the vast majority of applications, however it still seems like a bug to me that this is not accounted for. Of course, it is also entirely possible that I am missing something obvious.
Am I missing something obvious?

A: The python calendar is described here, which says:

Most of these functions and classes rely on the datetime module which
  uses an idealized calendar, the current Gregorian calendar
  indefinitely extended in both directions. This matches the definition
  of the "proleptic Gregorian" calendar in Dershowitz and Reingold's
  book "Calendrical Calculations", where it's the base calendar for all
  computations.

So no, England's decision in 1752 to use the Gregorian calendar (like much of the rest of western Europe) instead of the Julian calendar is not reflected in calendar that Python uses. It's quite interesting to me that the Unix cal command does include the switch.


text:
Q: Python: basic Loop I know how to do in javascript:
for (var i = 1; i <= 3; i++)

But how to do in Python? Codes:
for i in range(1,3):
    print(i)

Result:
1
2

I can print the result 1 & 2 but the values are wrong when I put i into a calculation loop. The values of i are forever 2. Here are the codes:
data = pd.read_csv('test.csv')
g = data.loc[1:12 , 'close']
for i in range(1,3):
    a = i-g

What I want to do is a = 1-g& a = 2-gwhen the range isrange(1,3)
Any ideas?Any help would would be appreciated.

A: If you are using the "a" variable outside the loop, it will only have the last value assigned to "a", in this case will be 2.
Make sure you use it inside the loop:
data = pd.read_csv('test.csv')
g = data.loc[1:12 , 'close']
for i in range(1,3):
    a = i-g
    print(a)

A: The upper bound of the range() function is exclusive.
So this:
 for i in range(1,3):
     ...

translates to:
 var i;
 for (i=1;i<3;i++) {
     ...
 }

to obtain the equivalent of (i=1;i<=3;i++) you need to add 1 to the upper bound:
 for i in range(1,4):
     ...


text:
Q: Check previous value of a 2 dimentional array before adding a new value I've created a function to add new integer values into a two-dimensional (2D) array from user input. And I would like to check if the newly provided integer is larger than the previous one before adding it to the array.
If it was a single-dimensional array that would be easy. I would index the array -1 and check the value.
But now with 2 dimensions, I'm getting confused and I don't know how to check the previous row's value.
Should I create if statements for each row? (Doesn't seem optimal)
What I have done so far:
#include <stdio.h>

#define N 3
#define M 5

void get_numbers()
{
    int i, j, number;
    int TABLE[N][M];

    for (i = 0; i < N; i++)
    {
        for (j = 0; j < M; j++)
        {
            printf("Position: [%d, %d]: ", i+1, j+1);
            scanf("%d", &number);

            if (j > 0)
            {
                while (number < TABLE[i][j-1])
                {
                    printf("The new number should be larger than the previous one %d \n", TABLE[i][j-1]);
                    printf("Please try again\n");

                    printf("Position: [%d, %d]: ", i+1, j+1);
                    scanf("%d", &number);
                }

                TABLE[i][j] = number;

            }
        }
    }
}

int main () {
    get_numbers();
}

A: All elements TABLE[i][0] of the array stay uninitialized.
You need to write
for (i = 0; i < N; i++)
{
    for (j = 0; j < M; j++)
    {
        printf("Position: [%d, %d]: ", i+1, j+1);
        scanf("%d", &number);

        if ( j == 0 )
        {
            TABLE[i][j] = number;
        }
        else
        {
            while (number <= TABLE[i][j-1])
            {
                printf("The new number should be larger than the previous one %d \n", TABLE[i][j-1]);
                printf("Please try again\n");

                printf("Position: [%d, %d]: ", i+1, j+1);
                scanf("%d", &number);
            }

            TABLE[i][j] = number;
        }
    }
}

If you also want to compare the first element of an row with the last element of the previous row when you need to write
for (i = 0; i < N; i++)
{
    for (j = 0; j < M; j++)
    {
        printf("Position: [%d, %d]: ", i+1, j+1);
        scanf("%d", &number);

        if ( i == 0 && j == 0 )
        {
            TABLE[i][j] = number;
        }
        else
        {
            while ( number <= ( j == 0 ? TABLE[i-1][M - 1] : TABLE[i][j-1] ) )
            {
                printf("The new number should be larger than the previous one %d \n", TABLE[i][j-1]);
                printf("Please try again\n");

                printf("Position: [%d, %d]: ", i+1, j+1);
                scanf("%d", &number);
            }

            TABLE[i][j] = number;
        }
    }
}

Another way is to reinterpret the two-dimensional array as a one-dimenisonal. For example
    int *p = ( int * )TABLE;

    for ( i = 0; i < N * M; i++ )
    {
        printf("Position: [%d, %d]: ", i / M + 1, i % M + 1 );
        scanf("%d", &number);

        if ( i == 0 )
        {
            p[i] = number;
        }
        else
        {
            while ( number <= p[i-1] )
            {
                printf("The new number should be larger than the previous one %d \n", p[i-1] );
                printf("Please try again\n");

                printf("Position: [%d, %d]: ", i / M + 1, i % M + 1 );
                scanf("%d", &number);
            }

            p[i] = number;
        }
    }


text:
Q: From single to multindex dataframe I have a geodataframe like this:
Out[7]:
                                               geometry
FID
0     POLYGON ((7.662965420348624 45.05600185397847,...
1     POLYGON ((7.665210146514162 45.05607590098681,...
2     POLYGON ((7.663353281768154 45.05601113630467,...
3     POLYGON ((7.660229137844505 45.0570570693801, ...

and I want to add another index, which is a time series index like this:
Out[10]:
DatetimeIndex(['2013-06-26 00:00:00+01:00', '2013-06-26 00:15:00+01:00',
               '2013-06-26 00:30:00+01:00', '2013-06-26 00:45:00+01:00',
               '2013-06-26 01:00:00+01:00', '2013-06-26 01:15:00+01:00',
               '2013-06-26 01:30:00+01:00', '2013-06-26 01:45:00+01:00'],
              dtype='datetime64[ns, Europe/London]', name=u'Date Time', freq=None)

I will like to assign to each FID the other index and obtain a multindex geodataframe. Such data frame will have a spatial index and a time series index.
How do I achieve this goal?


text:
Q: Export slickgrid to pdf and retain the formatting that is done in the UI to show the data Currently the export functionality for the pdf is
  PDF
This is exporting the grid but the formatting is all gone and the data is getting truncated as the grid is expanding horizontally.
Need a way to fix this, any help is much appreciated.

A: You are exporting the grid using tableExport.jquery.plugin, which does not have proper customization support. For example, as far as I can see here, font defaults to Helvetica and can't be changed.
I think you should try implementing export on server side using some library like wkhtmltopdf, which converts html to pdf and also supports css and js (it runs browser engine under the hood).


text:
Q: Evaluation of a series involving binomial coefficients I have a series $S$ I want to simplify, in terms of an integer $n$:
$$S = \sum_{k=0}^n {n \choose k} \frac{(-1)^k}{n+k+2}$$
I think that $$(n+2) {2n+2 \choose n+2} S = 1$$
which would mean $$S = \left[(n+2) {2n+2 \choose n+2} \right]^{-1}$$
but I'm stuck as to how to show this (if indeed it is true!).
Any help (even just with where to start) would be really appreciated.
Many thanks

A: Let
$$ S(x)=\sum_{k=0}^n {n \choose k} \frac{(-1)^k}{n+k+2}x^{n+k+2} $$
and then
$$ S'(x)=\sum_{k=0}^n {n \choose k} (-1)^kx^{n+k+1}=x^{n+1}(1-x)^n. $$
So
$$ S=\int_0^1x^{n+1}(1-x)^{n}dx $$
and hence
\begin{eqnarray}
S&=&\frac12\left[\int_0^1x^{n+1}(1-x)^{n}dx+\int_0^1(1-x)^{n+1}x^{n}dx\right]\\
&=&\frac12\int_0^1(1-x)^nx^ndx=\frac{1}{2(n+1)}\int_0^1(1-x)^ndx^{n+1}\\
&=&\frac{n}{2(n+1)}\int_0^1(1-x)^{n-1}x^{n+1}dx\\
&=&\frac{n(n-1)}{2(n+1)(n+2)}\int_0^1(1-x)^{n-2}nx^{n+2}dx\\
&=&\cdots\\
&=&\frac{n(n-1)\cdots1}{2(n+1)(n+2)\cdots2n}\int_0^1x^{2n+1}dx\\
&=&\frac{n(n-1)\cdots1}{2(n+1)(n+2)\cdots2n(2n+1)}\\
&=&\frac{(n!)^2}{2(2n+1)!}.
\end{eqnarray}


text:
Q: Update Index of Threejs BufferGeometry(adding faces) Adding vertices to a BufferGeometry and updating the positions attribute works fine. But I am starting to get desperate how I can do the same for the index(adding faces). Is there any way how to do this?
const vertices = new Float32Array(100 * 3);
const indices = new Array(100 * 3);

These are the arrays that are used.
Update:
This seems to do the trick:
const indices = new Uint16Array(100 * 3);
geometry.setIndex(new THREE.BufferAttribute(indices, 1));

Don't know exactly why, but it works.
geometry.index.needsUpdate = true
seemed to have no effect

A: When updating attributes you'd typically use geometry.setAttribute(). However, when updating indices you need to use geometry.setIndex(), as it's not exactly an attribute per-se. You can read about this method here in the docs.
For a simple demo on how to use setIndex, you can look at this live example, and its source code. In essence, you can just pass an array, and the engine will convert it to a BufferAttribute for you behind the scenes:
const indices = [0, 1, 2, 2, 3, 0];
geometry.setIndex(indices);


text:
Q: Gmail auto login and error message python I am trying to login to the blogger site, but first I have to enter the Gmail account. I entered it, but an error message appears, "This browser or app may not be secure"
can you help me with this error.
this is my code
from statistics import mean
import pandas as pd
from selenium_stealth import stealth
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import pyautogui
import time
print("ready?")
print("loading.......................................")
df = pd.read_excel("Moaaz.xlsx","Moaaz")
email = "sisoasn81@gmail.com"
password = "1*1#36@$%anz"
name = df["Name"].values.tolist()
website = df["Website"].values.tolist()
phone = df["Phone"].values.tolist()
logo = df["Logo"].values.tolist()
firm_map = df["Firm map"].values.tolist()

driver = webdriver.Chrome("D:\\driver\\chromedriver.exe")
driver.delete_all_cookies()
driver.get('https://www.blogger.com/blog/posts/3793019451239403430')
time.sleep(2)
driver.maximize_window()
time.sleep(2)
driver.find_element_by_id('identifierId').send_keys(email)
time.sleep(3)
driver.find_element_by_id('identifierNext').click()
time.sleep(3)
driver.find_element_by_id('password').send_keys(password)
time.sleep(2)
driver.find_element_by_id('passwordNext').click()
time.sleep(10)

for s in range(len(name)):
    #click new post
    driver.find_element_by_class_name('U26fgb O0WRkf zZhnYe e3Duub C0oVfc zr7Fj zFM5pd M9Bg4d').click()
    #enter name dog
    driver.find_element_by_class_name('whsOnd zHQkBf').send_keys(name[s])
    #convert to html view
    pyautogui.leftClick(627, 707)
    pyautogui.leftClick(455, 206)
    pyautogui.leftClick(149, 279)
    driver.stop_client()

A: You can use undetected-chromedriver, also works for cloudflare bypass and google login
pip install undetected-chromedriver

Your optimized code with undetected-chromedriver, WebdriverWait and By.
import pandas as pd
import pyautogui
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

print("ready?")
print("loading.......................................")
df = pd.read_excel("Moaaz.xlsx","Moaaz")
email = ""
password = ""
name = df["Name"].values.tolist()
website = df["Website"].values.tolist()
phone = df["Phone"].values.tolist()
logo = df["Logo"].values.tolist()
firm_map = df["Firm map"].values.tolist()

driver = uc.Chrome(use_subprocess=True)
wait = WebDriverWait(driver, 15)
driver.delete_all_cookies()
driver.get('https://www.blogger.com/blog/posts/3793019451239403430')
driver.maximize_window()

wait.until(EC.visibility_of_element_located((By.ID, 'identifierId'))).send_keys(email)
wait.until(EC.visibility_of_element_located((By.ID, 'identifierNext'))).click()
wait.until(EC.visibility_of_element_located((By.ID, 'password'))).send_keys(password)
wait.until(EC.visibility_of_element_located((By.ID, 'passwordNext'))).click()

for s in range(len(name)):
    #click new post
    wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'U26fgb O0WRkf zZhnYe e3Duub C0oVfc zr7Fj zFM5pd M9Bg4d'))).click()
    #enter name dog
    wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'whsOnd zHQkBf'))).send_keys(name[s])
    #convert to html view
    pyautogui.leftClick(627, 707)
    pyautogui.leftClick(455, 206)
    pyautogui.leftClick(149, 279)
    driver.stop_client()

A: You need to disable the web security with adding some options to your driver.
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--disable-web-security")
options.add_argument("--allow-running-insecure-content")

driver = webdriver.Chrome("D:\\driver\\chromedriver.exe",options = options)
driver.get('https://www.blogger.com/blog/posts/3793019451239403430')


text:
Q: matplotlib draw ellipse contour I am trying to draw something similar:

The main idea is to draw ellipses with different color in some specific range, for example from [-6, 6].
I have understood that plt.contour function can be used. But I do not understand how to generate lines.

A: I personally wouldn't do this with contour as you then need to add information about the elevation which I don't think you want?
matplotlib has Ellipse which is a subclass of Artist. The following example adds a single ellipse to a plot.
import matplotlib as mpl
ellipse = mpl.patches.Ellipse(xy=(0, 0), width=2.0, height=1.0)
fig, ax = plt.subplots()
fig.gca().add_artist(ellipse)

ax.set_aspect('equal')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)

You then need to research how to get the effect you are looking for, I would have a read of the docs in general making things transparent is done through alpha.


text:
Q: Linux command to print some characters from a long string I have a file called text.txt which contain:
id="qwidget_lastsale" class="qwidget-dollar">$2020.22\div

I really need to print out the word 2020.22 from that text file.
I used the command:
awk '{print $2}' text.txt | grep 2020.22

but my output will print:
class="qwidget-dollar">$2020.22\dev

Which command can I use to print out only 2020.22 from that string?

A: echo 'id="qwidget_lastsale" class="qwidget-dollar">$2020.22\div' | awk '{print gensub(/[^0-9.]+([0-9.]+).*/, "\\1","1", $2)}'
2020.22

In gensub we replace most of $2 with just the numeric component, and then print that using the print statement.

A: you want to extract the dollar value?
$ grep -oP '(?<=\$)[0-9.]+' file


text:
Q: How to compute the duration between two chrono::DateTime? I am using the chrono crate and want to compute the Duration between two DateTimes.
use chrono::Utc;
use chrono::offset::TimeZone;

let start_of_period = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let end_of_period = Utc.ymd(2021, 1, 1).and_hms(0, 0, 0);

// What should I enter here?
//
// The goal is to find a duration so that
// start_of_period + duration == end_of_period
// I expect duration to be of type std::time
let duration = ...

let nb_of_days = duration.num_days();

A: DateTime implements Sub<DateTime>, so you can just subtract the most recent date from the first one:
let duration = end_of_period - start_of_period;
println!("num days = {}", duration.num_days());

A: Seeing the docs of Utc: https://docs.rs/chrono/0.4.11/chrono/offset/struct.Utc.html
By calling either the method .now (or .today) you get back a struct that implements Sub<Date<Tz>> for Date<Tz>, from source you can see it is returning an OldDuration, which is just a type alias around Duration.
Finally, you can use the Duration with the other types implementing Add for it, like DateTime.
So the code should look like this:
let start_of_period = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let end_of_period = Utc.ymd(2021, 1, 1).and_hms(0, 0, 0);

let duration = end_of_period.now() - start_of_period.now();


text:
Q: Postgresql : null values cannot be formatted as an SQL identifier how to resolve this ERROR: null values cannot be formatted as an SQL identifier when trying to select my function:
select ws_sls_core.ars_pricing_test()
ERROR:  null values cannot be formatted as an SQL identifier
CONTEXT:  SQL statement "select string_agg(distinct format('(props ->> %L) as %I', w_order_line_d.matl_grp2_desc, w_order_line_d.matl_grp2_desc), ', ')
                       from ws_sls_core.w_support_pricing_d
    left join ws_sls_core.w_order_line_d
    on w_support_pricing_d.svc_pricing_type = w_order_line_d.matl_grp2_cd"
PL/pgSQL function ars_pricing_test() line 6 at SQL statement

I have checked and the query in use doesn't produce any NULL
select * from ws_sls_core.w_support_pricing_d where svc_pricing_type is
  null

I have tried the below-mentioned code without JOIN and it works fine, I need an additional column and have to use join, and I am only seeing this error.
Here is my complete code
CREATE OR REPLACE FUNCTION ws_sls_core.ars_pricing_test(
    )
RETURNS boolean
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
declare
  l_sql text;
  l_columns text;
begin
    select string_agg(distinct format('(props ->> %L) as %I', w_order_line_d.matl_grp2_desc, w_order_line_d.matl_grp2_desc), ', ')
    into l_columns
    from ws_sls_core.w_support_pricing_d
    left join ws_sls_core.w_order_line_d
    on w_support_pricing_d.svc_pricing_type = w_order_line_d.matl_grp2_cd;
--     and A.svc_pricing_type is not null;

  l_sql :=
    'create or replace view ars_pricing_test as
     select w_support_pricing_d.item_num, '||l_columns||'
     from (
      select w_support_pricing_d.item_num, json_object_agg(w_order_line_d.matl_grp2_desc,w_support_pricing_d.mnth_maint_price) as props
       from ws_sls_core.w_support_pricing_d
        left join ws_sls_core.w_order_line_d
        on w_support_pricing_d.svc_pricing_type = w_order_line_d.matl_grp2_cd
       group by w_support_pricing_d.item_num
     ) t';
  execute l_sql;
  return true;
end;
$BODY$;

ALTER FUNCTION ws_sls_core.ars_pricing_test()


text:
Q: Install Standalone Package Without Internet Connection, No GUI, Windows 10 I have MikTex 2.9 installed from the basic-miktex-2.9.6520-x64.exe file.  I need to install the Standalone package automatically without using the internet whatsoever as well as without any GUI interaction; it needs to be completely automatic.  I tried the following in the command prompt:
mpm --install standalone

But that requires a an internet connection.  I have standalone.tds.zip on my computer as well.  But
mpm --install "path_to_standalone.tds.zip"

doesn't work.  So I tried extracting the contents of this zip to the C:\Program Files\MiKTeX 2.9 directory.  Then I checked the MiKTeX Package Manager, and it reported that it still wasn't installed.  I don't get it and cannot figure this out to save my life.
Given that I'm on Windows 10, have MikTex 2.9 installed, have the standalone.tds.zip file on my computer, what can I do to completely automatically install this package properly without any internet connection?  Command line arguments are ideal here since I can put those in a batch script.


text:
Q: How to hash the security questions in rails? In my data schema for user, I have
  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "password_digest"
  end

To hash the password we have ' t.string "password_digest"', but what if I want to add security question to users?
Is there any default function for hash the answer for security question?

A: If your code is working now, then you presumably have has_secure_password in your model.
This, by default, adds a password accessor to your model, and hashes the value into a column called password_digest.
You can change the column/attribute name by passing the name as the first argument to has_secure_password:
class User < ApplicationRecord

  has_secure_password
  has_secure_password(:security_question_1)
  has_secure_password(:security_question_2)

  ...

This will automatically hash user.security_question_1 = "..." to a column called security_question_1_digest.
Keep in mind:

*

*this method is tailored for storing short user-generated passwords, using BCrypt, which means it has a maximum length of 72 characters.

*this method also adds a validates_confirmation_of validator to your model. You can suppress this by passing validations: false.


text:
Q: Inserting Pandas Dataframe into MySQL table using Autoincrement to automatically generate primary key I've a Pandas dataframe which I'm trying to insert into a MySQL table, using MySQLdb and to_sql. The table has 'allocationid' as primary key and autoincrement..  I will want to do this daily, deleting out the day's previous data from the MySQL table and reinserting updated data from the Pandas dataframe. Hence would like the primary key to autoincrement automatically (I won't be using it down the line, but may want to refer to it).
code is...
columns = ('date','tradeid','accountid','amount')
splitInput = pd.DataFrame(columns = columns)

splitInput['accountid'] = newHFfile['acctID']
splitInput['tradeid'] = newHFfile['Ref']
splitInput['amount'] = newHFfile['AMOUNT1']
splitInput['date'] = newHFfile['Trade Date']

db = MySQLdb.connect(host="(hostIP)", port=3306, user="user", passwd="(passwd)", db="(database)")

cursor = db.cursor()

query = """delete from  splittrades  where date = """ + runymdformat + """ """

cursor.execute(query)

db.commit()

splitInput.to_sql(con = db, name = 'splittrades',if_exists = 'append',flavor = 'mysql',index = False)

db.commit()

db.close()

The problem is that without adding a column for primary key, I get 'OperationalError: (1364, "Field 'allocationid' doesn't have a default value")'
If I add a primary key column and leave it blank, null,  I get OperationalError: (1366, "Incorrect integer value: '' for column 'allocationid' at row 1")
If I use 1 or 0 in the allocationid column I get a duplicated value error msg.
MySQL usually auto-increments the primary key if you don't specify it - is there a way I can make this work from Python?
PS am not a Python expert so pls treat me gently - thanks :-)


text:
Q: What are the advantages and disadvantages of becoming a werewolf? Before I decide whether or not I would like to become a werewolf, I'd like to know what I'll have to deal with. Whether this means being stronger, or having an appetite for human flesh, what are the advantages and disadvantages associated with becoming a werewolf?
I'm particularly interested in if there are any difference between the different races when they become werewolves. For instance, is there any difference between if an orc becomes a werewolf, to if a Khajiit becomes a werewolf?

A: You can become a werewolf once per day for a couple of real-time minutes.  It's excellent for serial killing of low-to-medium-level humanoids (like the Markarth prison), or for the fun of causing a major crime if caught transforming in sight.
When you have the beast blood, you cannot get diseases.  The only disadvantages are that you can never get the "restful sleep" bonuses, and you are doubly vulnerable to silver weapon attacks.  So I recommend that you get the beast blood through the Champions quest chain in Whiterun unless you're going straight through the main quest.

A: While in regular form, there isn't a whole lot of difference between werewolves and non-werewolves, but when you transform, you get a ton of benefits and drawbacks:
Benefits

*

*Increased max health by 100 (non-regenerating)

*Increased max stamina by 100

*Faster sprint speed

*Wolves no longer attack you

*Committing crimes in beast form don't count against your normal form

*Immunity to all diseases, including vampirism (also cures vampirism if you have it)

*Special, werewolf-only abilities like howls

Drawbacks

*

*No looting (when a werewolf)

*No inventory or equipment access (when a werewolf)

*No talking (when a werewolf)

*People either run away from you, cower, or attack you (no friendly humanoid NPCs) (when a werewolf)

*If someone sees you transform, it's automatically a crime

*No rested bonus

*If caught transforming in public it's 1,000 gold bounty to pay

A: IGN's wiki has a good breakdown.
From this page, I can only find one drawback besides the fact that once you are in beast mode certain companions might leave you, and most people will react negatively to you being a werewolf. That drawback is that you cannot use the Rest buff after sleeping, which normally gives you a 5% boost in leveling up skills for 8 hours. It doesn't seem like different classes react differently to becoming werewolves.

A: If you are a werewolf silver weapons do slightly more damage to you than they normally would. This isn't anything you have to worry about though.
However, in beast form silver weapons do double the amount of damage. But really the only people who have silver weapons are werewolf hunters (who are called Silverhand).


text:
Q: ggplot: colour some factor levels manually but not others In R, I'm trying to plot some data using ggplot's geom_point.
Let's simulate some data:
df <- data.frame(x = rnorm(20),
                 y = rnorm(20),
                 z = LETTERS[sample(3, 20, replace = T)])

Essentially, the data are some coordinates associated with a factor label ("A", "B" or "C").
I'd like to plot them all on a scatter plot using ggplot's geom_point, and I'd like to manually set the colour of the "C" point markers. I don't care what colour ggplot sets the markers for the "A" and "B" points.
Here's what I've come up with:
library(dplyr)
library(ggplot2)

df %>%
  filter(z != "C") %>%
  ggplot(aes(x, y)) +
  geom_point(aes(colour = factor(z))) +
  geom_point(data = filter(df, z == "C"),
             aes(x, y), colour = "#C0C0C0")

...which looks like this:

That's exactly what I want, except that the marker for the "C" points doesn't appear in the legend.
Let's try again, slightly differently:
df %>%
  filter(z != "C") %>%
  ggplot(aes(x, y)) +
  geom_point(aes(colour = factor(z))) +
  geom_point(data = filter(df, z == "C"),
             aes(x, y, colour = "#C0C0C0"))

...that gets the "C" marker into the legend, but it's mislabelled and the colour is not correct.
Another try:
df %>%
  filter(z != "C") %>%
  ggplot(aes(x, y)) +
  geom_point(aes(colour = factor(z))) +
  geom_point(data = filter(df, z == "C"),
             aes(x, y, colour = z))

That gets the "C" marker into the legend, labelled properly, and in the correct order, but I can't set its colour.
So to reiterate: how can I manually set the colour of "C", let "A" and "B" be coloured automatically by ggplot, and show "A", "B" and "C" in the legend?

A: Yo canset all colors with  scale_color_manual:
ggplot(df, aes(x = x, y = y, color = z)) + geom_point()+
      scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))

As I know you only can set all or let all automatic. Never tried to fix some.


text:
Q: Not a class, namespace or enumeration? My teacher got me a code to study and I can't figure out when I typedef the map (as i commented in the code) it works fine but when I define without typedef it doesn't seems to work. If someone could be kind to explain I would be grateful! I read something about "cyclic dependency" but not sure if it's the case here.
int main (){

    map <string, string> ri; // typedef map<string, string> maps;
    //maps ri;
    ri.insert(pair<string, string>{"Smoljan", "Dragan"});
    ri.insert(pair<string, string>{"Smolver", "Tina"});
    ri.insert(pair<string, string>{"Mirkovic", "Sonja"});

    string in;
    cout<<"Input:";
    cin>>in;

    string high(in);
    high.back()++;

    auto low = ri.lower_bound(in);

    /*(maps)*/ ri::key_compare comp;  //<----- here is the error

    //....
}

A: Well, cause is clear: ri is not a class, namespace or enumeration. It is an object.
What you need is to place before semicolons what you put with typedef: type name.
map <string, string>::key_compare comp;

or (C++11)
decltype(ri)::key_compare comp;


text:
Q: JSON object as key in key-value pair I see this isn't possible (in JavaScript), would this be due to serialization for persistance?
ActionScript3 does allow object instances as keys flash.utils.Dictionary
Then again, string Id's would serve the same uniqueness purpose of the instance, right?

A: This is what ES6 Map is for, it allows to use an object as key:
var map = new Map();
var obj1 = {};
var obj2 = {}; // identical, but not the same

map.set(obj1, 'value');

map.get(obj1); // 'value'
map.get(obj2); // undefined

Demo (Firefox and IE 11): http://jsbin.com/ehIgEha/1/edit?js,console, browser support: http://kangax.github.io/compat-table/es6/#Map


text:
Q: Python csv tags I have a csv file with different headers.
name,city
john doe,chicago

Have headers as
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames

How will you  run a regex that whenever a tag [name] was to be proceesed it will show "john doe"

A: You could use re.sub() with a function passed as repl, or you could just use string interpolation with a mapping:
print 'My name is %(name)s' % rowdict


text:
Q: Determining Error via IAsyncResult that has WebRequest WebResponse in C# I'm working on a Windows Phone app. Usually I would use a WebClient however, in this specific case I've been told that I need to use a HttpWebRequest. I can successfully fire off the request. However, occassionally it fails. Either because of a network issue or an exception thrown by the server. How do I detect an error associated with the IAsyncResult approach? Currently, I have the following:
private void HttpWebRequest_Completed(IAsyncResult result)
{
  WebRequest request = (WebRequest)(result.AsyncState);
  WebResponse response = request.EndGetResponse(result);

  // Detect if there was an error right here.
  ...
}

My code works fine unless there was an error. I'm not sure how to detect errors though. Thank you!

A: I'd expect EndGetResponse to throw the same exception which would be thrown directly if you'd called the synchronous GetResponse method.


text:
Q: События Event в WinApi Подскажите пожалуйста, вот на MSDN есть пример вызова GetAddrInfoExW, приведу только небольшую часть:

https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfoexw

Там есть пример вызова функции CreateEvent:
QueryContext.CompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

Но, в описании функции CreateEvent на том же MSDN`е нет ни какого QueryContext.CompleteEvent, CreateEvent возвращает обычный HANDLE:
HANDLE CreateEventA(
  LPSECURITY_ATTRIBUTES lpEventAttributes,
  BOOL                  bManualReset,
  BOOL                  bInitialState,
  LPCSTR                lpName
);

Я что то не пойму что такое  QueryContext.CompleteEvent и откуда он вообще взялся ?

A: Прокоментирую для вас код
int __cdecl wmain( _In_ int Argc, PWCHAR Argv[]) {
INT                 Error = ERROR_SUCCESS;
WSADATA             wsaData;
BOOL                IsWSAStartupCalled = FALSE;
ADDRINFOEX          Hints;
QUERY_CONTEXT       QueryContext; // Вот отсюда он взялся

// .. пропускаю кусок

QueryContext.CompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// Создали Event событие
if (QueryContext.CompleteEvent == NULL)
{
  // ...  Если не создалось - ошибка
}
// Делаем вызов
Error = GetAddrInfoExW(Argv[1], NULL, NS_DNS, NULL, &Hints,
                       &QueryContext.QueryResults, NULL,
                       &QueryContext.QueryOverlapped,
                       QueryCompleteCallback,
                       &CancelHandle);
// Так как мы передали Event - ответ должен быть PENDING
if (Error != WSA_IO_PENDING)
{  // Если ответ не PENDING, ответ 0 не будет, а  ошибку обработает код ниже, который в QueryCompleteCallback
    QueryCompleteCallback(Error, 0, &QueryContext.QueryOverlapped);
    goto exit; // и на выход
}
//  Ждем время  QueryTimeout = 5 секунд пока не произойдёт событие
if (WaitForSingleObject(QueryContext.CompleteEvent,
                        QueryTimeout)  == WAIT_TIMEOUT )
{

    wprintf(L"Пишем что недождались ");

    GetAddrInfoExCancel(&CancelHandle); // Отмена вызова

    WaitForSingleObject(QueryContext.CompleteEvent, INFINITE);// Ждём отмену до бесконечности
}

А тут ещё хитрость, они передали каллбек, QueryCompleteCallback (ниже по коду) будет вызвано в то время, пока будет идти первый WaitForSingleObject.
Это обычный механизм обращения с Overlapped-event. Похожее можно делать и с чтением файла и с другими операциями, которые могут растянуться во времени.
HANDLE позволяет хранить в себе какие угодно kernel обьекты. Файлы, pipe-ы, Thread, их список тут а функции собраны тут (msdn) в функциях есть "лишнии" обьекты которые не имеют хандлов.
Есть специальные функции NtQueryObject и подобных - которые могут узнать тип хандла. Особенность хандла в том, что для любого хандла можно делать CloseHandle,  будь то файл, Event, Thread, Process и так далее. Да, в самом низу примера от микрософт - они закрывают хандл. Наверно это для удобства сделано. Так уже сложилось начиная ещё с первых (или вторых) версий винды так принято с хандлами делать.


text:
Q: Protect your delete.php links sended by email How to protect my delete.php files
$id = (int) $_GET['id'];
$delete = $connection->prepare("DELETE FROM `articles` WHERE `id` = :id");
$delete->execute(['id' => $id]);
if($delete->rowCount() > 0){
   echo 'SUCCESS';
}else{
   echo 'ERROR';
}

Lets say am logged in my website panal and my session is on
 $_SESSION['user_id'] = My_ID;

And some hacker send a link in my email while i am logged in

That link is going to delete my article OR WORST a complete main section of my website and that is VERY DANGEROUS. So how can i secure my delete links from that

A: This is a very good example, why it is stated in the HTTP RFC, that GET method should be used only to request the data, while for the data manipulation it's POST method should be used.
And to protect POST forms from this kind of fraud, a usual CSRF protection have to be used. In short, each form should be signed with a secret token, stored in the session as well. So a site will be able to verify, whether the form was issued by the engine.
An example can be found here, preventing csrf in php

A: You can build two step confirm form
When user going to articles/delete.php?id=353, you just calculate some hash 'qweadasdasdqw' and provide link just like this articles/delete.php?id=353&hash=qweadasdasdqw
And just build some form with question 'Do you really want to delete article?'
button 'yes' will provide user to url articles/delete.php?id=353&hash=qweadasdasdqw ,
button 'no' wil provide user to list of article.
so if hash is correct, you will be delete this article
Take a look on the code
$hash = isset($_GET['hash']) ? $_GET['hash'] : null;
$id = (int) $_GET['id'];
if (isset($hash) && (md5($id) == $hash)) { // Check hash
    $delete = $connection->prepare("DELETE FROM `users` WHERE `id` = :id");
    $delete->execute(['id' => $id]);
    if($delete->rowCount() > 0){
       echo 'SUCCESS';
    }else{
       echo 'ERROR';
    }
} else {
    $hash = md5($id); // Generate hash todo use more security function
    echo 'Do you really want to delete this article? yes';
}

A: You could do few things ,

*

*Use post method for data manipulations instead of get.

*You can also make use of tokens, make sure you ,regenerate your tokens

*Don't just check if user is logged in but also make sure the logged in user has permission to delete / update that record .


text:
Q: queues in Laravel 5.1 error I recently Created a job class by the command php artisan make:job --queued and I dispatched it from the controller and it worked fine , and I deleted it again because I don't need it anymore , and I already did an Event class for sending Emails and it's also queued (and worked fine before creating Job Class) the problem now when I trigger php artisan queue:listen I got this Error

[InvalidArgumentException]
  No handler registered for command [__PHP_Incomplete_Class]

and everything was working fine before I created the job class
So What's the problem ?Help me please
Note:
I use the database queue Driver

A: Yes I found it Thank You Sir really it was a pending job So What i did is to download a  package that clears the queues from Github
https://github.com/morrislaptop/laravel-queue-clear
I hope it helps someone has the same problem


text:
Q: Dockerfile returns dns error when trying to create an image I'm trying to build a docker image, return error:

DNS lookup error

Dockerfile:
FROM python:3.7-alpine

LABEL maintainer="r.ofc@hotmail.com"

ENV PROJECT_ROOT /app
WORKDIR $PROJECT_ROOT

RUN apk update \
    && apk add mariadb-dev \
        gcc\
        python3-dev \
        pango-dev \
        cairo-dev \
        libtool \
        linux-headers \
        musl-dev \
        libffi-dev \
        openssl-dev \
        jpeg-dev \
        zlib-dev
RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .

CMD python manage.py runserver 0.0.0.0:8000

i'm runing kubernetes locale useing minikube


text:
Q: Snap Camera on Zoom doesn't work well I have installed Snap Camera on my PC (Windows 7) i can see the Snap Camera in my video setup on Zoom, but when When choose it I just see Snap Camera logo, with some short flicker every 30 sec or so.
BTW, when I open Snap Camera the video+filter looks great. Tried to restart apps, PC, re-install and install both applications, and play with all video definition under Zoom setup (e.g. HW acceleration, but nothing changes it). Please advise.
After checking some more, same thing when I use Skype, so it is most likely not related to zoom only


text:
Q: Asynchronous streams in CUDA do not yield increase in performance I am trying to accelerate the following bit of CUDA code by using multiple streams.
#define N (4096 * 4096)
#define blockDimX  16
#define blockDimY  16

float domain1 [N];
float domain2 [N];

__global__ updateDomain1_kernel(const int dimX, const int dimY) {
    // update mechanism here for domain1
    // ...
}

__global__ updateDomain2_kernel(const int dimX, const int dimY) {
    // update mechanism here for domain2, which is nearly the same
    // ...
}

__global__ addDomainsTogether_kernel(float* domainOut,
                                     const int dimX,
                                     const int dimY)
{
    // add domain1 and domain2 together and fill domainOut
}

void updateDomains(float* domainOut) {
    dim3 blocks((dimX + blockDimX - 1) / blockDimX , (dimY + blockDimY- 1) / blockDimY);
    dim3 threads(blockDimX, blockDimY);

    updateDomain1_kernel<<<blocks, threads>>> (dimX, dimY);
    updateDomain2_kernel<<<blocks, threads>>> (dimX, dimY);
    addDomainsTogether_kernel<<<block, threads>>> (domainOut_gpu, dimX, dimY);
    cudaMemcpy(domainOut, domainOut_gpu, N * sizeof(float), cudaMemcpyDeviceToHost);
}

The precise implementation doesn't really matter; what's important is that updating the respective domains are two completely independent operations, after which both are used in the third kernel call. Hence I thought it a good idea to try to accelerate it by putting each update kernel in its own stream, which I want to run simultaneously. So I changed it to the following:
void updateDomains(float* domainOut) {
    dim3 blocks((dimX + blockDimX - 1) / blockDimX , (dimY + blockDimY- 1) / blockDimY);
    dim3 threads(blockDimX, blockDimY);

    cudaStream_t stream0, stream1;
    cudaStreamCreate(&stream0);
    cudaStreamCreate(&stream1);

    updateDomain1_kernel<<<blocks, threads, 0, stream0>>> (dimX, dimY);
    updateDomain2_kernel<<<blocks, threads, 0, stream1>>> (dimX, dimY);
    cudaDeviceSynchronize();

    addDomainsTogether_kernel<<<block, threads>>> (domainOut_gpu, dimX, dimY);
    cudaMemcpy(domainOut, domainOut_gpu, N * sizeof(float), cudaMemcpyDeviceToHost);

    cudaStreamDestroy(stream0);
    cudaStreamDestroy(stream1);
}

I presumed to find a difference in performance speed, but there is absolutely no noticeable difference. So thinking that maybe the compiler was being smart the first time by automatically scheduling the update calls at the same time, I assumed that the following should slow down the performance:
void updateDomains(float* domainOut) {
    dim3 blocks((dimX + blockDimX - 1) / blockDimX , (dimY + blockDimY- 1) / blockDimY);
    dim3 threads(blockDimX, blockDimY);

    cudaStream_t stream0;
    cudaStreamCreate(&stream0);

    updateDomain1_kernel<<<blocks, threads, 0, stream0>>> (dimX, dimY);
    updateDomain2_kernel<<<blocks, threads, 0, stream0>>> (dimX, dimY);

    addDomainsTogether_kernel<<<block, threads0, stream0>>> (domainOut_gpu, dimX, dimY);
    cudaMemcpy(domainOut, domainOut_gpu, N * sizeof(float), cudaMemcpyDeviceToHost);

    cudaStreamDestroy(stream0);
}

However, again there is hardly any difference in performance speed. If anything, the last one seems fastest. Which makes me think there is something about CUDA streams I do not understand. Can someone enlighten me on how accelerate this code?

A: Increased parallelism only increases your computational throughput if you weren't already using all the cores available. If you already had sufficient parallelism, it won't help you except to increase your synchronization overheads.


text:
Q: Spring JPA - sequence caching gives unexpected behaviour. Using allocation size = 1 is ok My Spring Boot application uses a.o. 2 Entity classes. Entity class 1 uses a technical key id that uses a sequence. The Entity contains a list of other Entities, so a one-to-many. The Child entity uses the same sequence.
Using a seqeuence allocation (cacheing) size of 20, I see that I get EntityExistsException:

javax.persistence.EntityExistsException: A different object with the
  same identifier value was already associated with the session :
  [nl.xyz.app1.entity.ChildFields #123456]

The Entities are:
@Entity
@Table(name = "CHILD_FIELDS")
public class ChildFields implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_entity_seq_gen")
    @SequenceGenerator(name = "my_entity_seq_gen", sequenceName = "MYSEQ_S01")
    @Column(name = "CF_ID", unique = true, nullable = false)
    private Long id;

    @Column(name = "CF_DETAILS_ID")
    private Long detailsId;

And
@Entity
@Table(name = "PARENTS_OBJECT")
public class ParentObject implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_entity_seq_gen")
    @SequenceGenerator(name = "my_entity_seq_gen", sequenceName = "MYSEQ_S01")
    @Column(name = "PF_ID", unique = true, nullable = false)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "CF_DETAILS_ID")
    private List<ChildFields> children;

When I use a allocation sequence of 1, then everything is ok!
Why is this?
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "my_entity_seq_gen" )
@SequenceGenerator(name = "my_entity_seq_gen", sequenceName = "MYSEQ_S01", allocationSize=1)

Etc.

A: Take care when using JPA in combination with DB sequences. A solution is using an allocationSize of 1. I tested this both with Oracle and Progress.
You can find a good explanation via this post. Puspender Tanwar, gives a elaborate explanation!
The issue is solved by changing the Sequence IncrementBy value to the value as I set in allocationSize of JPA.

CREATE SEQUENCE  "APPS"."LINE_LOCQTY_JPA_ID_SQ"  MINVALUE 1 MAXVALUE
  999999999999999999999999999 INCREMENT BY 20 START WITH 7641 CACHE 20
  NOORDER  NOCYCLE ;

The explanation for the issue for the previous Sequence(IncrementBy value 1):

*

*When the JPA required the Id value, it hits the DB Sequence and asks for the unique value, Sequence returns 7641.

*Now JPA has a starting point for ID, and based on allocationSize=20, JPA creates next 20 values itself and generate 7641 to 7660 unique IDs.

*Now when all of these IDs get consumed, JPA asks DB Sequence for next unique value. And since the last value returned was 7641, sequence returns 7642(because INCREMENTBY value was 1 ).

*JPA gets the 7642 and creates next 20 values in cache.

*The time when JPA tries to allocate these values to the ID, it finds 7642 already has been assigned to an entity object(at step 2).

How INCREMENTBY 20 solved the issue: When Ids get consumed at step 3, JPA asks for next value to Sequence. Last value return was 7641, so this time it will increment it by 20 and return 7661. JPA creates values from 7661 to 7680 and uses them. And hence there is no unique key violation issue.


text:
Q: Can't use source code for deprecated control SlidableListItem Microsoft has deprecated SlidableListItem in favour of SwipeControl. I tried SwipeControl using the XAML controls gallery - it does not let me swipe left and right with a mouse (I can using SlidableListItem). I think I need a touchscreen device for it to work.
So I'd like to continue using SlidableListItem despite having updated to the latest nuget packages.
I've copied the code for SlidableListItem into my project from WindowsCommunityToolKit branch 4.0.0. I get this crash when I try to use the control:

System.TypeLoadException: Failure has occurred while loading a
  type.\r\n   at Windows.UI.Xaml.FrameworkElement.MeasureOverride(Size
  availableSize)

(I successfully copied the code for the HamburgerControl into my project yesterday.)

A: I tried to copy the source code of SlidableListItem, after paying attention to the following points, I successfully copied it:

*

*If you don't need SwipeControl, please delete the related code:

*

*Do not copy the code of SlidableListItemSwipeControlTemplate.xaml

*Delete the properties and callback methods related to UseSwipeControlWhenPossible in SlidableListItem.cs (such as OnUseSwipeControlWhenPossibleChanged, OnSwipeControlValueChanged, UpdateSwipeControlItems, etc.)

*In the SledableListItem.cs file, there are two places that refer to the resource file path, please modify it according to your own project structure (you can also delete the relevant code if SwipeControl is not needed)

*If you are migrating the code to your own control library, please remember to introduce SlidableListItem.xaml resource file in App.xaml
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ms-appx:///Controls/SlidableListItem.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

But in fact, SwipeControl is a common control that UWP adapts to the operating habits of different platforms. On the desktop, we hold down the left mouse button and drag and drop is usually used to perform the transfer operation instead of calling out the secondary menu (we usually right-click on the desktop).
Simulating touch screen operation experience in keyboard and mouse mode is sometimes not a pleasant thing. If you plan to adapt to the operation habits of multiple platforms, please refer to this document to add compound commands.


text:
Q: Como obter dados de duas tabelas em mesma coluna? Tenho duas tabelas no banco de dados:

Tabela1
Id      Nome       Sexo
1       NomeA      Macho
2       NomeC      Fêmea

Tabela2
Id      Nome       Sexo
1       NomeB      Macho
2       NomeD      Fêmea

Gostaria de ter o seguinte resultado:

Id      Nome       Sexo       Tabela
1       NomeA      Macho      Tabela1
2       NomeB      Fêmea      Tabela2
1       NomeC      Macho      Tabela1
2       NomeD      Fêmea      Tabela2

Percebam que está em ordem alfabética das duas tabelas.
Como eu poderia fazer um SELECT no SQL Server que retornasse um resultado como este?
Usando Linq com Entity Framework, é possível fazer o mesmo? (Neste caso tem-se db.Tabela1 e db.Tabela2)

A: Se as colunas são as mesmas, você pode usar um SELECT com UNION (se quiser evitar duplicações) ou UNION ALL se quiser exibir o resultado mesmo com as duplicações:
SELECT ID, NOME, SEXO, 'Tabela1' as TABELA
FROM TABELA1
ORDER BY NOME

UNION

SELECT ID, NOME, SEXO, 'Tabela2' as TABELA
FROM TABELA2
ORDER BY NOME

No Entity Framework:
var uniao = db.Tabela1.Select(new {
    Id = Id,
    Nome = Nome,
    Sexo = Sexo,
    Tabela = 'Tabela1'
}).ToList().Union(db.Tabela2.Select(new {
    Id = Id,
    Nome = Nome,
    Sexo = Sexo,
    Tabela = 'Tabela2'
}).ToList()).OrderBy(x => x.Nome);

A: Uma opção que teria é criar um View no SQL Server:
CREATE VIEW vw_Tabelas AS
  SELECT
      [Id]
    , [Nome]
    , [Sexo]
    , 'Tabela1' AS [Tabela]
  FROM
    Tabela1

  UNION

  SELECT
      [Id]
    , [Nome]
    , [Sexo]
    , 'Tabela2'
  FROM
    Tabela2

Assim, o seu query acaba sendo apenas assim:
SELECT [Id], [Nome], [Sexo], [Tabela] FROM vw_Tabelas ORDER BY [Nome]

E o LINQ igual:
var resultados = db.vw_Tabelas.Select().ToList().OrderBy(x => x.Nome);


text:
Q: Given a QGraphicScene and a QGraphicView how can I write a jpg file? Given a QGraphicScene and a QGraphicView how can I write a jpg file from that?
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

QGraphicsScene *scene = new QGraphicsScene();
scene->setSceneRect(-300, -300, 600, 600);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);

qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

myPlot *myplot = new myPlot;
scene->addItem(myplot);

QGraphicsView *view = new QGraphicsView();
view->setScene(scene);
view->setRenderHint(QPainter::Antialiasing);
view->setBackgroundBrush(Qt::yellow);
view->setCacheMode(QGraphicsView::CacheBackground);
view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
view->setDragMode(QGraphicsView::ScrollHandDrag);
view->setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Colliding Mice"));
view->resize(1000, 800);
view->show();

A: QImage img(yourScene->sceneRect().width(), yourScene->sceneRect().height(), QImage::Format_ARGB32);
QPainter painter(&img);
yourScene->render(&painter, yourScene->sceneRect());
img.save("scene.jpg");


text:
Q: Упрощение sql запроса с подзапросами. Oracle Здравствуйте. Нужно упростить запрос но пока что не как не могу понять как это сделать. Идея в том что бы все вложенные селекты переписать в джоины. ПОдскажит пожалуйста как это сделать. Вот мой запрос.
select weight from myTableData
where port = (select port from myTableDict where Name = 'название') and
date = (
    select max(date) from myTableData
    where port = (select port from myTableDict where Name = 'название'));

Это пример моего запроса. Надеюсь всё расписал достаточно понятно. Если нет то пишите объясню. Нужно сделать вместо селектов вложенных, джоины не могу пока что понять как именно это сделать.
План запроса:

udp_port это port, w это myTableData, s это myTableDict.
Собстенно в таблице WEIGHER_DATA, 31 милион записей с небольшим. На ней есть 2 индекса. На поле upd_port и на поле insert_date которое я подписал в примере как date. Стоимость запроса почти под 56 тысяч как по мне многовато. С этой информацией можно как то упростить и понизить стоимость запроса?

A: select max(weight) keep (dense_rank last order by M.port,M.date)
  from myTableData M, myTableDict D
 where D.Name='название' and M.port=D.port

Конструкция KEEP дает значение поля weight для последней (dense_rank last) записи в порядке сортировки по дате. т.е. значение на максимальную дату. JOIN сокращен до запятой и параметры из ON перенесены в where.


text:
Q: How to create a simple plugin in Neo4j? I configured Maven and managed to run example-Plugins like FullTextIndex (https://github.com/neo4j-contrib/neo4j-rdf/blob/master/src/main/java/org/neo4j/rdf/fulltext/FulltextIndex.java).
Still I struggle to create a simple Function by myself. I want to have a java-function that can find a node by ID and return its properties.
I know I can do this in Cypher, but the target is to understand the logic of plugins for Neo4j.
So after importing the plugin i should be able to type in:
INPUT ID
call example.function(217)

OUTPUT e. g.
name = Tree, age = 85, label = Plant, location = Munich

Thanks a lot!

A: In Neo4j, user-defined procedures are simple .jar files that you will put in the $NEO4J_HOME/plugins directory. Logically, to create a new user-defined procedure you will need to generate this jar file. You can do it configuring a new maven project or using the repository Neo4j Procedure Template.
User-defined procedures are simply Java classes with methods annotated with @Procedure. If the procedure writes in the database then mode = WRITE should be defined (not your case).
Also you will need query the database to get the node by ID and return the properties. To do it you will need inject in your Java class the GraphDatabaseService class using the @Context annotation.
To achieve your goal, I believe that you will need to use the getNodeById() method from GraphDatabaseService and the getProperties() in the returned Node.

A: What you are looking for is User Defined Functions / Procedures. There is a dedicated section in the neo4j documentation :
https://neo4j.com/developer/procedures-functions/#_extending_cypher
http://neo4j.com/docs/developer-manual/current/extending-neo4j/procedures/#user-defined-procedures
You can also look at APOC which contains hundreds of such examples used in real life.
https://github.com/neo4j-contrib/neo4j-apoc-procedures


text:
Q: Position Sticky In React. Like the one on official facebook page How to make the div container stick once it reach the top of the view port. I tried it with
position: sticky; top: 0 it only for the top div once the second div moved the div with sticky position also moved. Below s the sudo code.
parent  div ---->
            it has two divs(flexed [1st, 2nd]) ----->
                    Div 1st    Div 2nd
                 |-----------|----------|
                 |  Div 1    |          |
                 |           |    I     |
                 |  Div2     |    N     |
                 |           |    F     |  <<<<<< Infinite  Scroll
 Sticky  >>>>>>> |  Div3     |    I     |
 To the Top      |           |    N     |
         >>>>>>> |  Div4     |    I     |
                 |           |    T     |
                 |           |    e     |
                 |           |          |
                 |           |          |
                 |           |          |
                 |-----------|----------|

                The 1st div has 4 more divs(last two divs should be sticky)
                The 2nd div will have infilite scroll and will not be sticky

I want to acheive the same scroll behaviour when we visit the our profile page on facebook.

A: Use CSS property position: fixed with top left right bottom properties instead of postion: sticky
Div 2nd should have position: relative and there should be another div inside Div 2nd that you want to be stick to a position and give the inner div the property of position:fixed

.right-div{
 position: relative;
}
.stick-div{
position: fixed;
top: 3%;
background-color: black;
right: 13%;
height: 200px;
}

 left div

left div

 sdkasd

sticked to one place


text:
Q: Alternate between windows on launcher click There is no way to set unity to change between opened windows by clicking on the laucher incon?
Everytime I want to change a window of the same program I have to use the keyboard!

A: There is not, exactly. It will focus that application. If you click it while that application is focused though, it should show the zoomed out view of all the application windows and you can click on another that way.


text:
Q: Custom Actionbar icon compatible with other themes the user may choose When creating custom ActionBar icons what happens if the user changes their theme to something  that makes your icon unreadable? Do they have this kind of power?
Example: So say I make an icon for my ActionBar in Holo Dark, so that the icon will be a lighter shade of white. What if the user changes their theme to Holo Light (or can they in my app?), forcing my icon to not be readable because it is also close to the same color as its background? I'm just concerned that if I create a custom app it will not look proper to only certain people.
I have been trying to find something about this but my searches and Google's Iconography pages didn't really give me a clear answer.

A: Android allows setting a themes to application/activity in AndroidManifest.xml, and you can change theme theme dynamically. If a user change their system themes,  it don't affect you application. If you want to change your application/activity themes, you should call setTheme() before setContentView() in Activity.onCreate()


text:
Q: Sorting arraylist of unknown type and throwing an exception if objects are incomparable Here's my test class with sort method :
public class Main {
    public static void main(final String[] args) {
        ArrayList<Person> people = new ArrayList<Person>();

        Person person1 = new Person("Jonas", 36);
        Person person2 = new Person("Petras", 16);

        people.add(person1);
        people.add(person2);

        ArrayList<Integer> ints = new ArrayList<Integer>();
        ints.add(6);
        ints.add(5);

        ints = Main.sortAscending(ints);

        System.out.println(ints);
    }

    public static <T extends Comparable<? super T>> ArrayList<T> sortAscending(
            final ArrayList<T> list) {
        Collections.sort(list);
        return list;
    }
}

It works fine as long as I pass in list of primitive types : string, ints, etc. However when I try to pass in list of my objects it doesn't work.
Here's my class :
public class Person {
    final String name;
    final int age;

    public Person(final String name, final int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("{name=%s, age=%d}", name, age);
    }
}

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(final Person person1, final Person person2) {
        return person1.age < person2.age ? -1 : person1.age == person2.age ? 0 : 1;
    }
}

*

*How can make my method sortAscending work with my class ?

*How do I throw an exception of objects I pass in do not have implemented compare method ?

A: Send instance of your comparator to sort():
Collections.sort(list, new AgeComparator());

A: To use Main.sortAscending you need to implement the Comparable interface on your Person class and implement the compareTo method
public class Person implements Comparable<Person> {
   @Override
   public int compareTo(Person arg0) {
       //your code here to compare object
   }
}

Another option is to use the sort() method and pass your Comparator in.


text:
Q: Bind Duration object with form fields I have class with field of type Duration:
class MyEntity{

private Duration duration;
//getters, setters
}

Now in my thymeleaf template I want to have form with Hours, Minutes and Seconds:
<form method="post" th:action="@{/add}" th:object="${entity}">
     <input type="number" th:field="???" min="0" />
     <input type="number" th:field="???" min="0" max="59" />
     <input type="number" th:field="???" min="0" max="59" />
</form>

In my controller I would like to have something like:
@PostMapping("/save")
public String saveTime(@ModelAttribute MyEntity entity) {
    timeRepo.save(timeData);
    return "redirect:/";
}

Is it possible with thymeleaf to bind model that has something more than just strings and numbers but also another object types or I have to create DTO and care by myself about wrapping/unwrapping the data?

A: Try using a converter, this link may help you if this notion is new for you:
Spring MVC - Binding Java Backing Objects with Custom Converters


text:
Q: Use two entity fields in one form field I'd like to use one text form field to save data in two entity properties. However I didn't found any solution/hint which might lead to a clean implementation.
Consider the following example†:

*

*There is a Doctrine entity with two properties: count, unit

*A user enters "34 apples" in a simple text input field

*The DataTransformer (or whatever is appropriate) should transform this value in such a way that in the underlying entity count = '34' and unit = 'apple' is being saved.

A: you could have a field which is not mapped in the database and in the prePersist and preUpdate methods you would transform the data and save these in the appropriate fields. For example:
/**
 *
 * @ORM\HasLifecycleCallbacks()
 */
class MyClass
{
    private $info;

    /**
     * @ORM\Column(name="count", type="integer")
     */
    private $count;

    /**
     * @ORM\Column(name="unit", type="string")
     */
    private $unit;

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function separateInfo(){
        $infoArray     = explode(' ', $this->info);
        $this->count   = $infoArray[0];
        $this->unit    = $infoArray[1];
    }
}

And in the form you only add the 'info' field:
class MyClassType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('info');
    }
}

This is not tested, but it's the idea which could help you.
I hope this be useful for you.
Kind regards.


text:
Q: I want to send coordinate value from C# code to shader code in Unity I want to send coordinate value from C# code to shader code in Unity.
C# code:
public class SendWorldPositionToShaderProgram : MonoBehaviour {

    void Start () {
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.SetVector("_WorldPosition", transform.position);
        }
    }
}

Shader code:
Shader "Custom/MyRotateShader2" {

    Properties {
        _WorldPosition("WorldPosition", Vector) = (0, 0, 0, 0)
    }
    SubShader {
        Tags
        {
            "RenderType" = "Opaque"
        }

        CGPROGRAM

        #pragma surface surf Lambert vertex:vertex_program
        #include "UnityCG.cginc"

        float4 _WorldPosition;

        void vertex_program(inout appdata_full v)
        {
            float4 wp = _WorldPosition;
            wp.x; // is not real coordinate!
            wp.y; // not too!
            wp.z; // not too!
        }

        void surf( Input IN, inout SurfaceOutput o)
        {

            ...

        }

        ENDCG
    }
    FallBack "Diffuse"
}


text:
Q: Javascript Math returning NaN My math all seems to be correct, but I'm returning a NaN.
The Javascript:
// This section calculates how much the user will have to spend until the average age of life expectancy.
function updatespending() {
  var age = parseFloat(document.forms[0].CurrentAge.value);
  var value = parseFloat(document.forms[0].NetWorth.value);
  if(document.forms[0].sex.value == "male")
     {var yearsleft = Math.round (76 - age);}
  else if(document.forms[0].sex.value == "female")
     {var yearsleft = 81 - age;}
  document.forms[0].AnnualSpending.value = Math.round (value / years left);

The HTML code:

    How much will you have to live off of if you liquidate all of your assets?

        Sex:

        <input type="radio" name="sex" value="male">Male

        <input type="radio" name="sex" value="female">Female

        Current Age:
        <input type="text" onchange="updatespending()" onkeyup="numericOnly(this)" maxlength="2" size="3" value="0" name="CurrentAge" />

        Annual Spending Available:
        $<input name="AnnualSpending" disabled="disabled" readonly />

This is, of course, all encompassed in a form. If I remove the == and put a = , it will return whatever the first if statement says. Anything else returns a NaN. Any help would be greatly appreciated.

A: On your last line you have:
document.forms[0].AnnualSpending.value = Math.round (value / years left);

Shouldn't that be:
document.forms[0].AnnualSpending.value = Math.round (value / yearsleft);

Note the yearsLeft variable.

A: Thorbjørn Kappel Hanser has one part of your problem, the other is:
document.forms[0].sex.value == "male"

note that sex is a radio group, so document.forms[0].sex returns a NodeList that doesn't have a value property. You need to determine which radio button is checked, then get its value, e.g.
function getRadioGroupValue(group) {
  for (var i=0, iLen=group.length; i<iLen; i++) {
    if (group[i].checked) {
      return group[i].value;
    }
  }
}

and then:
var sex = getRadioGroupValue(document.forms[0].sex);
if (sex == 'male') {
  ...
}

A: NaN means NaN meaning you're trying to add either letters or symbols to numbers which isn't possible.