text:
Q: Lefschetz trace formula over truncated Witt ring Let $k$ be a finite field, $W_n(k)$ be its $n$-th truncated Witt ring. We have a Frobenius on $W_n(\bar{k})$ whose fixed point is exactly $W_n(k)$. Let $X$ be a finite type separated scheme over $W_n(k)$, do we have a Lefschetz trace formula describing $\#X(W_n(k))$ by traces of geometric Frobenius on $X_{W_n(\bar k)}$'s $\ell$-adic etale cohomology with compact support?
It's true that etale site is unchanged after closed immersion with nilpotent ideal, but the sheaf may change. For example, in general $H^1(X, \Bbb G_m) \not = H^1(X_{red},\Bbb G_m)$ (see Picard group of non reduced scheme).
Motivation: if $X$ is smooth over $\Bbb Z/p \Bbb Z$, then we have $\#X(\Bbb Z/p^n \Bbb Z)=\#X(\Bbb Z/p\Bbb Z) p^{(n-1)\text{dim}(X)}$ for which I hope to find a cohomological explanation. This is related to Igusa zeta function, and I also want to understand $\#X(\Bbb Z/p^n \Bbb Z)$ for non-smooth $X$.


text:
Q: .NET WCF access to local objects I preface this post with a warning. While I am a fairly competent programmer (if that can be the case when one is fresh out of 4 years of college), I am very new to Windows programming. I am programming in .NET C# (version 4).
I am attempting to create a Windows Service that can be configured remotely via a "client" configuration utility (Windows Forms app). The reason I chose WCF for IPC is because my understanding is that WCF is a replacement for Windows Remoting and that Remoting is being phased out.
My problem is that I can't figure out how to access an already instantiated object from the WCF instance created when the configuration utility connects to the Windows Service.
Perhaps this very simplified code block will give you more of an idea of what I'm attempting to do. (Making it up as I go. Hopefully no embarrassing errors in logic.)
class Blah
{
    /*
     * Create configuration object that is read
     * by myApp and written to by myServ.
    */
    ConfigManager confMan = new ConfigManager();

    MyService myApp = new MyService(ref confMan);
    Thread myAppT = new Thread(new ThreadStart(myApp.init));
    myAppt.Start();
    myAppT.Join();

    //The confServ will handle all of the WCF related stuff
    ConfigServer confServ = new ConfigServer(confMan);
    Thread confServT = new Thread(new ThreadStart(confServ.init));
    confServT.Start();
    confServT.Join();
}

class ConfigManager
{
    public bool someAttribute;

    public ConfigManager()
    {
    }

    public init()
    {
        someAttribute = false;
    }
}

class MyService
{
    ConfigManager confMan;

    public MyService(ref ConfigManager confMan)
    {
        this.confMan = confMan;
    }

    public int init()
    {
        while(1==1)
        {
            if(confMan.someAttribute == true)
                return 0;
        }
    }
}

class ConfServ
{
    ConfigManager confMan;
    public ConfServ(ref ConfigManager confMan)
    {
        this.confMan = confMan;
    }

    public void init()
    {
        //Do all the ServiceHost WCF stuff
    }
}

[ServiceContract]
public interface IModConfig
{
    [OperationContract]
    void changeFalse();
    void changeTrue();
}

/*
 * How can I get my instance of confMan
 * into this instance of ModConfig
*/
class ModConfig: IModConfig
{
    public void changeFalse()
    {
        /*
         * I want to change confMan.someAttribute
         * to false here.
        */
    }

    public void changeTrue()
    {
        /*
         * I want to change confMan.someAttribute
         * to true here.
        */
    }
}

Basically I just want to be able to write to the ConfigManager instance that is being referenced by the MyService instance.
I think I've clearly defined my problem. Let me know if I need to further elaborate or reword my post.

A: While using static fields/properties for storing configuration will technically solve this problem, I would consider it a dirty hack. The more your code depends on static fields, the less scalable it is (what if, at some point in the future, you want to host two identical services in a single process?), and it becomes much more resistant to unit testing.
The correct solution to this is using InstanceContextMode.Single with the WCF framework, and create your WCF service implementation object explicitly, passing it references to whatever core objects it needs:
MyService app = ...
...

WcfService myService = new WcfService( app );
ServiceHost wcfHost = new ServiceHost( myService );
wcfHost.Open();

...

[ServiceBehavior( InstanceContextMode=InstanceContextMode.Single )]
public class WcfService : IYourWcfContract
{
    private MyService _app;

    public WcfService( MyService app )
    {
        _app = app;
    }

    // Implements IYourWcfContract.UpdateConfiguration
    public void UpdateConfiguration( string newConfig )
    {
        _app.UpdateConfiguration( newConfig );
    }
}

Alternatively, you can get rid of the seemingly meaningless delegation, and use your MyService object as the WCF service implementation itself. This, however, is also less desirable (in my view), since it puts another binding on MyService.

A: Where are you keeping your configuration?
public void changeTrue()
{
    // load configuration from some file, database, other storage
    // update configuration
    // persist the new configuration
}

If this configuration is kept in memory, then you can make it a singleton or a static object so that there's only one instance.  Then you just get the single instance and modify it.
By the way, while(1==1) doesn't look right.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image wont display in ReactJS because of path from local storage I am currently trying to display an image using React and using local storage from my pc, not on server for now. Basically, I want to call the pictures that I uploaded, and the filename is already saved inside PostgreSQL database. What I want to do is having a path (my local storage path) that will allows me to render the image. I know we can import pictures at the top using "import .. from image-filepath", but the filename changes according to the user assigned on the database.
Is there any other way for me to execute this? Thank you very much!
File Structure
main folder
  -public
    -uploads
       -location of the image


text: Q: application_start equivalent in web api? I need to execute a method to cache a bunch of data as soon as a web api 2.2 app loads.  I think WebForms had something like an Application_Start event in its Global.asax file.  Does Web API 2.2 have any type of equivalent event where I can trigger the method to cache the necessary data?


text:
Q: how to create a DTO of this object in nestJs? I'm trying to learn NestJs and I'm want to practice it.
I want to learn more about the DTO so I create this sample db.ts and I want to return it using DTO but I don't know how. can someone help me.
to help you understand what I'm trying to do:
I want to create a home route (localhost:8080) this route have a controller will return using a service provider the following object but using a dto.
The service Provider function will be like that.
@Injectable()
export class AppService {
    private week = Week;
    getWeek() : WeekResponseDto[] {
        return (this.week);
    }
}

The DataBase:
export let Week = [
    {
        DayName : "TuesDay",
        TimeZone: [
            {
                First: {
                        Start: 18,
                        end: 19,
                        isReserved: false,
                        reserver: "someone"
                },
                Second: {
                        Start: 19,
                        end: 20,
                        isReserved: false,
                        reserver: "someone"
                },
                Third: {
                        Start: 20,
                        end: 21,
                        isReserved: false,
                        reserver: "someone"
                }
            }
        ]
    },
    {
        DayName : "Wednesday",
        TimeZone: [
            {
                First: {
                        Start: 18,
                        end: 19,
                        isReserved: false,
                        reserver: "someone"
                },
                Second: {
                        Start: 19,
                        end: 20,
                        isReserved: false,
                        reserver: "someone"
                },
                Third: {
                        Start: 20,
                        end: 21,
                        isReserved: false,
                        reserver: "someone"
                }
            }
        ]
    },
    {
        DayName : "Friday",
        TimeZone: [
            {
                First: {
                        Start: 18,
                        end: 19,
                        isReserved: false,
                        reserver: "someone"
                },
                Second: {
                        Start: 19,
                        end: 20,
                        isReserved: false,
                        reserver: "someone"
                },
                Third: {
                        Start: 20,
                        end: 21,
                        isReserved: false,
                        reserver: "someone"
                }
            }
        ]
    }
]


text:
Q: Access Google Analytics without Google Account A company is not using Google Suite and it is against company policy to use personal (consumer) accounts (even Google ones).
There is a need to access Google Analytics - is it possible at all without Google Account?
thanks

A: You can use Google Analytics without a gmail account, however you must still link your current email to Google's services.
Go to https://www.google.com/accounts/NewAccount and select "use my current email address instead."
After this, you will have to verify your email, and you can then use this email address to access Google Analytics.

A: If you are talking about user access to reports within Google Analytics portal - you have to have Google Account for that. GA does not support federated IDs or ADFS.
https://support.google.com/analytics/answer/1009692?hl=en
Accessing data is a different story - your tool (script) can have Google Account to access data, but users of your script, don't have to. Not as robust through. Please have a look at https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on
Another option might be to have a "one for all" user account and often change passwords and have a browser extension to automatically log users in - but that really depends on the organization security policy.


text:
Q: Telegram Bot, how to send a phone number as a link on a message I'm trying to send a message with a phone number as a link. Is there a way to acomplish that? I'm using the Laravel Telegram Bot API
public function start( $telegram, $chatid ) {

        $keyboard = [
            ['Continue'],
        ];

        $reply_markup = Telegram::replyKeyboardMarkup([
            'keyboard' => $keyboard,
            'resize_keyboard' => true,
            'one_time_keyboard' => true
        ]);

        $text = "¡Hola! " . config('constants.emojis.waving-hand') .
            " Hey I'm Bot. " . config('constants.emojis.hug-face') .
            "\nPlease chose some option" .
            config('constants.emojis.glass') . "\nOr contact us at HEREÍ to talk with an specialist.";
        $this->sendMessage( $telegram, $chatid, $text, $reply_markup );

    }

Also here is my send message function
public function sendMessage( $telegram, $chatid, $text, $reply_markup ) {

    if ( !is_null( $reply_markup ) ) {

        $response = $telegram->sendMessage([
          'chat_id' => $chatid,
          'text' => $text,
          'parse_mode' => 'HTML',
          'reply_markup' => $reply_markup
        ]);

    } else {

        $response = $telegram->sendMessage([
          'chat_id' => $chatid,
          'text' => $text,
          'parse_mode' => 'HTML',
        ]);

    }

}

Thanks in advance.

A: you can use the phone number with plus and country code:
+989123456789
if you use that format, telegram automatically link the number!


text:
Q: how to write a script that only acts on new log entries I feel like this should be a simple thing but I am having a hard time figuring it out.
I am trying to write a script that will monitor one of the apache log files and take some specific action.  But how should I go about monitoring the log file?
Everytime a new line is written to log, I want that entry to be checked to see if it matches what I am looking for and if so x happens. When I am doing this manually I used cat or tail -f.  I dont want to run the script every 30 seconds via cron and go through the whole log (or even the last 5 lines), figure out which of those lines are new since the last time the script ran and then so some things.
Is there a way only check the single new entry in the log?

A: Running your script via cron but using logtail or logtail2 to read the file will avoid reading the whole file every minute.  Logtail keeps track of where it last read to and jumps to that point the next time you use it.
If you want to act on new log lines immediately rather than waiting up to 59 seconds between cron invocations, you will have to use tail -f or some equivalent.
Janne's and Khaled's answers both look to solve this problem well.

A: You can make use of the already available Linux tools like tail, grep, and named pipes. First, create a named pipe (fifo) using:
$ mkfifo /tmp/myfifo

Second, create a simple script that will read from this fifo file. Here is a simple example:
#!/bin/bash
pipe=/tmp/myfifo

while true
do
    if read line <$pipe; then
        if [[ "$line" == 'quit' ]]; then
            break
        fi
        echo $line
    fi
done
echo "Reader exiting"

This script reads from the named pipe and prints the line to stdout until it gets the "quit" word. This is just an example that can be customized.
Third, use tail to read new lines that are appended to apache log file and redirect the output to the named pipe.
$ tail -n0 -F /var/log/apache2/access.log | grep some_text > /tmp/myfifo

The -F option means to follow the file by name which should make it immune to logrotate. So, it will follow always the same file name. The -n0 means to not get any old line. The grep is useful to direct only the relevant lines.
Using this solution, you don't need any cron job. Just run the script and the tail command shown above.

A: If you have syslog-ng (probably rsyslogd will do too) as syslog-daemon, you can use that.
Just configure it to keep an eye on Apache log file, or alternatively configure Apache to send logs to syslog facility with CustomLog directive and logger.
Syslog-daemon will then use pattern matching and perform $foo if some match is found. For example, in syslog-ng you can set up a log file hook and filter it like this:
source apache_log { file("/var/log/apache2/access.log"); };
filter apache_match { match("GET /evilscript.php"); };

And then syslog-ng call external script
destination apache_logmatch_script { program("/usr/local/bin/apachematch.pl"); };

Finally put all of those together:
log { source(apache_log); filter(apache_match); destination apache_logmatch_script); };

If using this technique, syslog-ng will spawn your script background waiting for new stuff to appear. Because of this you need to modify your scripts to wait for input from STDIN; here's a short Perl example:
#!/usr/bin/perl -w

$|=1;
while (<>) {
     printf "Stuff happened, I got this entry: %s!\n", $_;
}

I'm not going deeper with my reply until I know you want to try this technique.

A: You could keep a record of the last line you read. On each new run read from the last+1 line to the end of file and update record.
But keep in mind the logfile might get rotated. So you should keep a record of the inode number for example.
fail2ban does implement logfile monitoring the way you seem to want it. Maybe take a look at it? Either you could borrow some ideas or actually use it.

A: You could use diff.  Copy the log file to a temp file.
Take a diff of the live log file and the temp file.
Run the pattern matching on the resultant diff.
Idea taken from the nagios check_log plugin.  See http://www.kilala.nl/Sysadmin/index.php?id=715 for more details.

A: If fail2ban is not suited to your needs, you can try and modify flog.c which was written by Markus J. Ranum:
"This little utility does the equivalent of "tail -f" but is smart
enough to handle changing files if a log rotater moves the file out
from under the user while we're running. Also, unlike "tail -f" this
program is smart enough to exit when the user logs out(!) and will
not spew logs to the pty forever. No effort is made at elegance or
performance."
You can modify to check whether any new line matches your desired pattern and act accordingly.

A: If you want a python solution, check out Pygtail: https://github.com/bgreenlee/pygtail
It's based on logcheck's logtail2 tool

A: #!/bin/bash

while read line;
do
      echo $line > /tmp/output.log
      mail -s 'Event Msg.' 'email@gmail.com' < /tmp/output.log
done < <(tail -n0 -F /var/adm/messages)


text:
Q: missing input file in snakemake below is my snakefile script.
import os
import glob
import yaml

##load config file
configfile: "config/config.yaml"

##ref and query locations
referance = config["reference_loc"]
query = config["query_loc"]

##output file location
output = config["output"]

##sample file name
suffix = [".fsa", ".fasta", ".fa", ".fna", ".fas"]
sample_file = glob.glob(query+"*"+str(suffix))
sample1 = [item.removeprefix(query) for item in sample_file]
sample2 = [item.removesuffix(".fasta") for item in sample1]
sample3 = [item.removesuffix(".fas") for item in sample2]
sample4 = [item.removesuffix(".fsa") for item in sample3]
sample5 = [item.removesuffix(".fna") for item in sample4]
sample = [item.removesuffix(".fa") for item in sample5]

##referance file name
ref_file = glob.glob(referance+"*"+str(suffix))
ref1 = [item.removeprefix(referance) for item in ref_file]
ref2 = [item.removesuffix(".fasta") for item in ref1]
ref3 = [item.removesuffix(".fas") for item in ref2]
ref4 = [item.removesuffix(".fsa") for item in ref3]
ref5 = [item.removesuffix(".fna") for item in ref4]
ref = [item.removesuffix(".fa") for item in ref5]

##rules
rule all:
    input:
        expand(output+"final/{ref}_merged.csv", ref = ref)

rule blast:
    input:
        expand(output+'{sample}_{ref}.txt', sample = sample, ref = ref)

related rules are also found below
rule blast:
    input:
        query=query+'{sample}'+str(suffix),
        ref=referance+'{ref}'+str(suffix)
    output:
        output+'{sample}_{ref}.txt'
    threads:
        workflow.cores
    conda:
        'envs/blast.yaml'
    shell:
        "blastp -subject {input.ref} -query {input.query} -outfmt '6 qacc sacc pident length qcovs evalue mismatch gaps qseq sseq qlen slen sstart send' -out {output} -num_threads {threads}"

rule merge_data:
    input:
        rules.blast.output
    output:
        output+"final/{ref}_merged.csv"
    conda:
        'envs/pandas.yaml'
    scripts:
        ../scripts/pd_blastresults.py'

i get a return message with the following message,
snakemake --cores 14 --use-conda all
Building DAG of jobs...
MissingInputException in line 39 of /home/user/Desktop/newtest/workflow/Snakefile:
Missing input files for rule all:
    affected files:
        /home/user/Desktop/data/results/final/GlpTReferenceNC_000913.3_merged.csv

and if i use the other rule i also get a similar message
snakemake --cores 14 --use-conda blast
Building DAG of jobs...
MissingInputException in line 43 of /home/user/Desktop/newtest/workflow/Snakefile:
Missing input files for rule blast:
    affected files:
        /home/user/Desktop/data/results/GlpTCP014497.1_GlpTReferenceNC_000913.3.txt
        /home/user/Desktop/data/results/GlpTCP063774.1_GlpTReferenceNC_000913.3.txt
        /home/user/Desktop/data/results/GlpTCP014488_GlpTReferenceNC_000913.3.txt
        /home/user/Desktop/data/results/GlpTCP103710.1_GlpTReferenceNC_000913.3.txt
        /home/user/Desktop/data/results/GlpTCP014522.1_GlpTReferenceNC_000913.3.txt

And i have trying so much to figure out what is happening, i don't seem to find the issue. Help is much appreciated. Thank you.
what i tried to do is:

*

*specify locations for each files and not through wildcards, and make the script work on each alone, also got the same errors.

*kept sample wildcards and only specified ref location, still same issue

*re-wrote the whole snakefile, same error.
i did not uninstall snakemake or conda yet, i want to find a solution before i try this way.
Edited after euronion answer,
that helped me figure out the issue. i added all the rules to the main sankefile and found out what was happening there.
    import os
    import sys
    import glob
    import yaml
    import pandas as pd

    ##load config file
    configfile: "config/config.yaml"

    ##ref and query locations
    referance = config["reference_loc"]
    query = config["query_loc"]

    ##output file location
    output = config["output"]

    ##sample file name
    suffix = [".fsa", ".fasta", ".fa", ".fna", ".fas"]
    sample_file = glob.glob(query+"*"+str(suffix))
    sample1 = [item.removeprefix(query) for item in sample_file]
    sample2 = [item.removesuffix(".fasta") for item in sample1]
    sample = [item.removesuffix(".fa") for item in sample2]
    print(sample)

    ##rules
    rule all:
        input:
            expand(output+"final/{sample}_merged.csv", sample = sample)

    rule blast:
        input:
            query=query+'{sample}.fasta',
            ref=referance
        output:
            output+'{sample}.txt'
        threads:
            workflow.cores
        conda:
            'envs/blast.yaml'
        shell:
            "blastp -subject {input.ref} -query {input.query} -outfmt '6 qacc sacc pident length qcovs evalue mismatch gaps qseq sseq qlen slen sstart send' -out {output} -num_threads {threads}"

    rule merge_data:
        input:
            rules.blast.output
        output:
            output1=output+"final/{sample}_merged.csv"
        conda:
            'envs/pandas.yaml'
        script:
            "../scripts/pd_blastresults.py"

but now i got into another issue is specifying my different reference files, i'll just figure that later.


text:
Q: MySite - Audiences and Trusted Host location I am bit confused about this theory. Our current farm is only 1 production multi-server farm, 1 TEST and 1 DEV multi-server farm. I dont have same farm replicated in Europe or Asia. It's only 1 farm in Michigan. Do I need to worry about target/manage audiences and setup Trusted my site host location?
This (https://technet.microsoft.com/en-us/library/cc262500.aspx#geodist) article talks about "Trusted My Site host locations" where it's applicable if you have multi-farm setup.
Please advise.
Note: Our parent company (Insurance) has global SharePoint farm where farms are setup in US, Europe, Asia, Africa and I can see they are implementing this option to prevent users from creating multiple mysites.
Now, if I am on Michigan based (child company) intranet site (different url, hosted in different data center but same domain) and I am able to create a mysite. Would it possible when a user go to the parent sharepoint site and their mysite not be generated since employee from michigan are in different OU of active directory.

A: Simple answer would be you should be using the same MySite host as the rest of the organization. MySite is closely linked with the User Profile and Search Service configuration and being in different OU's would not matter as long as they have been included in the AD connection configuration in the User Profile Service Application of the farm hosting the common MySite. There are obvious benefits of having a common MySite host for the organization as that would mean no need for duplication or replication of content and users would have the same MySite personal site from the common MySite host.
From the article you posted, I think these statements from Microsoft drive the point above:

*

*An enterprise services farm sharing a single User Profile service application together with one or more consuming farms. The My Sites Host is located on one of the consuming farms. In SharePoint Server 2013, the consuming farm must be physically located in the same datacenter as the enterprise services farm when you share the User Profile service application. Consuming the User Profile service application from another farm over a WAN connection is not supported. This means that both the User Profile service application and the My Site Host must be located in the same datacenter.

*For example, in a server farm deployment that spans geographic regions, you might have separate User Profile service applications for each region or regional server farms in the environment. By default, a user can create a different My Site in each User Profile service application or server farm, which could cause unwanted results from both an administration perspective and a user perspective. When you have multiple My Sites for an individual user in an organization, server resource needs increase. Additionally, users might not understand or want multiple My Sites.
To prevent individual users from creating multiple My Sites, configure trusted My Site host locations. When specified, users are redirected to the single My Site host location that is intended for their accounts regardless of where they are browsing when they attempt to create or access their My Sites. This feature ensures that each user can create only one My Site in an organization.


text:
Q: kubeadm join command fails due to possibly incorrect preflight check I recently set up a kubernetes cluster on AWS (EC2 Classic).
I followed this documentation: http://kubernetes.io/docs/getting-started-guides/kubeadm/
When it came to joining my slaves to my cluster, the kubeadm join command failed with:
Running pre-flight checks
preflight check errors:
    /var/lib/kubelet is not empty

As far as I understand it, all nodes need to have the kubelet installed. I think this is a bugged preflight check (https://github.com/kubernetes/kubernetes/issues/36987). How do I get around it to join my node to my cluster?

A: There is a flag to skip the preflight checks:
kubeadm join --skip-preflight-checks --token=TOKEN MASTER_IP

A: It would be safe to installed kubeadm on all the machines as now it installed kubectl, kubelet as well along with kubeadm....
then try to run your command. Please ensure whatever version of kubelet you are running it should be compatible for kubeadm running on master machine...


text:
Q: Learning Curves: Should the training set size be increased incrementally or Random Selection? I am trying to write a bespoke learning curve function. I was wondering how is it usually implemented. When the size of the training set is increased - Is it normally increased by adding new samples to the already existing set incrementally? Or is the training size size is selected randomly?
To give an example: Suppose the train-set size ratios are [0.2, 0.3, 0.4 ...], then when we go from 0.2 to 0.3, do we add an extra 0.1 on top of what existed before(0.2) incrementally? Or do we just get another random sample from the full set?

A: I think you should get another fully random sample. This can help if, for example, the first iteration of the sample is biased, one way or another.

A: In my experiments, I always create increasing training set sizes by adding samples to the already existing set. So, essentially my training set at each step is $T_1 \subset T_2 \subset \ldots T_n$. However, I ensure I use the same seed throughout and then run my experiments with different seeds. So, my final training sets look like,
$$T_{11} \subset T_{12} \subset \ldots T_{1n}\\
T_{21} \subset T_{22} \subset \ldots T_{2n}\\
\vdots \\
T_{m1} \subset T_{m2} \subset \ldots T_{mn}$$
Then I report the results averaged over these m experiments.
There is a reason why increased training set sizes are created by adding samples. Most algorithms have stochastic behavior when it comes to generalization. If you want to show increasing performance or decreasing loss  curves with respect to training set sizes, it become difficult to portray this behaviour in the presence of variability of performance with random training sets. That is if the curves are not as expected you don't know what went wrong - whether it was the training sample or your model not performing as expected. However, by keeping these increasing superset of training samples, we can say something about what went wrong if the curves still are not as we expected them to be.


text:
Q: execute ping command with GUI While writing a GUI application in PyQt5 I encounter weird(for me) behavior.
When I wanted to open an information window and start doing another thing after it fully loads. I noticed that the information window does not load fully until the next block of code is done.
This is how it looks

Code that reproduces this unwanted behavior
from PyQt5.QtWidgets import QApplication,QMessageBox
import sys
import os
app = QApplication(sys.argv)

box = QMessageBox()
box.setText("Text")
box.show()
os.system("ping 8.8.8.8 ")

sys.exit(app.exec())

Behavior is the same whether I use QMessegBox, inherit it in another class or write my own QMeesgeBox type class.
I guess this behavior works like this because of os.system() function and I would use Process or Thread to make a workaround, but if It is possible I would like to ensure that window is fully loaded and then the next procedure is taking place.
Python version 3.7.0
PyQt5 version 5.12.1

A: Although the solutions of S.Nick and Guimoute seems to work but the reality is that it has only made the window show a moment but if you want to interact with it you will see that it is frozen, for example try to move the window to check it. The os.system() task is blocking so it must be executed in another thread
import os
import sys
from PyQt5.QtWidgets import QApplication,QMessageBox

import threading
app = QApplication(sys.argv)

box = QMessageBox()
box.setText("Text")
box.show()

def task():
    os.system("ping 8.8.8.8 ")
threading.Thread(target=task, daemon=True).start()
# or threading.Thread(target=os.system, args=("ping 8.8.8.8 ",), daemon=True).start()
sys.exit(app.exec_())

Or use QProcess:
import sys
import os
from PyQt5.QtWidgets import QApplication,QMessageBox
from PyQt5.QtCore import QProcess

app = QApplication(sys.argv)

box = QMessageBox()
box.setText("Text")
box.show()

def on_readyReadStandardOutput():
    print(process.readAllStandardOutput().data().decode(), end="")

process = QProcess()
process.start("ping", ["8.8.8.8"])
process.readyReadStandardOutput.connect(on_readyReadStandardOutput)
sys.exit(app.exec_())

Update
import os
import sys
from PyQt5 import QtCore, QtWidgets

class PingObject(QtCore.QObject):
    finished = QtCore.pyqtSignal()

    @QtCore.pyqtSlot()
    def start(self):
        os.system("ping 8.8.8.8")
        self.finished.emit()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    box = QtWidgets.QMessageBox()
    box.setText("Text")
    box.show()
    thread = QtCore.QThread()
    thread.start()
    ping = PingObject()
    ping.moveToThread(thread)
    QtCore.QTimer.singleShot(0, ping.start)
    loop = QtCore.QEventLoop()
    ping.finished.connect(loop.quit)
    loop.exec_()
    print("finished ping")
    sys.exit(app.exec_())

Another Option:
import os
import sys
from PyQt5 import QtCore, QtWidgets

class Thread(QtCore.QThread):
    def run(self):
        response = os.popen("ping 8.8.8.8")
        for line in response.readlines():
            print(line)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    box = QtWidgets.QMessageBox()
    box.setText("Text")
    box.show()

    thread = Thread()
    thread.start()
    ret = app.exec_()
    thread.quit()
    thread.wait()
    sys.exit(ret)

A: Here is a single-line solution:
from PyQt5.QtWidgets import QApplication,QMessageBox
import sys
import os
app = QApplication(sys.argv)

box = QMessageBox()
box.setText("Text")
box.show()
QApplication.processEvents() # <------------ this one
os.system("ping 8.8.8.8 ")

sys.exit(app.exec())

A: As an option. Try it:
import sys
import os
from PyQt5.QtWidgets import QApplication,QMessageBox
from PyQt5.QtCore import QTimer

app = QApplication(sys.argv)

box = QMessageBox()
box.setText("Text")
box.show()

def osSystem():
    os.system("ping 8.8.8.8 ")

QTimer.singleShot(20, osSystem )

#os.system("ping 8.8.8.8 ")

sys.exit(app.exec())


text:
Q: DocumentDB readCollection function error I'm trying to use the "readCollection" function, but I get an Error:

The "options" parameter must be of type "object". Actual type is:
  "function".

my code:
docDbClient.readCollection(docUrl, function (err, collection) {
   console.log(collection);
}, function(err){
    console.log(err);
});

The docUrl var is equal to my document._self path.
This code was working before, but for some reason it not anymore without me making any changes.
From what the error says the 'option' parameter needs to be an object instead of a function, but from what I read on the documentation the 'option' parameter is optional which I don't have it with in my function.
I'm also getting the same error when I use the replaceDocument function.
http://azure.github.io/azure-documentdb-node/DocumentClient.html#readCollection

A: The problem is that you have an error handling function in your parameter list, which causes it to think that the second parameter is options. Remove the error handling function, and add code inside your main handler to process it if err does not come back null.


text:
Q: How do I create a framed box using stars as the frame and dashes on the inside? I need to create a box made of stars that is filled with dashes on the inside.
This is for a homework assignment. I have a rough outline of code to use, but I am unsure how to get the stars into a box and dashes on the inside instead of stars.
GNU nano 3.2                                           1017.c

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <unistd.h>

    int main()
    {
        int sp, r, line;
        int k;

       for(line = 0; line <5; line++)
       {
           for(k = 0; k < 5; k++)
           {
               for(r = 0; r < sp; r++)
                   printf(" ");
               printf("*");
           }
           printf("\n");
       }

    return 0;
    }

This is what I should be getting:
*******
*-----*
*-----*
*-----*
*-----*
*******

But my actual output has been:
  *       *        *      *    *
      *       *   *          *  *
   *        * *          *    *
       * *       *   *       *
  *         *        *          *   *

A: You need a condition expression to check whether you are filling a boundary or the interior. You need to check if it is the first row or last row, or first column or last column (those are your boundaries where you output '*'), otherwise you output out fille ('-'). Similar to:
#include <stdio.h>

#define ROWS 5
#define COLS ROWS

int main (void) {

    int r, c;
    for (r = 0; r < ROWS; r++)
    {
        for (c = 0; c < COLS; c++)
        {
            if (!r || r == ROWS-1 || !c || c == COLS-1)
                putchar('*');
            else
                putchar('-');
        }
        putchar('\n');
    }

    return 0;
}

Example Use/Output
$ ./bin/hboxfilledex
*****
*---*
*---*
*---*
*****

Look things over and let me know if you have further questions.

A: Here you go (formatting is horrible because entering code on here sucks. But this code will work nonetheless):
#include <stdio.h>

void print_rectangle(int n, int m)

{

int i, j;

for (i = 1; i <= n; i++)

{

for (j = 1; j <= m; j++)

{

if (i==1 || i==n || j==1 || j==m)

 printf("*");

else

 printf("-");

 }

printf("\n");

 }

}

int main()

{

int rows = 6, columns = 7;

print_rectangle(rows, columns);

return 0;

}


text:
Q: C# Replacing an Object in a class of Objects dynamically ~ I guess this is my 2nd post kinda on the same topic, kinda...
Anyway, I would like to update my agents AIbundles class dynamically by passing an AI behavior to replace or add:
*Not Working code
public class agent
{
    AIbundles = new AIbundle();

    public void UpdateBehavior (object Behavior)
    {
        object CastedBehavior = (Behavior.type) Behavior; //Cast
        this.agent.AIbundles.(Behavior.type) = CastedBehavior;
    }
}

Example of my AIbundles class (extremely simplified)
public class AIbundles
{
    ExampleBehavior1 ExampleBehavior1;
    ExampleBehavior2 ExampleBehavior2;
    ExampleBehavior3 ExampleBehavior3;

    AIbundles()
    {
        ExampleBehavior1 = new ExampleBehavior1();
        ExampleBehavior2 = new ExampleBehavior2();
        ExampleBehavior3 = new ExampleBehavior3();
    }
}

Sadly I am quite aware that this is a very bad way of implementing this, is there a better way of handling objects dynamically?

A: It looks to me like your ExampleBehavior classes should extend some base type (whether it's an abstract class or an interface depends on your situation). Let's call the base type BehaviorBase. Then your AIBundle class should have a property of type BehaviorBase called Behavior, and you can do something like this, without any sort of casting:
public void UpdateBehavior(BehaviorBase behavior) {
   this.agent.AIbundles.Behavior = behavior;
}

Which you would call like this:
var agent = ...;
var someAIThing = initWithAgent(agent);
BehaviorBase behavior = ...;
someAIThing.UpdateBehavior(behavior);

At this point, I would strongly consider eliminating the UpdateBehavior method and simply assign the behavior to the property directly:
var agent = ...;
var someAIThing = initWithAgent(agent);
BehaviorBase behavior = ...;
agent.AIBundles.Behavior = behavior;

A: Maybe you should not create a property of each type within your "collection" like class.
Instead use a Dictionary if you want to retrieve the right behavior by name.
Or simply a List of behaviors.
Each behavior could have something like a name or type property, to identify it, if needed.
You could also just have a IBehavior interface which has methods which are common...
something like this might do it for you I think:

    public class AIbundles
    {
        public Dictionary<string, IExampleBehavior> ExampleBehaviors { get; set; }

        public AIbundles()
        {
            this.ExampleBehaviors = new Dictionary<string, IExampleBehavior>();
        }

    }

    public class agent {
        AIbundles bundles = new AIbundles();

        public void UpdateBehavior (IExampleBehavior behavior)
        {
            this.bundles.ExampleBehaviors[behavior.Name] = behavior;
        }
     }


text:
Q: FancyBox Images Aren't Loading Correctly I'm using a combination of the Masonry and Fancybox plugins to create a photo gallery, but the images loaded by FancyBox aren't displaying correctly. They are forced to the right side of the screen, and are taking too much space. I should also note that both the white border and the arrow buttons aren't appearing, and that you can't close the images by clicking outside of them. Here is a screenshot of my page.

The gallery is on the left, and the loaded image is forced to the right side of the screen. It's also considerably larger than it should be. Here's the code I'm using.
Links
<link href="css/styles_desktop.css" type="text/css" rel="stylesheet" />
<link href="fancyapps-fancyBox-18d1712/source/jquery.fancybox.css" type="text/css" />
<link href="fancyapps-fancyBox-18d1712/source/helpers/jquery.fancybox-buttons.css" />

CSS
div#gallery {
    width: 990px;
    margin: 10px auto;
}

.item {
    width: 330px;
    display: inline-block;
}

jQuery

HTML

A: jquery.fancybox.css file not loaded properly in your site. Please  copy the all style from jquery.fancybox.css and insert into style.descktop.css file. It will works fine. Seems It is an issue.


text:
Q: File permissions using cacls, icals for USB drive in FAT format? I'm creating a desktop application. This application runs only if its in USB drive. In my application i used MS DOS commands like cacls, icals for giving access permission. My problem is, these commands will work only if the USB drive is in NTFS format only, when I change the file format to FAT the above commands doesn't work. Is there any possible to run this commands when the USB drive in FAT. Thanks in advance.

A: The FAT filesystem doesn't have a rich set of file permissions like NTFS does, so depending on what you need to do with these permissions, you might be out of luck.


text:
Q: Parsing JSON giving "unexpected token o" error I am having a problem parsing simple JSON strings. I have checked them on JSONLint and it shows that they are valid. But when I try to parse them using either JSON.parse or the jQuery alternative it gives me the error unexpected token o:
<!doctype HTML>
<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
      var ques_list = JSON.parse(cur_ques_details);

      document.write(ques_list['ques_title']);
    </script>
  </body>
</html>

Note: I'm encoding my strings using json_encode() in PHP.

A: Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

A: Try parse so:
var yourval = jQuery.parseJSON(JSON.stringify(data));

A: Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o". if you need to get it as string, you could use JSON.stringify()

A: I had the same problem when I submitted data using jQuery AJAX:
$.ajax({
   url:...
   success:function(data){
      //server response's data is JSON
      //I use jQuery's parseJSON method
      $.parseJSON(data);//it's ERROR
   }
});

If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text", data is a JSON string. Then the use of $.parseJSON is okay.

A: Using JSON.stringify(data);:
$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});

A: The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
<!doctype HTML>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
            var ques_list = JSON.parse(cur_ques_details);
            document.write(ques_list['ques_title']);
        </script>
    </body>
</html>

As the other respondents have mentioned, the object  is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
<!doctype HTML>
<html>
<head>
</head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
            document.write(cur_ques_details.ques_title);
        </script>
    </body>
</html>

A: cur_ques_details is already a JS object, you don't need to parse it

A: I was seeing this unexpected token o error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object] instead of {}. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.


text:
Q: Oracle Webcenter Content Fast Checkin not working with Siebel iFrame I have enabled fast checkin on WCC through adding useFastCheckin=1 as an addition configuration variable.
However, now when users upload documents to WCC through the Siebel Iframe, the documets are not displaying on the Iframe after being uploaded.
The document is available in WCC if you search for it but no documents are visible in the iFrame.
Then when removing the useFastCheckin=1 on WCC, the documents display on siebel iFrame as normal.
Does anyone have a solution for this to allow for WCC to use fast checkin and show the documents on the iFrame?

A: I managed to find a solution to the issue that I was facing in my above question.
I added the following two additional configuration variables to WebCenter Content General configuration:
UseSearchCache=false
SearchCacheMaxItemAgeInMinutes=0
and voila problem solved.


text:
Q: JsonCpp ambiguous overload only in Windows I need to read a json file with jsoncpp library.
I have this file:
{"one":false,"two":[{"id":"first"},{"id":"second"}],"three":550}
If i need to read only the first id of "two" element, i use:
std::string contents; //Contain the file
Json::Value root;
Json::Reader reader;
reader.parse(contents, root, false);
std::string aux = root["two"][0]["id"].asString();

It works fine in Linux, but when i try it in Windows i have this error:
error: ambiguous overload for 'operator[]' in 'root.Json::Value::operator[](((const char*)"two"))[0]'
Why it happens and how can i fix this? Thanks.
Solved: There are two operator[], one with an int as parameter and other with a const char as parameter, and the compiler doesn't know who to use in Windows, but yes in Linux. Now i use [0u] instead [0] to indicate a number as parameter and it works fine.

A: This drove me crazy, until I stumbled upon this question, I mysteriously figured it out:
Just cast it to Json::Uint (for some reason), or use 'u':
MapEvent::MapEvent(Json::Value& val)
{
    operator_enum = val.get(0u, "").asString();
}


text:
Q: Файл отправки почтовых шаблонов в Битриксе Подскажите, пожалуйста, где в Битриксе находится файл отправки почтовых шаблонов? На сайте есть форма, которая сделана через "Сервисы" - "Веб-формы", к которой прикреплен почтовый шаблон. Боты уже совсем одолели своим спамом. Пытался сначала в шаблоне формы работать - боты всё равно отправляют форму.
В форме action указывает только на страницу, на которой находится форма (/contacts/). Если это поможет, то стоит решение Аспро (aspro_tires2).

A: Почтовые шаблоны находятся по пути: site.ru/bitrix/admin/message_admin.php?lang=ru, далее вам надо найти нужный почтовый шаблон/шаблоны и поправить.
Сам "файл отправить почтовых шаблонов" (конечно не правильно так говорить), он не один и не стоит в этих файлах код менять. Легче тогда воспользоваться перехватом события отправки почты (документация) и как-то проверять, что форму заполнил не бот.
Но зачем такие муки, когда можно подключить "капчу"? Та же капча от битрикса или от гугля версии 2 или еще лучше версии 3, причем Аспро поддерживает капчу от гугля обоих версий в некоторых решений своих разработок. И капча поможет избавиться от 99% спама.


text:
Q: Writing Styled Text to a .docx file I'm trying to write an application that will write text to a .docx file. My application uses a JTextPane so the user can write whatever he/she wants, and it also provides many buttons such as bold, font color, font size... ect. What I'm having a problem with is maintaining the style of the text on the JTextPane to when I write to the .docx file. I'm fairly new to Swing and Apache POI so example code and/or a detailed explanation would be helpful.
What I have is this: (pad refers to the JTextPane)
FileOutputStream output = new FileOutputStream(file);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(pad.getText());
document.write(output);
output.close();

A: For my example I assume you'd use a HTMLEditorKit in your JTextPane. I would then parse the StyledDocument of the pane and set the textruns accordingly.
Of course this is just a starter, you'd need to parse all the possible styles and convert them yourself in the loop below.
I've to admit, that I've never done something with the HTMLEditorKit and therefore I don't know how to handle the CSS.CssValues properly.
import java.awt.Color;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import org.apache.poi.xwpf.usermodel.*;

public class StyledText {
    public static void main(String[] args) throws Exception {
        // prepare
        JTextPane pad = new JTextPane();
        pad.setContentType("text/html");
        HTMLEditorKit kit = (HTMLEditorKit)pad.getEditorKit();
        HTMLDocument htmldoc = (HTMLDocument)kit.createDefaultDocument();
        kit.insertHTML(htmldoc, htmldoc.getLength(), "
paragraph 1
", 0, 0, null);
        kit.insertHTML(htmldoc, htmldoc.getLength(), "
paragraph 2
", 0, 0, null);
        pad.setDocument(htmldoc);

        // convert
        StyledDocument doc = pad.getStyledDocument();
        XWPFDocument docX = new XWPFDocument();

        int lastPos=-1;
        while (lastPos < doc.getLength()) {
            Element line = doc.getParagraphElement(lastPos+1);
            lastPos = line.getEndOffset();
            XWPFParagraph paragraph = docX.createParagraph();
            for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) {
                final Element frag = line.getElement(elIdx);

                XWPFRun run = paragraph.createRun();
                String subtext = doc.getText(frag.getStartOffset(), frag.getEndOffset()-frag.getStartOffset());
                run.setText(subtext);

                final AttributeSet as = frag.getAttributes();
                final Enumeration<?> ae = as.getAttributeNames();

                while (ae.hasMoreElements()) {
                    final Object attrib = ae.nextElement();

                    if (CSS.Attribute.COLOR.equals(attrib)) {
                        // I don't know how to really work with the CSS-swing class ...
                        Field f = as.getAttribute(attrib).getClass().getDeclaredField("c");
                        f.setAccessible(true);
                        Color c = (Color)f.get(as.getAttribute(attrib));
                        run.setColor(String.format("%1$02X%2$02X%3$02X", c.getRed(),c.getGreen(),c.getBlue()));
                    } else if (CSS.Attribute.FONT_WEIGHT.equals(attrib)) {
                        if ("bold".equals(as.getAttribute(attrib).toString())) {
                            run.setBold(true);
                        }
                    }
                }
            }
        }

        FileOutputStream fos = new FileOutputStream("test.docx");
        docX.write(fos);
        fos.close();
    }
}


text:
Q: Responsive jQuery slider Has anyone ever heard of a jQuery slider that is responsive and allows images with different widths?
Thanks

A: unoslider.heroku.com is the best responsive slider I've seen recently

A: http://docs.jquery.com/UI/Slider
use your own images

A: Sure you can use the original Slider that comes with JQuery as @cpjolicoeur mentioned above.
You may also try these following:

*

*Responsive Image Gallery with Thumbnail Carousel

*Blueberry
I have used FlexSlider on many responsive websites. But dont know why their site is down. But still you can keep that in your list.
Thanks
Shajed Evan

A: One good jQuery plugin that has been around for a while is CarouFredsel (yes, with Fred in the middle). Here is the link:
http://caroufredsel.frebsite.nl/
They have nice demos for responsive/fluid carousels:
http://caroufredsel.frebsite.nl/examples/responsive-carousels.php

A: Here is an example
http://jsfiddle.net/y2CeN/
Here also in carousel
http://jquery.malsup.com/cycle2/demo/carousel.php
Both cycle2 using jquery

A: Liquid Slider is one that I made. Email me if you have any questions about it. It's pretty powerful, yet simple and to the point. I have been making tutorials for it as well.

A: You want one of these:
http://bxslider.com/ BXSlider
http://unslider.com/ UnSlider


text:
Q: Assembly-TASM: on-screen button in graphic mode I was wondering what's the simplest way to know whether a mouse was clicked between a certain range of pixels, i.e to display a rectangular button in graphic mode and find out if the user clicked on it.
Thanks!

A: The same mouse driver function that informs you about the mouse being clicked, also tells you where the mouse was at that moment.
Next code waits for a left button click:
NoLeftClick:
    mov     ax, 0003h   ; MOUSE.GetMousePosition
    int     33h         ; -> BX CX DX
    test    bx, 1       ; Is left button down?
    jz      NoLeftClick ; No

Once the click arrives you start comparing the coordinates that you got in CX (X) and DX (Y) with the coordinates of the rectangle that interests you:
    cmp     cx, UpperLeftCornerX
    jb      Outside
    cmp     cx, LowerRightCornerX
    ja      Outside
    cmp     dx, UpperLeftCornerY
    jb      Outside
    cmp     dx, LowerRightCornerY
    ja      Outside
Inside:
    ...
Outside:
    ...

For more info about the mouse api consult http://stanislavs.org/helppc/int_33.html


text:
Q: How do you add a colormap to a matplotlib Animation? Suppose I am trying to visualize an objects position using its X and Y axis positions, and using some other variable, 'Z'  as the color map. This simplified example below illustrates how I am currently doing this.
import numpy as np
from matplotlib import pyplot as plt

dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)

plt.scatter(dataX, dataY, c=dataZ, cmap='winter', edgecolors='none')
plt.colorbar()
plt.show()

and the result:

I want to add a live animation to this instead of just showing a static image, but I am struggling to add the colormap to it. The code below shows how I am doing it without a colormap.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import Tkinter
import tkMessageBox

def restart():
    root = Tkinter.Tk()
    root.withdraw()
    result = tkMessageBox.askyesno("Restart", "Would you like to restart the animation?")
    if result:
        ani.frame_seq = ani.new_frame_seq()
        ani.event_source.start()
    else:
        plt.close()

dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)

def function(num, dataX,dataY, line):
    line.set_data(dataX[..., :num],dataY[..., :num])
    if num == dataX.size :
        restart()
    return line,

fig = plt.figure()

l, = plt.plot([], [], 'ro', markeredgewidth=0.0)
limitsX = [min(dataX)-100,max(dataX)+100]
limitsY = [min(dataY)-100, max(dataY)+100]
plt.xlim(limitsX[0],limitsX[1] )
plt.ylim(limitsY[0],limitsY[1] )
plt.xlabel('x')
plt.ylabel('y')
plt.title('test')

ani = animation.FuncAnimation(fig, function, (dataX.size+1), fargs=(dataX,dataY,l),
                              interval=10, blit = True, repeat = False)

plt.show()

Re-asking the question: How do I add a colormap to my animation?

A: This answer is loosely based on my answer to a similar problem, although I felt that the specific case of handling a PathCollection (as returned by scatter()) warrants a new answer.
Here is the way I would approach the problem. The trick is to generate a separate, static colorbar on a second axe in the figure. Then, when updating the PathCollection properties, use that colorbar and normalization to update the color of the points.
dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)

def animate(num):
    data = np.hstack((dataX[:num,np.newaxis], dataY[:num, np.newaxis]))
    art.set_offsets(data)
    art.set_color(cmap(norm(dataZ[:num]))) # update colors using the colorbar and its normalization defined below
    return art,

fig,[ax,cax] = plt.subplots(1,2, gridspec_kw={"width_ratios":[50,1]})
# Set the colormap and norm to correspond to the data for which
# the colorbar will be used.
cmap = matplotlib.cm.winter
norm = matplotlib.colors.Normalize(vmin=-50, vmax=50)

cb1 = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap,
                                norm=norm,
                                orientation='vertical')

ax.set_xlim(-60,60)
ax.set_ylim(-60,60)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('test')
art = ax.scatter([],[],c=[])

ani = animation.FuncAnimation(fig, animate,interval=2, blit=True, repeat=True)

plt.show()


text:
Q: HTML5 canvas alternatives for d3.js, graph visualization library Is there any Canvas library that is like d3.js (is svg library). I have a website here and I coded a graph with svg elements however it is not efficient on smart phone's browsers and works so slow. I now, want to change it with a 2d canvas type of it and see whether it is better or not. Can you suggest a canvas library that is useful for this purpose?
Thanks...

A: I know I am late to the party, but times have changed, and I believe this question deserves an updated answer. SVG performance has improved a lot over the years and especially for the non-trivial graph-like visualizations it often gives superior performance; but it really depends on the exact use-case: If the visualization is simple and consists of thousands of elements, especially on mobile, Canvas may be the faster option. If the visualization is almost trivial, WebGL gives the best performance and beats Canvas hands-down - especially on mobile!
However WebGL especially and also Canvas are a bit harder to use than the declarative approach that SVG uses. Things like CSS animations and transitions are easy to do with SVG and give good performance due to being hardware accelerated and totally independent of JavaScript performance. Canvas and WebGL always require JavaScript.
If you take a look at the commercial graph drawing library yFiles for HTML you will see that it offers all three technologies at the same time. This is because all three can be the best choice, depending on the exact use-case.
There is a blog entry that compares the performance of SVG, Canvas, and WebGL especially in the context of graph visualization. It compares various graph sizes and categories of devices. The "conclusion" is that there is not a clear winner. Often times the combination of all three technologies gives the best results. For smaller graphs, though, SVG most of the time gives very good results and is a pleasure to work with. That's also the reason why d3.js has its focus on SVG, rather than Canvas and WebGL, I would say.
There is an interactive demo linked from that blog entry that let's you play with the various technologies and see their strengths and weaknesses. Of course the demo mainly compares the three technologies used in that specific library so your results may vary, but they spent a lot of time optimizing all three technologies in that library, so I think the results are not too biased.
Disclaimer: I work for the company that creates the above mentioned library, but I do not represent my employer here on SO. I think what I said should be valid not just for that library.

A: For the Samsung Olympic Genome Project facebook app, we used http://thejit.org to make the force directed graph style animation for the app. It's heavily modified by me and others on my team of course, and only plays a very small part in the app, but it's quite a powerful framework.

A: Chart.js is a javascript library that just came out that creates charts using HTML5 for rendering. Its not as feature inclusive as D3, but it is working to become exactly that in the future. http://www.chartjs.org/

A: Take a look at Cytoscape.JS which uses a HTML5 canvas for rendering. At the time of writing this it's in its infancy but the project seems promising. According to its wiki the library supports both desktop and mobile browsers:

Cytoscape.js is easily integrated into your webapp, especially since
  Cytoscape.js supports both desktop browsers, like Chrome, and mobile
  browsers, like on the iPad.

A: D3 is not necessarily an svg only library - svg is used in many cases, but the library can do any kind of representations that you would like to make.  See this example of parallel coordinates using canvas in D3, by Kai Chang: http://bl.ocks.org/2409451
Also see here for some discussion on performance issues, etc, that might be helpful: https://groups.google.com/d/topic/d3-js/mtlTsGCULVQ/discussion


text:
Q: How can I get the app version of comment at the Google Play? I can only get the comment date, but it seems there is no url/api to get the corresponding  version of specific comment.
I've already tried this api:
https://code.google.com/p/android-market-api/
It does not contains the version number:
"comments": [
    {
      "rating": 5,
      "creationTime": 1269710736815,
      "authorName": "Nate Kidwell",
      "text": "Tremendous application. More examples would be great (as would integrated rubydocs), but awesome all the same.",
      "authorId": "04441815096871118032"
    },
...

Any other solution? I just want the version number

A: As reported in that library website (This is not an official api. I'm not afiliated to google in any way) is not an official API and Google does not provide any official API for the market.
So if that library doesn't provide any API to get the information you need, there is no other quick and simple way to do that.


text:
Q: Paypal payment is successufly completed in prestashop however the result message says error My prestashop version is 1.5.4.1 and my paypal version is 3.5.8. When I test the payment paypall accepts the payment. ORder is created how ever in the result window there is an error message (in red color) . The title of the result window is "Error Occured" In the details it says
Paypal Response:Checkout Status:->Payment Action Completed ....and all the other details like timestamp, email of the customer order status etc. etc..

Why do I get this error message in big RED font in prestashop even the payment is done successfully. I checked my payment account and I saw that payment is really done there is no problem..
Is there a way to show a success message in stead of those error messages...
Thank you
Ferda

A: This is something about paypal expiration date. I read it somewhere. Ican not check if it is really true but somehow even I didn't change anything in paypal accoutn but  I don't get this error now...


text:
Q: Mathematica code for Gram Schmidt Orthogonalization for a general Inner Product (in particular, weighted Bergman spaces) I am trying to write a Mathematica code to find an orthonormal basis of the weighted Bergman space defined by:
$$A^2(\varOmega) = \Big\{f \in \operatorname{Hol}(\varOmega) \; \Big| \; \|f\|= \textstyle\sqrt{\int_{\varOmega}|f(z)|^2 \, (1-|z|^2) \, \mathrm{d}A(z)} < \infty\Big\}$$
with the normalized Lebesgue measure on region $\Omega$. The inner product is like the usual $L^2$ inner product, $\langle f,g\rangle = \int_{\varOmega}\overline{f(z)} \, g(z) \, (1-|z|^2) \, \mathrm{d}A(z) \} $
I'm looking at $\Omega$ of the form:
Ω = RegionDifference[Disk[{0, 0}, 1], Disk[{1, 0}, b]]

which looks like this:

Can someone help me out with the code? I'm quite new to Mathematica and don't know much about it. I'm trying to see what orthogonalization of the set $\{1,z,z^2,\dots\}$ looks like.

A: If floating point approximations suffice, then this leads quite quickly to results:
b = 1/10;
Ω = DiscretizeRegion[RegionDifference[Disk[{0, 0}, 1], Disk[{1, 0}, b]],
                     MaxCellMeasure -> (1 -> 0.01)];
innerprod[f_, g_] :=
Integrate[f Conjugate[g] (1 - (x + I y) Conjugate[(x + I y)]), {x, y} ∈ Ω];
basis = (x + I y)^Range[0, 5];
orthobasis = Orthogonalize[basis, innerprod];

If you want exact computations, then you can try to leave away DiscretizeRegion. But be prepared to wait very long time.

A: In case you need/want symbolic results, you have to do a bit more work to get results in a reasonable amount of time.
I'll use the same parameters used in Henrik's answer:
With[{b = 1/10}, Ω = RegionDifference[Disk[{0, 0}, 1], Disk[{1, 0}, b]]]

The trick is to recognize that computing the inner product $\langle f,g\rangle$ when both functions $f,g$ are polynomials entails a lot of repetitive work, due to the evaluation of expressions of the form $\langle z^m,z^n\rangle$. It thus makes sense to evaluate and memoize these subexpressions so that they get used in the inner product computation:
iProdPow[m_, n_] := iProdPow[m, n] =
   Simplify[Integrate[ComplexExpand[(x + I y)^m Conjugate[(x + I y)^n]
                                    (1 - (x + I y) Conjugate[x + I y]),
                                    TargetFunctions -> {Re, Im}],
                      {x, y} ∈ Ω]]

iProd[f_, g_, z_] /; PolynomialQ[f, z] && PolynomialQ[g, z] :=
   With[{fe = CoefficientList[f, z], ge = CoefficientList[g, z]},
        Simplify[Sum[fe[[j + 1]] ge[[k + 1]] iProdPow[j, k],
                     {j, 0, Length[fe] - 1}, {k, 0, Length[ge] - 1}]]]

I've found Orthogonalize[] to be a bit slow for this application, so I decided to steal borrow and modify acl's Gram-Schmidt code instead:
With[{n = 3},
     res = Block[{u, v},
                 v = z^Range[0, n]; u = ConstantArray[0, n + 1]; u[[1]] = v[[1]];
                 Do[u[[i]] =
                    Collect[v[[i]] -
                             Sum[u[[j]] iProd[v[[i]], u[[j]], z]/
                                 iProd[u[[j]], u[[j]], z], {j, 1, i - 1}],
                            z, Simplify],
                    {i, 2, n + 1}];
                 u/Sqrt[iProd[#, #, z] & /@ u]]];

The resulting expressions are quite complicated:
LeafCount /@ res
   {33, 158, 1644, 28985}

but evaluating N[] and comparing them with Henrik's results (and squinting a little bit) shows that the results from this method are consistent with his.


text:
Q: R a plot ploblem with lines? I have to do some plots using R. I run R-studio and I have used multiple R distros in order to check if the same problem is preented.
The problem is that the plot() with type='l' connects all points together. Can somebody help?
p <- sample(seq(0,2,0.01), 100, replace = T)
plot(p, p^2, type='l', col=2)

A: You'll probably have to sort the points first.
p <- sort(sample(seq(0, 2, 0.01), 100, replace=TRUE))
plot(p, p^2, type='l', col=2)


text:
Q: Is defining structure inside a function a good way to conceal the structure from other functions? You can define a structure inside a function like this:
fn user_status() -> bool {
    struct UserStatus {
        logined: bool,
        name: Option<String>,
    }
    // ...
    true
}

Is this a good way to conceal structure from other functions and is structure defined every time something calls the function or it is created just once?

A: I think this is a perfectly reasonable way to define a type only used within a function.
Types are defined at compile time; there's no "defining" going on at runtime when functions are called.


text:
Q: What's the acceptable swift version for app submission? I have an existing app in the app store written using swift 3. For subsequent update will Apple reject my app because it's still in swift 3?
According to this link,

If your app is written in Swift, you can continue to submit apps in
  Swift 4 to the App Store and migrate individual modules to Swift 5
  when you're ready.

So means if swift version is less than 4 my app updates will get rejected? When will they stop accepting swift 4 apps?

A: Here is an excerpt from Apple:

Starting March 27, 2019, all iOS apps submitted to the App Store will
need to be built with the iOS 12.1 SDK or later, and support the
all-screen design of iPhone XS Max or the 12.9-inch iPad Pro (3rd
Generation). All watchOS apps will need to support watchOS 5 and Apple
Watch Series 4

This means that any submissions to App Store after March 27, 2019 requires iOS 12.1 SDK or later which I believe is available in XCode 10.2 onwards. XCode 10.2 doesn't have support for Swift 3. In essence, Apple stopped accepting applications written in Swift 3 after March 27, 2019.
The same principle would apply to Swift 4. Whenever they decide to up the minimum SDK requirement, it would force a minimum XCode version which, in turn, would force minimum Swift version

A: Based on this: https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes

Xcode 10 is the last release that will support Swift 3. Migrate your
  projects from Swift 3 code to Swift 4.2 syntax by opening the project
  and choosing Edit > Convert > To Current Swift Syntax

It will depend on Xcode and minimum iOS SDK version support. Probably Xcode 11 will not allow you to upload an ipa built from Swift 3 source at all.

A: From Apple:

Starting March 27, 2019, all iOS apps submitted to the App Store will
  need to be built with the iOS 12.1 SDK or later, and support the
  all-screen design of iPhone XS Max or the 12.9-inch iPad Pro (3rd
  Generation). All watchOS apps will need to support watchOS 5 and Apple
  Watch Series 4

This means that any submissions to App Store after March 27, 2019 requires iOS 12.1 SDK or later. According to Xcode wiki:, the included iOS SDK in Xcode 10.1 is iOS12.1. Furthermore, this link stated that for Xcode 10.1 the supported swift versions are 3.4.1, 4.1.5 and 4.2.1
Hence, it's alright submit apps using version 3.4.1, 4.1.5 or 4.2.1.
Couldn't find a consolidated list for swift version, Xcode SDK and iOS SDK. Will try to build one and post it here. And the frequency of the force upgrade of iOS SDK being implemented.


text:
Q: In Backbone, can't get object's id or cid after using "create" function to add it to Parse I'm using Backbone and Parse to build a survey website. I imitated the Todo list example to add a question to the page. As in the todo list example, I have "createOnEnter" and "addOne". Getting the id is important to me because I need to set the id of the question the same as its id in Parse.
    addOne: function(question) {
    alert(question.get("content"));
    alert(question.id);
    var view = new QuestionView({model: question});
    this.$("#questions").append(view.render().el);
},

    createOnEnter: function(e) {
    if (e.keyCode != 13) {
        return;
    }

    this.survey.create({
        content: $("#new-question").val(),
        type: $("#choose-type").val(),
        order: this.survey.nextOrder(),
        user: Parse.User.current(),
        ACL: new Parse.ACL(Parse.User.current())
    }, {wait: true});
        $("#new-question").val('');
    }

So alert(question.get("content")) will indeed gave me the expected content but alert(question.id) shows undefined. However I believe each entry saved to Parse will get a unique id so I couldn't understand why question.id is undefined. Even worse, alert(question.get("cid")) is also undefined.....This is really confusing to me.
Thanks a lot!!!

A: ids are given by the server (when you fetch and the server return an id fields). It could also get added if when you create your model you manually add an id field - but the point is that this isn't done automatically. id is the unique identifier of a resource on the server.
As you're creating question on the frontend, you'll need to use the unique id Backbone create who's called cid . http://backbonejs.org/#Model-cid


text:
Q: SNS - Introduce Consumption Delay I have a lambda that transfer data from source s3 bucket to destination s3 bucket.
There is a process that pushes message into source s3 bucket. This process sends a notification via SNS after data is pushed to source s3 bucket. A third party verification lambda is triggered once data is pushed into source bucket which validates the data pushed into source bucket. This process can take anywhere between 5-30 mins to complete.
My lambda should transfer data from source to destination only after the validation is completed by third party app. They have exposed an api which I can use to determine if validation is complete. Once my lambda receives the message from the topic , it will call the external api if validation is complete. If the validation is not complete , I want to retry after 5 minutes.
Can I push the message back into SNS topic and introduce a delay of 5 mins after which it can trigger my lambda again? If this is not possible are there any aws patterns available which can help achieve this without additional coding (and still use lambda for data transfer)?


text:
Q: check box array selector for jQuery validation My HTMl:
<input type="checkbox" name="subjects[0]" class="checkbox_array" value="1"  />
<input type="checkbox" name="subjects[1]" class="checkbox_array"  value="1"  />
<input type="checkbox" name="subjects[2]" class="checkbox_array" value="1"  />
<input type="checkbox" name="subjects[3]" class="checkbox_array" value="1"  />
<input type="button" id="ss" />

jquery:
$("#ss").click(function(){
    if($('input[name=subjects\\[\\]]:checked').length<=0)
    {
        alert("No radio checked")
    }
});

its not working for me... using class if($('.checkbox_array:checked').length<=0)  it work that easy but how can i do with input name selector

A: ($('input[name*="subjects"]:checked').length<=0)

Will work...
Doc: http://api.jquery.com/attribute-contains-selector/

A: You can do this using the Attribute Starts With Selector:
$("#ss").click(function () {
    if ($('input[name^=subjects]:checked').length <= 0) {
        alert("No radio checked")
    }
});

Demo: Fiddle


text:
Q: SSRS group total with semi dirty data Data is Bill of Lading where I have to report items as well as lots and counts.  Actual data is sent by other system that mixes total weight of an item on each line of lot details.  I receive a textual generation of each Lot # and count from that lot per line on each line.  Did I say dirty data?
I have grouped in a sub tablix to show only one item at a time just fine.
Now I need to get a total weight for the truck load.  How do I Sum ONLY the first value for that item and skip all the second, third,... lots that comprise this item for my Tablix summary?  Data below should show 8343 in the total weight.
Usually have 2 lots per item, may only be 1 lot 10% and may be more than 2 lots 15% of the time.
Will usually have at most 4 items per truck with most 75% of all trucks holding only 1 or 2 items.
item     weight  LotQuantity
ABC123    4655   4502052014 - 1200, 4512052014 - 2400
ABC123    4655   4502052014 - 1200, 4512052014 - 2400
ABC122    3688   4502052014 - 600, 4512052014 - 1200
ABC122    3688   4502052014 - 800, 4512052014 - 1400
TIA

A: Created functions in report code:
Dim wgt1 AS Double
Function addWgt(ByVal value AS Double)
    wgt1 += value
End Function
Function getWT()
    return wgt1
End Function
Dim Cnt AS Double
Function addCnt(ByVal value AS Double )
    Cnt += value
End Function
Function getCNT()
    return CNT
End Function
In an empty column I added the current weight as well as the current count via the addWGT()
For the report footer I just put in  =Code.getWT()


text:
Q: Azure Data Factory Python SDK Create Trigger I'm working with the Azure Data Factory Python SDK to create a Trigger as documented here. Unfortunately, it's not working and I'm getting a very cryptic error message.
I'm using the following code (as per the example):
tr_name = 'mytrigger'
scheduler_recurrence = ScheduleTriggerRecurrence(frequency='Minute', interval='15',start_time='2017-12-12T04:00:00Z', end_time='2017-12-12T05:00:00Z', time_zone='UTC')
pipeline_parameters = {'inputPath':'adftutorial/input', 'outputPath':'adftutorial/output'}
pipelines_to_run = []
pipeline_reference = PipelineReference(reference_name='copyPipeline')
pipelines_to_run.append(TriggerPipelineReference(pipeline_reference=pipeline_reference, parameters=pipeline_parameters))
tr_properties = ScheduleTrigger(description='My scheduler trigger', pipelines = pipelines_to_run, recurrence=scheduler_recurrence)

adf_client.triggers.create_or_update(rg_name, df_name, tr_name, tr_properties)

The error I'm getting is:
azure.core.exceptions.HttpResponseError: (InvalidPropertyValue) Invalid value for property 'Properties'
Code: InvalidPropertyValue
Message: Invalid value for property 'Properties'
Target: mytrigger

which doesn't tell me much at all :-(. Has anyone seen this before? I'm struggling to figure this out. I've looked for an attribute Properties, but there doesn't seem to be one. Is there a good way to debug what's going on here?

A: To resolve this azure.core.exceptions.HttpResponseError: (InvalidPropertyValue) Invalid value for property 'Properties' error:
Instead of:
tr_properties = ScheduleTrigger(description='My scheduler trigger', pipelines = pipelines_to_run, recurrence=scheduler_recurrence)

You can try this:
tr_properties = TriggerResource(properties=ScheduleTrigger(description='My scheduler trigger',pipelines=pipelines_to_run,recurrence=scheduler_recurrence))

You can refer to Bad body serialization creating a Schedule Trigger in Data Factory and Azure data factory trigger creation using python SDK


text:
Q: What problem does Julia solve for data science? I am not able to find any definitive answer to what problem Julia solves compared to the two languages, I was told are most commonly used in working with data (data science), R and Python.
I am not asking for any opinions. Please support replies with factual information (sad I need to add this but it seems some people think this topic is opinion based).
Could anyone explain this?

A: The Julia Programming Language solves the same problems as R and Python. However, it can solve them extremely faster than those mentioned above, as it runs over C code and uses a JIT compiler. See the Julia Benchmark. This and other advantages that can be found at the language site, it's Twitter profiles: Julia Computing and Julia Language.


text:
Q: Jpa Database relationships for a Voting system There are many questions about voting systems so I will cut right to the chase.
My question is about relationships ,
import play.db.jpa.GenericModel;

public class VotesModel extends GenericModel {
    @ManyToOne
    public StatusModel status;
    @ManyToOne
    public UserModel user;
    public Date time;
}

The usual voting rules apply,

*

*A status can have many votes

*A user can vote on many status.

*But a user can vote only once on a status .

I have easily applied the first 2 rules as @ManyToOne , How do I apply the 3rd and most important rule?
Environment:
Playframework 1.2.5 , MySQL

A: Make a composite key out of status and user


text:
Q: Explaining Variance I am currently faced with the problem of explaining variance in an evaluation where users rate Cloud services on a quality scale.
My data looks as follows:
Dependent variable:

*

*Quality score (ratio scale)

Independent variable:

*

*loss rate (ratio scale, can easily be mapped to interval scale and represented in R as a factor with levels none, low, medium, and high).

*Delay (as loss rate)

*Jitter (als loss rate)

My problem is as follows: the quality of using a cloud service correlates with loss rates: the more loss, the less pleasant it is to use the service over the Internet. Plotting quality over loss in a scatter plot, however, shows variance that is caused by either delay or jitter: so for the same loss rate, I get variability in the obtained quality scores that is caused by either delay or jitter. It is also possible that it's purely based on the data loss as main effect.
I would like to find an approach, that gives me, for each loss rate (low, medium, high) an explanation for the variance in the obtained quality scores: was it caused purely by the loss? Or by loss and jitter, or by loss and delay?
What is the best way to approach this? I was thinking about ANOVA, but feel very uncomfortable in judging whether it is the right tool for me. Can ANOVA really help me to figure out why I see variability in quality scores for the same loss rate? Do I need a between groups or within groups test?
Is there any other way to approach this?
Many thanks in advance!

A: Don't transform your ratio scales into intervals.  Just use a linear regression with lm() (testing for all the usual assumptions, of course).  Unless I misunderstand your problem, this is exactly what regression is good for.


text:
Q: gulp browserify and bromote My project is using gulp-starter which has quite a bit of wiring already implemented with browserify and I'm now trying to add bromote to this project.
I found this reference to implement bromote with browserify browserify & factor-bundle dependency ids and tried to get it working.
Here is my resulting gist:
https://gist.github.com/newtonianb/18f8bcd23ee9762324c6
It compiles fine but I'm not able to access my export. From my understanding, whatever you export in bromote you can then use it like so within your javascript source files
var bromote = require('bromote');
bromote.your_export_name(function(x) {});

But in my javascript source files when I try require('bromote') I get
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Cannot find module node_moduleromotelibexport-remote.js' from 'node_modules\bromote\loaders'
  at node_modules\browserify\node_modules\resolve\lib\async.js:50:17
  at process (node_modules\browserify\node_modules\resolve\lib\async.js:119:43)
  at node_modules\browserify\node_modules\resolve\lib\async.js:128:21
  at load (node_modules\browserify\node_modules\resolve\lib\async.js:60:43)
  at node_modules\browserify\node_modules\resolve\lib\async.js:66:22
  at node_modules\browserify\node_modules\resolve\lib\async.js:21:47
  at Object.oncomplete (fs.js:107:15)

A: If all you need is google maps, drop bromote and just use browserify with the google-maps npm module.  For the most part, your best bet is to see if there's something that will already work with browserify.


text:
Q: RemoteCache, RemoteCacheManager, and Lifecycle I am looking at the documentation for the RemoteCache, RemoteCacheManager, Lifecycle Start, and Lifecycle Stop.
I am having a hard time understanding what exactly do the start() and stop() methods do.
The reason that I ask is because I am attempting to remotely stop and start a particular cache. I want to do this so that I can observe the behavior my applications exert during a stopped/started state. i.e I write a test that remotely stops a cache. When this happens, I make a simulated call to see how my software behaves now that the cache is down.
I have tried calling both stop() and start() in the RemoteCache and the RemoteCacheManager on a particular instance, but no exceptions seem to occur by the infinispan dependency. Thus, it is leading me to believe that I am misinterpreting the purpose of these two methods.
My software is calling the remote cache with code that looks as follows:
final RemoteCache<String, String> cache = remoteCacheManager.getCache(CACHE_NAME);
if (cache != null) {
    if (cache.containsKey(key)) {
        // Do something
    } else {
        // Do something else
    }
} else {
    throw new Exception("cache null");
}

My test is calling the remote cache with some code like this:
final Properties props = new Properties();
props.put(ConfigurationProperties.SERVER_LIST, serverList);
props.put(ConfigurationProperties.SO_TIMEOUT, 5000);
props.put(ConfigurationProperties.CONNECT_TIMEOUT, 5000);
rmtCacheMgr = new RemoteCacheManager(props, true);

In a test, I might perform something like this to stop the remote cache:
rmtCacheMgr.close();

Surely, if my software calls getCache, and I set the cache to stopped during my test, it should throw some exception or complain to some level, no?

A: Configure a New RemoteCacheManager:
import org.infinispan.client.hotrod.configuration.Configuration;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;

Configuration conf = new
ConfigurationBuilder().addServer().host("localhost").port(11222).build();
RemoteCacheManager manager = new RemoteCacheManager(conf);
RemoteCache defaultCache = manager.getCache();

https://access.redhat.com/documentation/en-US/Red_Hat_JBoss_Data_Grid/6.4/html-single/Administration_and_Configuration_Guide/index.html#part-Set_Up_a_Cache_Manager
Hope this will help. Don't forget to mark the answer as accepted and upvote it IF it fits for your question!


text:
Q: Registering a Shopify Webhook via the ShopifyAPI gem This call correctly returns an empty array:
hooks = ShopifyAPI::Session.temp(s.myshopify_domain, s.shopify_access_token) do
  ShopifyAPI::Webhook.find :all
end

While this call always returns a 403:
hook = ShopifyAPI::Session.temp(s.myshopify_domain, s.shopify_access_token) do
  ShopifyAPI::Webhook.create(
    format:     'json',
    topic:      'orders/fulfilled',
    address:    "http://www.something.fr/api/webhooks?store_id=#{s.id }&store_check=#{ s.checksum }"
  )
end

I've tried pretty much all solutions offered over various websites, each time with a failure.
What am I missing here?

A: The whole code block given in original post is correct.
It was in fact a rights problem, the customer who provided us with the API tokens didn't enable webhook creation rights on the Shopify configuration.
It might seem like nothing, but it is critical that you check that with whoever gave you credentials!

A: Try this
hook = ShopifyAPI::Session.temp(s.myshopify_domain, s.shopify_access_token) do
  ShopifyAPI::Webhook.new(
    format:     'json',
    topic:      'orders/fulfilled',
    address:    "http://www.something.fr/api/webhooks?store_id=#{s.id }&store_check=#{ s.checksum }"
  )
end

Possible duplicate: Error Creating Shopify Webhook through the API


text:
Q: How can I prove by induction that $9^k - 5^k$ is divisible by 4? Recently had this on a discrete math test, which sadly I think I failed.  But the question asked:

Prove that $9^k - 5^k$ is divisible by $4$.

Using the only approach I learned in the class, I substituted $n = k$, and tried to prove for $k+1$ like this:
$$9^{k+1} - 5^{k+1},$$
which just factors to $9 \cdot 9^k - 5 \cdot 5^k$.
But I cannot factor out $9^k - 5^k$, so I'm totally stuck.

A: $9^{k+1}-5^{k+1}=(8+1)9^k-(4+1)5^k=9^k-5^k+4(2\cdot 9^k-5^k)$  The secret to induction proofs is usually to find a way to relate the $k+1$ case to the $k$ case.
Alternately, just note $9\equiv 1 \pmod 4, 5 \equiv 1 \pmod 4$, so $9^k-5^k \equiv 1^k-1^k \pmod 4$

A:
${\color{White}{\text{Proof without words.}}}$

A: Note that induction is not actually needed: you can instead use the identity
$$x^n-y^n=(x-y)\sum_{k=0}^{n-1}x^ky^{n-1-k}\;.$$
In this case it becomes
$$9^n-5^n=4\sum_{k=0}^{n-1}x^ky^{n-1-k}\;,$$
and since the summation clearly yields an integer, we have $4\mid 9^n-5^n$. The identity is a standard one, but it's also not hard to prove:
$$\begin{align*}
(x-y)\sum_{k=0}^{n-1}x^ky^{n-1-k}&=x\sum_{k=0}^{n-1}x^ky^{n-1-k}-y\sum_{k=0}^{n-1}x^ky^{n-1-k}\\\\
&=\sum_{k=0}^{n-1}x^{k+1}y^{n-1-k}-\sum_{k=0}^{n-1}x^ky^{n-k}\\\\
&=\sum_{k=1}^nx^ky^{n-k}-\sum_{k=0}^{n-1}x^ky^{n-k}\\\\
&=x^ny^0+\sum_{k=1}^{n-1}x^ky^{n-k}-\sum_{k=1}^{n-1}x^ky^{n-k}-x^0y^n\\\\
&=x^n-y^n\;.
\end{align*}$$

A: $$\begin{align} 9\cdot 9^k - 5\cdot 5^k & = (4 + 5)\cdot 9^k - 5\cdot 5^k \\ \\ & = 4\cdot 9^k + 5 \cdot 9^k - 5\cdot 5^k \\ \\ & = 4\cdot 9^k + 5(9^k - 5^k)\\ \\ & \quad \text{ use inductive hypothesis}\quad\cdots\end{align}$$

A: It sounds like you understand the basic idea, but you're having trouble with the "trick" in the inductive step.  This is common for proofs by mathematical induction, and you'll get better at it with more experience.
As you said, you're assuming that
$
9^k-5^k
$
is divisible by four, and you want to prove that
$
9^{k+1}-5^{k+1}
$
is divisible by four.  You noticed that you can write the last expression as
$9\cdot 9^k-5\cdot 5^k$, and you said you're having trouble applying your assumption to it.  What happens if you add $9\cdot 5^k-9\cdot 5^k$ to your expression?  This is just zero, so you're not changing anything, but you can write
$$
9^{k+1}-5^{k+1}
=9\cdot 9^k-5\cdot 5^k+9\cdot 5^k-9\cdot 5^k
=9\cdot (9^k-5^k)+(9-5)\cdot 5^k.
$$
By the assumption, the first term, $9\cdot (9^k-5^k)$, is divisible by four, and by observation, the second term, $(9-5)\cdot 5^k$, is divisible by four, so the sum of the two terms and therefore $9^{k+1}-5^{k+1}$ are divisible by four.  This is what you wanted to show.
You can always add zero (or multiply by one), and by writing zero (or one) in a particular way, you can sometimes make an argument easier to prove.  Also, since your proof is by mathematical induction, you need to show that $9^n-5^n$ is divisible by four for, say, $n=0$ or $n=1$.  You may have already done so and not asked about it in your question, but it's worth mentioning.


text:
Q: how to set default web page while opening new tab in web browser? I am using Firefox as my default web browser. In that when I opening new tab (Ctrl+T), an empty page (blank page) is being opened. But now I want to load my default page when I open the new tab. Please guide me. Thanks in advance..

A: I don't think you can do that directly in firefox.
There is however this: https://addons.mozilla.org/en-US/firefox/addon/777/


text:
Q: can't create a graph with matplotlib from a csv file / data type issue I'm hoping to get some help here. I'm trying to create some simple bar/line graphs from a csv file, however, it gives me an empty graph until I open this csv file manually in excel and change the data type to numeric. I've tried changing the data type with pd.to_numeric but it still gives an empty graph.
The csv that I'm trying to visualise is web data that I scraped using Beautiful Soup, I used .text method do get rid of all of the HTML tags so maybe it's causing the issue?
Would really appreciate some help. thanks!
Data file: https://dropmefiles.com/AYTUT
import numpy
import matplotlib
from matplotlib import pyplot as plt
import pandas as pd
import csv

my_data = pd.read_csv('my_data.csv')
my_data_n = my_data.apply(pd.to_numeric)
plt.bar(x=my_data_n['Company'], height=my_data_n['Market_Cap'])
plt.show()

A: Your csv file is corrupt. There are commas at the end of each line. Remove them and your code should work. pd.to_numeric is not required for this sample dataset.
Test code:
from matplotlib import pyplot as plt
import pandas as pd

my_data = pd.read_csv('/mnt/ramdisk/my_data.csv')

fig = plt.bar(x=my_data['Company'], height=my_data['Market_Cap'])
plt.tick_params(axis='x', rotation=90)
plt.title("Title")
plt.tight_layout()
plt.show()


text:
Q: How do I call a function in a polymorphic object list? In C#, if I have an object that is inherited from another object, and I have a list of the inherited object, how can I call a function in the base class?
Here is an example:
class testObject
{
    public void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public void testFunction()
    {

    }
}

Here is the list:
List<testObject> testObjects

If I add some testObject2 objects to the list, how can I call the testFunction function for each testObject2 object? If I try and call testFunction for each object, the testFunction in the testObject is called.
EDIT
When adding the override code to the testFunction in testObject2, I am getting this error:

cannot override inherited member because it is not marked virtual,
  abstract, or override

A: class testObject
{
    public virtual void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public override void testFunction()
    {

    }
}

You need to add virtual to the method in testObject class and override it in the testObject2. If you want to add a little logic to already existing logic you can do it like this:
    public override void testFunction()
    {
         //it is calling the method in base
         base.testFunction();

        //here you can add more logic if you want.
    }

If you want totally separate method in which you do something else you just
    public override void testFunction()
    {
        //write another logic.
    }

A: To enable polymorphic funtions you must declare the function as virtual, or abstract and then override them in child classes
class testObject
{
    public virtual void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public override void testFunction()
    {

    }
}

A: Class Definition:
class  testObject
    {
        public string s;
        public virtual void testFunction()
        {
            string b = s;
        }
    }

    class testObject2 : testObject
    {
        public string m;
        public override void testFunction()
        {
            string x = m;

        }
    }

Function call:
  List<testObject> testObjects = new List<testObject>();
  testObjects.Add(new testObject2() { m = "a" });
  testObjects[0].testFunction();