text:
Q: Within subjects main effect in an ANOVA changes after a between subjects variable is included in the model Yesterday my colleagues (all researchers) and I were bewildered by something. My colleague was asked to revise her article by the reviewers of a journal. She had done 3 repeated measures ANOVAs  to answer each of the research questions, and the reviewers asked her to check for differences in the between subjects measure (in this case gender). She therefore set out to repeat her ANOVA (in SPSS) as a mixed model, with the repeated measures staying the same, but adding one between subjects measure (gender). She found no significant differences in gender and one significant interaction of a within subjects measure and gender (not problematic for this paper).
Here is the baffling part though: Her main within-subjects effects suddenly had changed - different F and p values were shown.
This defies my knowledge and understanding of what a mixed model ANOVA calculates. As I understand it:
F(within subjects main effect) = MS(within) / MS error(within)
F(within subjects * between subjects interaction) = MS(within * between) / MS error(within)
F(between subjects main effect) = MS(between) / MS error(between)
The F value of the within subjects main effect should not change, whether you are including a between subjects variable or not. This calculation is based on the same numbers either way and should therefore yield the same results either way. What are we missing here? What are we not understanding?


text:
Q: Slow Mongo queries from Rails app taking > 1000 ms ... ideas for optimization? We built a Rails app on Mongo 2.2 and Rails 3.2.12. We're new to Mongo and would appreciate any tips on how we should optimize very slow queries, ones that take longer than 1000 ms.
We're using MongoMapper as the interface to Mongo.
We are indexing these table, but is there a way to confirm whether our queries are using these indices properly? How else can we pinpoint the cause of slowness?
Here is one day's worth of slow Mongo queries: https://gist.github.com/panabee/2876e833002f3151eeda
Here is explain on three of those queries: https://gist.github.com/panabee/358bd87ba7b954018dab

A: Your issue is schema design, indexing design and probably also insufficient resources to handle the current load (possibly - it's impossible to tell without fixing the queries first).
When designing your schema you must consider how you will be accessing the data for reads and writes.  The structure of your documents and your indexing strategy must reflect the needs of the reads and writes.  You currently have queries which must scan thousands of documents to select very few - this is a reflection of poor indexing strategy.  With effective indexing your queries should be able to use indexes to zero in on the number of documents they need, in addition if sorts must be done then those should also be supported by indexes.
This would not be appropriate venue for an answer since your problem isn't that you are missing a single index or using the wrong type of query.  You need to reconsider your schema design and your indexing strategy based on the needs of your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: psycopg2: dynamic table, columns and values I am trying t use psycopg2 to generate a dynamic INSERT INTO statement where table, columns and values are all dynamic.
I've read the documentation around the psycopg2.SQL class, which provides some hints, however I can't get the final result.
# inputs to the DB. Keys represent COLS. 2 records.

kvalues = [{'first':11,'second':22},{'first':33,'second':44}]

table   = 'my_table'
columns = list(kvalues[0].keys())
values  = [list(kvalue.values()) for kvalue in kvalues]

# Generate SQL string
conn = psycopg2.connect(#...details..)
cur  = conn.cursor()

query_string = sql.SQL("INSERT INTO {} ({}) VALUES %s").format(
        sql.Identifier(table),
        sql.SQL(', ').join(map(sql.Identifier, columns))).as_string(cur)

print(cur.mogrify(query_string, values))

#>> TypeError: not all arguments converted during string formatting

I've tried adding the values in the SQL statement, but this also produces more errors.
How can I generate a dynamic insert into statement which accepts the cols, vals from kvalues?
Thank you!

A: Issue is around Tuple/List formatting. Below is the code that works:
kvalues = [{'first':11,'second':22},{'first':33,'second':44}]

table   = 'my_table'
columns = list(kvalues[0].keys())
values  = [tuple(kvalue.values()) for kvalue in kvalues]

# Generate SQL string
conn = psycopg2.connect(#...details..)
cur  = conn.cursor()

query_string = sql.SQL("INSERT INTO {} ({}) VALUES {}").format(
        sql.Identifier(table),
        sql.SQL(', ').join(map(sql.Identifier, columns)),
        sql.SQL(', ').join(sql.Placeholder()*len(values)),
        ).as_string(cur)

print(cur.mogrify(query_string, values))


text:
Q: CreateProcess error=2 running javadoc from Ant Can anyone tell me why I am getting this error message
Buildfile: C:\Users\Tara\workspace\Testing\build.xml
doc:
   [delete] Deleting directory C:\Users\Tara\workspace\Testing\doc
    [mkdir] Created dir: C:\Users\Tara\workspace\Testing\doc
  [javadoc] Generating Javadoc
  [javadoc] Javadoc execution

BUILD FAILED
C:\Users\Tara\workspace\Testing\build.xml:24: Javadoc failed: java.io.IOException: Cannot run program "javadoc.exe": CreateProcess error=2, The system cannot find the file specified

Total time: 206 milliseconds

when I run this in Eclipse?
<project name="SimpleBuildScript" basedir="." default="doc">
<property file="build.properties"/>
<target name="compile" description="Compiles the Task">
    <delete dir="${class.dir}"/>
    <mkdir dir="${class.dir}"/>
        <javac srcdir="src" destdir="classes"/>
</target>

<target name="clean" description="Delete all generated files">
        <delete dir="${class.dir}"/>
        <delete dir="${jar.dir}"/>
</target>

<target name="doc" description="generate documentation">
    <delete dir="${doc.dir}"/>
    <mkdir dir="${doc.dir}"/>
        <javadoc sourcepath="${source.dir}" destdir="${doc.dir}"/>
</target>
</project>

A: I came across the same issue and solved it by adding an additional JREs definitions under:
Windows > Preferences > Java > Installed JREs

At the time it failed, I was using Jre7 in C:\Program Files\Java\jre7 then I have added and selected Jre in C:\Program Files\Java\jdk1.7.0_07\jre.

A: Change Ant Config :  [Edit Configuration] -> [JRE] -> Change jre to jdk
and I solve this problem

A: Providing you have a jdk installed and added to Eclipse:

*

*Windows->Preferences Java->Installed

*JREs->Add

You can then

*

*Right click on build.xml

*Select Run As->Ant Build... note the ellipsis!

*Switch to JRE tab

*Select the jdk from the list

Credit for a similar solution:
http://blog.darevay.com/2008/12/running-javadoc-ant-task-from-eclipse/

A: javadoc is not in the path. With newer ant you can provide attribute (executable) to specify exe location.  See documentation here

A: Add javadoc.exe to your build path.

*

*From the start menu, click on Control Panel >  System (use classic view) to view system properties.

*In the System Properties window, click on Advanced to the left.

*Click on Environment Variables.

*In the list of System Variables, select Path and then press the Edit button. a window that allows you to alter the value of the Path variable.

*At the end of the text for the Path variable, add a semicolon and the directory path to Java (no spaces): eg. C:\Program Files\Java\jdk1.6.0_39\bin

A: make sure the javadoc.exe is on your path; this error usually means the ant task cannot find the executable


text:
Q: android edittext automatically enters the input I have this EditText for password that only allows 4 characters. My Question is, how do i make it enter the password after inputting 4 characters? Without the use of button, just after the 4th character it will enter the password.

A: You can use a textChangeListener.
Field1.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() == 4)
      // length is 4 characters do what you want to do here.
      Toast.makeText(context, s, 100).show();
   }
  });


text:
Q: Do any OS X apps ease Search and Replace across multiple files? I'm looking for an OS X tool which allows me to search and replace a search string in multiple files. The requirements are the following:

*

*Search and Replace

*Search by regular expression

*Search across multiple files

*Search across nested directory structures

*Replace expression can use values from the search (Regular Expression)

*The tool has an easy to use user interface

*Preferably free

I know that some text editors like BBEdit have this functionality, but I would prefer a lightweight tool that doesn't require me to open the files for editing first.
If there aren't any tools to match these requirements, I would also consider a command line alternative. I know that perl and sed support something like this - a solution that I can define either as a Bash alias or function would be welcome in this case.

A: Sublime Text is what I use, it's great!

Sublime Text:

*

*is free to evaluate (no time limit imposed)

*can search and replace

*can search by regular expression

*can search across multiple files

*can search across nested directory structures

*can use values from the search in replace expression

*has an easy to use user interface

A: You don't have to open the files with BBEdit. You just point it to a folder. It's a very powerful tool, one that I've often used with large numbers of HTML files.

A: In addition to the other solutions using a text editor, I have found FAR - Find and Replace, a multi-platform find and replace tool. It's not the prettiest one, but it looks like it does what I'm looking for.
http://findandreplace.sourceforge.net/

A: I often use Ruby scripts like this:
Dir["**/*.txt"].each { |f|
  IO.write(f, IO.read(f).gsub(/search/, "replace"))
}

Or you can use gets(nil) with -i:
ruby -i -e 'print gets(nil).gsub(/search/, "replace")' *.txt

If you install Bash 4 and enable globstar, you can use ** in shells as well:
sed -i '' 's/search/replace/g' **/*.txt

A: I typically use TextMate:

TextMate (1) is/was a buy product, but TextMate 2 is currently under active openSource development on gitHub and free to use.

A: This is exactly sed was written and it matches all of your requirements, except the learning curve is a bit steep.
For a more gentle learning curve, try TextWrangler from BareBones. It uses the BBEdit text engine and, I believe, has the full search & replace functionality of its big brother

A: Take a look at my App Search and Replace. You can use it on multiple files or directories, safe your search/replace strings and you can use regular expressions.


text:
Q: Change routes for VPN I need to use for some things a cisco VPN connection, but I don't want to route all my trafic over the VPN but only that traffic, that is send to a specific network.
How does a script look like, that sends all traffic to 10.10.3.1 or exchange.server.de through the VPN tunnel and the rest of the traffic uses the default route that existed before the VPN was established?
Thanks for your help.

A: You'll need root access, but basically, you would reset the routes (route) and the IP chains (iptables):
gateway=192.168.1.1 # or whatever your default gateway is
# anything going to 10.10.3.0 will go through the vpn (cscotun0 interface)
route add -net 10.10.3.0 netmask 255.255.255.0 dev cscotun0
# everything else will go through the gateway
route del default
route add default gw $gateway
# flush iptables to clear the ciscovpn chain
iptables --flush
iptables --delete-chain
echo "nameserver $gateway" >> /etc/resolv.conf

This is just a rough setup (and assumes that your VPN network is class C).  The one that I use with my company's VPN is much more involved with nearly a dozen static routes added.
You aren't quite clear about what the VPN networks are, so I made some guesses.

A: You would have to set up split tunneling on the concentrator side of the connection This link will give you a good idea of what I'm talking about. If you do not have access to the VPN concentrator, then you will not be able to change what does and what doesnt go through the tunnel

A: I just set up what they call "client side VPN split tunnel" to achieve access to two hosts by VPN while maintaining traffic outside the VPN (in this case the default route allowing access by ssh and so on). As I understand it the perfect way would be a server-side configuration but obviously this is not always possible.
Find this well written How-to that explains how to set up a split tunnel to access some hosts inside the vpn network with fixed IP addresses and keep DNS and all other routes to the internet.


text:
Q: Bigrquery cannot coerce integers I've recently started using "bigrquery" package in R to get some data from Google Bigquery, however most of the integer columns in the data frame I receive has NAs.
The same SQL query in Google's own BigQuery dashboard returns valid results. I also tried in python and the same query returns valid results there as well so it's really R-specific (it's not an authorization problem).
What I receive when I call query_exec(query,project=projectID) in R:

What I receive in Google BigQuery or call pd.io.gbq.read_gbq(query,projectID) in Python:

What could be the reason?
Error message I receive for these NAs is:

NAs introduced by coercion to integer range

A: I'm not familiar with R or "bigrquery" specifically, but it sounds like your integer values are being coerced into a 32-bit integer and are out-of-range (BigQuery integers are 64-bit).
Workaround: if you just want to treat the number as an opaque ID, can you cast it to a string in your query?
It isn't clear to me why the same thing would happen for your boolean column, but perhaps you should check that the types are equivalent (maybe integer vs. boolean), since they seem to work for the following column.
Possibly related:
https://github.com/rstats-db/bigrquery/issues/35


text:
Q: подключить к vue-form-wizard проверку vee-validate Всем привет!
В laravel 5.6 / vue.js 2.5.7/ хочу подключить vue-form-wizard ( https://cristijora.github.io/vue-form-wizard/#/?id=call-a-function-before-tab-switch )
с использованием vee-validate либы. Непонятно как организовать валидацию при переходе на следующую закладку :
Я попытался вызвать метод validateDetailsTab которая должна вернуть true/false  в зависимости можно ли перейти на следующюю закладку
но всегда возвращется false из-за асинхронности вызова проверки :
<template>

            <form-wizard @on-complete="onComplete"
                         @on-loading="setLoading"
                         @on-validate="handleValidation"
                         @on-error="handleErrorMessage"
                         shape="tab" :color="wizard_color">

                <tab-content title="Details"  icon="fa fa-comment" :before-change="validateDetailsTab">

                        Name  *

                            <input v-validate="'required|max:255'" v-model="userChat.name"
                                   :class="{ 'form-control':true, 'input': true, 'text-danger': vueErrorsList.has('name') }" name="name" id="name"
                                   type="text" placeholder="name">
                            {{ vueErrorsList.first('name') }}

                    ...

                </tab-content>

                <tab-content title="Additional Info" icon="fa fa-tasks">
                    Task
                </tab-content>

            </form-wizard>

</template>

А как правильно ?
Спасибо!


text:
Q: How to install SUMOLIB using Python3? I am working on a project which has SUMOLIB module as a dependency on , but I have no idea how to install it. I tried doing pip install sumolib, but it shows me that no such module exists.
Can someone tell me how to install SUMOLIB?

A: Maybe look at the downloads page of Sumolib.
https://sumo.dlr.de/docs/Downloads.html

A: sumolib is installed as a part of the SUMO package. It can be found under SUMO_HOME/tools/sumolib.
To use sumolib in a script, check here.


text:
Q: Counting socket.io users across horizontal servers I have multiple socket.io servers scaled horizontally using a redisstore.  I've got rooms setup effectively and am successfully able to broadcast to rooms across servers, etc.  Now I'm trying to build a status page and what I'm failing on figuring out is how to simply count the number of users connected across all servers.
io.sockets.clients('room') and io.sockets.sockets will only tell you the number of connected clients on that one server, not all servers connected to the same RedisStore.
Suggestions?
Thanks.

A: When a user connects to the chatroom, you can atomically increment a user counter in your RedisStore.  When a user disconnects, you decrement the value.  This way Redis maintains the user count and is accessible to all servers.
See INCR and DECR
SET userCount = "0"

When a user connects:
INCR userCount

When a user disconnects:
DECR userCount

A: Here is how I solved it using Redis scripting. It requires version 2.6 or later, so most likely still requires compiling your own instance for now.
Each time a process starts up, I generate a new UUID and leave it in the global scope. I could use the pid, but this feels a little safer.
# Pardon my coffeescript
processId = require('node-uuid').v4()

When a user connects (the socket.io connection event), I then push that user's id into a list of users based on that processId.  I also set the expiry of that key to 30 seconds.
RedisClient.lpush "process:#{processId}", user._id
RedisClient.expire "process:#{processId}", 30

When a user disconnects (the disconnect event), I remove it and update the expiry.
RedisClient.lrem "process:#{processId}", 1, user._id
RedisClient.expire "process:#{processId}", 30

I also setup an function that runs on a 30 second interval to essentially "ping" that key so that it stays there.  So if the process does accidentally die, all those user sessions will essentially disappear.
setInterval ->
  RedisClient.expire "process:#{processId}", 30
, 30 * 1000

Now for the magic. Redis 2.6 includes LUA scripting, which essentially gives a stored procedure sort of functionality. It's really fast and not very processor intensive (they compare it to "almost" running C code).
My stored procedure basically loops through all of the process lists, and creates a user:user_id key with their total count of current logins. This means that if they're logged in with two browsers, etc. it'll still allow me to use logic to tell if they've disconnected completely, or just one of their sessions.
I run this function every 15 seconds on all my processes, and also after a connect/disconnect event. This means that my user counts will most likely be accurate to the second, and never incorrect for more than 15 to 30 seconds.
The code to generate that redis function looks like:
def = require("promised-io/promise").Deferred

reconcileSha = ->
  reconcileFunction = "
    local keys_to_remove = redis.call('KEYS', 'user:*')
    for i=1, #keys_to_remove do
      redis.call('DEL', keys_to_remove[i])
    end

    local processes = redis.call('KEYS', 'process:*')
    for i=1, #processes do
      local users_in_process = redis.call('LRANGE', processes[i], 0, -1)
      for j=1, #users_in_process do
        redis.call('INCR', 'user:' .. users_in_process[j])
      end
    end
  "

  dfd = new def()
  RedisClient.script 'load', reconcileFunction, (err, res) ->
    dfd.resolve(res)
  dfd.promise

And then I can use that in my script later on with:
reconcileSha().then (sha) ->
  RedisClient.evalsha sha, 0, (err, res) ->
    # do stuff

The last thing I do is try and handle some shutdown events to make sure that the process tries it's best to not rely on the redis timeouts and actually shuts down gracefully.
gracefulShutdown = (callback) ->
  console.log "shutdown"
  reconcileSha().then (sha) ->
    RedisClient.del("process:#{processId}")
    RedisClient.evalsha sha, 0, (err, res) ->
      callback() if callback?

# For ctrl-c
process.once 'SIGINT', ->
  gracefulShutdown ->
    process.kill(process.pid, 'SIGINT')

# For nodemon
process.once 'SIGUSR2', ->
  gracefulShutdown ->
    process.kill(process.pid, 'SIGUSR2')

So far it's been working great.
One thing I still want to do is make it so that the redis function returns any keys that have changed their values. This way I could actually send out an event if the counts have changed for a particular user without any of the servers actively knowing (like if a process dies). For now, I have to rely on polling the user:* values again to know that it's changed. It works, but it could be better...

A: I solved this by having each server periodically set a user count in redis with an expiration that included their own pid:
every  do setex userCount:<pid> <interval+10> <count>
then the status server can query for each of these keys, and then get the values for each key:
for each keys userCount* do total+=get <key>
so if a server crashes or is shutdown then its counts will drop out of redis after interval+10
sorry about the ugly pseudocode. :)

A: You could use hash keys to store the values.
When a user connects to server 1 you could set a field called "srv1" on a key called "userCounts".  Just override the value to whatever the current count is using HSET.  No need to increment/decrement.  Just set the current value known by socket.io.
HSET userCounts srv1 "5"

When another user connects to a different server set a different field.
HSET userCounts srv2 "10"

Then any server can get the total by returning all the fields from "userCounts" and adding them together using HVALS to return a value list.
HVALS userCounts

When a server crashes you'll need to run a script in response to the crash that removes that server's field from userCounts or HSET it to "0".
You can look at Forever to automate restarting the server.


text:
Q: segmentation fault: 11 in C code Why am I getting a segmentation fault with this code?
 /* solver.h header file */
 10 struct options{
 11     unsigned int one:1, two:1, three:1, four:1, five:1, six:1, seven:1, eight:1, nine:1;
 12 };
 13
 14
 15 /* structure to describe a cell */
 16 struct cell{
 17     short value;
 18     struct options open_options;
 19 };

solver.c:
  5 #include <stdio.h>
  6 #include "solver.h"
  7
  8
  9
 10
 11
 12 int main(){
 13         struct cell board [9][9];
 14         int i=0,j=0;
 15
 16
 17         for(i = 1; i<10; i++)
 18                 for(j = 1; j<10; j++)
 19                         (board[i][j]).value = j;
 20
 21         for(i = 1; i<10; i++){
 22                 for(j = 1; j<10; j++)
 23                         printf(" %d",(board[i][j]).value);
 24                 printf("\n");
 25         }
 26         return 0;
 27 }

output:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
Segmentation fault: 11

A: some_type array[9]; defines array to be an array of 9 elements, with subscripts going from 0 to 8 inclusive. You can't use array[9].

A: Arrays are indexed from 0, so the loops should be for(i = 0; i<9; i++) and not for(i = 1; i<10; i++)
In your case, you probably override part of the stack, but in general, going out of boundaries results in undefined behavior.

A: board[9][9] will contain elements with indices in the range 0...8, not 1...9. When you assigned to board[9][whatever], you actually overwrote memory that didn't belong to you, and this happened to cause the program to explode when return 0 handed control back to the C runtime and it started walking its structures to perform shut down.


text:
Q: Postresql remove single table via shell script I have a config script that resets my development PostgreSQL database. This is written as a shell script. However, I would like to keep one table that does not have any foreign keys anywhere else. Therefore I am looking for a way to delete single tables rather than the whole database.
This is my current setup, which works perfectly. It drops the database, creates new and creates all the tables for me:
#!/bin/bash

export PGPASSWORD=$1

echo "Configuring ..."

dropdb -U $2 $3
createdb -U $2 $3

psql -U $2 $3 < ./bin/sql/user.sql
psql -U $2 $3 < ./bin/sql/account.sql
psql -U $2 $3 < ./bin/sql/account-user.sql
psql -U $2 $3 < ./bin/sql/fuelprice.sql
psql -U $2 $3 < ./bin/sql/vehicle.sql
psql -U $2 $3 < ./bin/sql/account-vehicle.sql

echo "All configured."

However, I would like to be able to instead of dropping the database and create new one just delete certain tables and re-create those.
I have tried following:
#!/bin/bash

export PGPASSWORD=$1

echo "Configuring ..."

psql -U $2 $3 -c `DROP TABLE "Config.User"`

psql -U $2 $3 < ./bin/sql/user.sql

echo "All configured."

The part that I can not make work is:
psql -U $2 $3 -c DROP TABLE "Config.User"
I am getting following reply from the command line:
psql: option requires an argument -- c
I had a look on the help but I am unsure what additional argument I might be missing.
Please note that $1 is password variable, $2 is user and $3 is database.

A: As per the comment from user 'melpomene'. All that was needed is to swap ` for '.


text:
Q: How to get audio/video source WP REST API Fields? I'm using WP REST API V2 in my project. After sending Get request to get posts, I don't see fields with the source of my audio/video wordpress posts (youtube or soundcloud sources).
I would like to know how to include source field of (audio and video posts) into my request results. If my post is an audio or video post:

These posts have source field that can be set to soundcloud or youtube track url:

I need to get these sources in the results of my get request. I have an idea that it should look similar to getting thumbnail url setting up a function to get a field in functions.php file , but I don't know how to set it and what function with which fields should it be to get source urls of audio and video posts.
P.S. Example of getting thumbnail url function in functions.php file:
add_action( 'rest_api_init', 'ccw_insert_thumbnail_url' );
                function ccw_insert_thumbnail_url() {
                    register_rest_field( 'post',
                        'ccw_thumbnail',
                        array(
                            'get_callback'    => 'ccw_get_thumbnail_url',
                            'update_callback' => null,
                            'schema'          => null,
                        )
                    );
                }

            function ccw_get_thumbnail_url($post){
                if(has_post_thumbnail($post['id'])){
                    $imgArray = wp_get_attachment_image_src( get_post_thumbnail_id( $post['id'] ), 'thumbnail' );
                    $imgURL = $imgArray[0];
                    return $imgURL;
                }else{
                    return false;
                }
            }


text:
Q: PyCharm does not find submodules, but console does I cannot properly access submodules in pycharm. Let's say I have
import numpy as np

And then I tried accessing the testing submodule as np.testing.assert_all_close(). The code runs, but pycharm will not recognise the testing submodule, or do any kind of autocompletion. If I import like this however, it works:
import numpy as np
import numpy.testing

Then it works as np.testing.... This did not happen before, maybe it is an interpreter issue? I am using poetry as environment:
https://plugins.jetbrains.com/plugin/14307-poetry
If I open an iPython console using this same environment, there is no issue, autocomplete works perfectly.


text:
Q: Determining the automorphism of a vertex transitive/Cayley graph which will map a vertex to another given vertex under some conditions A Cayley graph is a vertex-transitive graph, meaning that given any two vertices $v_1, v_2$ in the vertex set of the graph $X$ ($V(X)$), there exists an automorphism $\phi:V(X) \rightarrow V(X)$, such that $\phi(v_1)=v_2$.
For a Cayley graph say, $X=Cay((\mathbb{Z}_p \times \mathbb{Z}_p) \rtimes \mathbb{Z}_q, \{s,t\})$, where $|s|=q,|t|=p$, let $\theta: \mathbb{Z}_q \rightarrow Aut(\mathbb{Z}_p \times \mathbb{Z}_p)$ be known.
As an example, when $q=3$, $\theta_s(t^iu^j)=s^{-1}t^iu^js=(t^{-j}u^{i-j})$, where ${t,u}$ forms a basis of $(\mathbb{Z}_p \times \mathbb{Z}_p)$ with $u= \theta_s(t)$.
For a vertex $v_1=(t^{k_1}u^{k_2},s^{k_3})$, if I trace along a sequence of edges, say $sts^{-1}t^2$, then it ends up at the vertex $v_2=(t^{m_1}u^{m_2},s^{m_3})$ (i.e. $v_1 sts^{-1}t^2 =v_2$).
Is it possible to find an automorphism $\phi:V(X) \rightarrow V(X)$, which will map $v_1$ to $v_2$ if I know the values of $k_1, k_2, k_3, m_1, m_2, m_3, t, s, \theta_s, p, q$ such that it will satisfy the following condition?
If I calculate the $\phi(v^\prime)$ for any other vertex $v^\prime \in X$, and get $\phi(v^\prime)=w$, then $w$ has to be a vertex present at a point obtained by tracing along the same sequence of edges (path) $sts^{-1}t^2$ starting at $v^\prime$. i.e. $v^\prime sts^{-1}t^2 =w$.
How to get such an automorphism if possible?
Thanks a lot in advance.


text:
Q: Is my DFD accurate? This is my first ever DFD that I made after my fair share of learning but I have no way of verifying whether it is correct or not. Although I have taken utmost care to make sure it is right, I may be wrong.
Here is the scenario:
Bebop Records is a mail-order company that distributes CDs and tapes at discount prices to record club members.  When an order processing clerk receives an order form, he or she verifies that the sender is a club member by checking the Member file.  If the sender is not a member, the clerk returns the order along with a membership application form.  If the customer is a member, the clerk verifies the order item data by checking the Item file.
Then the clerk enters the order data and saves it to the Daily Order file. The clerk also prints an invoice and shipping list for each order, which are forwarded to Order Fulfilment.
And here is my diagram:

A: Tom DeMarco invented Data Flow Diagrams, and described them in his book, "Structured Analysis and System Specification".  One of his key points was that they're either right or they're OBVIOUSLY wrong.
Your DFD appears, unfortunately, to fall in the latter category.
Your text spec says that the clerk RETURNS non-member order forms, presumably to the customer, along with a blank membership form.
Your DFD, however, shows a non-member order form as going to Order Fulfillment, having gone through all the stages, just like a member order form.


text: Q: Перенаправить на другую страницу Уважаемые подскажите пожалуйста. Есть у меня asp.net webApi 2 application. В нем у меня  authorizationFilter: AuthorizationFilterAttribute. Переопределяю я метод onAuthorizationAsync. В нем я запрашиваю текущие права пользователя. Вопрос такой: как мне отсюда перенаправить пользователя на другую страницу (например page.html) если у него недостаточно прав ? Это можно вроде как то сделать с помощью HttpActionContext в response передать HttpResponseMessage но у меня не получается отправить именно на page.html(находится в папке с проектом).


text:
Q: How to get sum of a column in a table (for a particular employeeID) and store that in another column in another table? I have two tables, "Employees" and "Expenses"
Employees table has two columns "EmployeeID(PK)" and "Expense_Total"
Expenses has two columns "EmployeeID" and "Expense".
 Please note EmployeeID here is not a PK as one employee could have many expenses. I want to find the sum total for all employees and then insert that into "Expense_Total" column in "Employees" table, for each respective employee. How to do this? I've attempted the following below:
            PreparedStatement ps1 = con.prepareStatement("UPDATE payroll_system.Employees emp JOIN payroll_system.Expenses exp ON emp.employeeID = exp.employeeID SET emp.Expense_Total = //I need the sum here//");

A: I think you have try following query.
If you insert first time means you have no records in Employess Table than you can use this insert query to insert Expense total :
INSERT INTO `employees`(id,expense_total) SELECT emp_id, SUM(expense) FROM expenses GROUP BY emp_id

If you have already data into the Employees than you need to execute Update Query into the Employees Table :
UPDATE employees emp SET emp.expense_total = (SELECT SUM(expense) FROM expenses WHERE emp_id = emp.id)

Please try this.
You can check here : http://sqlfiddle.com/#!9/3f4d67

A: UPDATE
  Employees em
  LEFT JOIN(
    SELECT
      e.employeeID AS employeeID,
      SUM(e.expense) AS totAmnt
    FROM
      Expense e
    GROUP BY
      e.employeeID) AS t
    ON t.employeeID = em.employeeID
SET
  em.Expense_Total = IFNULL(t.totAmnt,0);

Bye


text:
Q: Google Sheets: Conditional Formatting - color all non-empty cells in a row within a range based on the value of another cell?  Hello!
 So I have different (non-numeric) values in Column B (B3:B). And I have transactions (formatted as currency) in Columns C through E (range C3:E). So I want every cell in any given row within that range to be colored, whenever that cell  has some value (non-empty) AND the corresponding cell (of the same row) in Column B has "$" value in it.
 In other words I need a formula that would check the whole (C3:E) range, find all non-empty cells (assuming that there will be blank cells in that range), check the corresponding (of the same row number) cells in Column B and, if those corresponding cells contain "$" value, color all the non-empty cells in that row (even if there are several non-empty cells in there) within the (C3:E) range.
Let's say we see that in row 7 there are two cells (and they are within our C3:E range) that have values 23.54 and 67.90 (non-empty). That's the first condition. And we also see that the value of the corresponding cell in row 7 of Column B (B7) is "$". That's the second condition. So only cells C7 and E7 (not the whole C7-E7 row) must be colored by conditional formatting. So in the table I provided only cells D4, C7 and E7 must be colored.

 That's the custom formula for Conditional Formatting that I came up with =AND(NOT(ISBLANK(C3:E)),AND($B3="$")) but the problem is that it colors the whole row instead of the non-empty cells in that row only.
 Where am I making a mistake?

Please advise.

     Column B      Column C     Column D     Column E
3      None               14.50                                    12.004         $                                         45.905      Some               23.906       Few7        $                    23.54                                   67.90

P.S: What would the formula be to color the cells that contain anything else but "$" with another color?

A: try like this:
=($B3="$")*(C3<>"")


text:
Q: async running in main thread Having this async method that return a coroutine
async def async_task() -> str:
    time.sleep(1)
    print(threading.current_thread().name)
    return f"Hello Async world {random.randint(1, 100)}"

why when I await for the result
await async_task()

the print says that I'm in the main thread?
MainThread

I was expecting to see a thread name of the event loop


text:
Q: Problem adding to solr index using Django-Haystack I'm trying to index a model in Solr with django-haystack, but it returns me the following error(when using rebuild_index or update_index) :
Failed to add documents to Solr: [Reason: ERROR:unknown field 'django_ct']

I followed step by step the "getting started" of Haystack-Search.
I'm using :

*

*the latest version of Apache Solr (1.4.1)

*the latest version of django-haystack

my search_indexes.py :
from haystack.indexes import *
from haystack import site
from models import Entity

class EntityIndex(SearchIndex):
    name = CharField(document=True)

    def get_queryset(self):
        return Entity.objects.all()

site.register(Entity, EntityIndex)

A: Be sure your $SOLR_HOME/conf/schema.xml file contains the 'django_ct' field declaration.  That is a custom field and needs to be added manually along with any other custom fields you are using.

A: Try using text = CharField(document


text:
Q: How can we not include default.ctp in cakephp? I'm creating a web page in cakephp. I've a login form, before a user can access it. I've created the login form too. I've written my nav bar in default.ctp. Since, the nav bar is written in default.ctp, the nav-bar is visible in login page too. But, I don't want to show that in the login page. I learnt that I need to create my new layout and include it in my page. This is how I tried:
LoginController.php
<?php
    namespace App\Controller;
    session_start ();

    use App\Controller\AppController;
    use Cake\ORM\TableRegistry;
    class LoginController extends AppController
    {
     public function loginindex(){
            $this->layout= 'loginlayout';
            $this->render ( 'login' );
        }
}

loginlayout.ctp
<?php
$cakeDescription = 'Takt Time';

use Cake\Routing\Router;
?>
<!DOCTYPE html>

<?= $this->Html->charset() ?>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?= $cakeDescription ?> ::
        <?= $this->fetch('title') ?>
    </title>

    <?= $this->fetch('meta') ?>
    <?= $this->fetch('css') ?>
    <?= $this->fetch('script') ?>

login.ctp
<?php
    use Cake\Routing\Router;
    echo $this->Form->create(false,array('url'=>array('controller'=>'login','action'=>'loginentry'),'id'=>'myform'));
?>

            <?php echo $this->Html->image('logo-white.png'); ?>

 Demand

 Available time

 Pulse

            <form novalidate="novalidate" method="post" id="myform">

                    Sign In to your account

                        <input name="LoginID" id="LoginID" class="form-control"
                            placeholder="Username" type="text">

                        <input name="Password" id="Password" class="form-control"
                            placeholder="Password" type="password">

                    <input value="SIGN IN" class="btn btn-primary btn-sm" type="submit"
                        id="btnSave" name="btnSave"> Forgot your password?

            </form>

This is how I did. In loginlayout.ctp I didn't write anything in the body section because, I've customised my home.ctp to display login form. So, I'm just going to display my login page, without the nav-bars.
But, the problem is the login page appears with the nav-bars. What's wrong with the above code? What should I add or change?


text:
Q: CPANEL root folder deleted By mistake I have deleted the root folder which include public_html, ssl , var and all hidden files because I wanted to take a backup as my previous backup has all these folders.
But now I am not able to access my Wp-Admin.
Can someone tell me what should I do in this case?
I was just playing with wordpress, so if someone can point me to fresh install instead of restore that would also be good.

A: Recreate the public_html folder from a linux shell console:
mkdir public_html
chmod 750 public_html
chown cpaneluser:nobody public_html

Then restore your files from backup. Be sure that all the files inside the public_html/ folder to have this ownership cpaneluser:cpaneluser (where cpaneluser is your account cpanel username)
If you do not want to restore then be sure you have created the public_html/ folder with the permissions mentioned above and then just reinstall wordpress. You can do that manually using FTP or you can just use Softaculous or any other installer that might be available in your cpanel account.


text:
Q: I'm having issues with making a scoreboard with discord.js So I'm trying to develop a discord bot with discord.js, and I wanted to make a scoreboard, but for some reason I can't make the variable change when a command to add a point to the scoreboard is called. Can somebody help? The points constantly stay at 0. Also I'm kind of a beginner at programming so if you could explain in an easy way to understand, it'd be much appreciated. Thanks!
client.on('message', msg => {

    var x = 0
    var y = 0
    if(msg.content.toLowerCase() === 'r!score x 1') {
        x = x + 1;
        msg.channel.send("Team y has won a point, now they're at " + x + "!")
    }else if(msg.content.toLowerCase() === 'r!score y 1') {
        y = y + 1;
        msg.channel.send("Team y has won a point, now they're at " + y + "!")
    } else if(msg.content.toLowerCase() === 'r!placar') {

        const scoreboard = new Discord.MessageEmbed()
    .setColor("#0099ff")
    .setTitle("**Scoreboard**")
    .addFields(
        {name: "__Team X__", value: x + " points"},
        {name: "__Team Y__", value: y + " points"}
    );
        msg.channel.send(scoreboard)

    }

})

A: You probably wanted to use Message Collectors, but I will show a different way. This can be adapted to your code to fit some sort of game.
let x = 0,
y = 0;
client.on("message", msg => {
  if(msg.content === 'r!score x 1') {
    msg.channel.send(`Team x has won a point, now they're at ${++x}!`)
  } else if(msg.content === 'r!score x 2') {
    msg.channel.send(`Team y has won a point, now they're at ${++y}!`)
  } else if(msg.content === 'r!placar') {
    const scoreboard = new Discord.MessageEmbed()
    .setColor("#0099ff")
    .setTitle("**Scoreboard**")
    .addFields(
      {name: "__Team X__", value: x + " points"},
      {name: "__Team Y__", value: y + " points"}
    );
        msg.channel.send(scoreboard)
  }
})

Why is your code not working?
Your code is only saying 0 for both because you are declaring the variable inside the function. Every callback, the variable gets declared and the value is set as 0. You then check if the message content is r!placar then send the embed where x is 0 and y is the same. I declared it outside of the callback which lets you access it from anywhere in the callback, keeping the value.


text:
Q: Mongo query takes long time on production but fast on development My query:
export const getBimObjectsByProperty = async (projectId: string, forgeFile: string, propertyName: string, value: string, pset?: string,) => {
  try {
    let query = {
      project: new mongoose.Types.ObjectId(projectId),
      forgeFile: new mongoose.Types.ObjectId(forgeFile),
      properties: {
        $elemMatch: {
          property: propertyName,
          pset,
          value
        }
      }
    };
    const response = await mongoose.model('bimObject').find(query).exec();
    return Promise.resolve(response);
  } catch (error) {
    return Promise.reject(error);
  }
};

This takes 4 seconds on development and 17s in production.
The returned data is not much so it's not a bandwidth problem.
What can be the reason it's so slow on production? Is it hardware? Should I increase CPU?


text:
Q: Conjectured value of a difficult integral with Dedekind eta functions In my research on quantum groups I have the following conjecture:
\begin{equation}
\int_0^\infty\frac{\eta (2 i x)^8}{\eta (i x)^2 \eta (4 i x)^2}\,dx\,{\stackrel?=}\,\frac{K(\tfrac{1}{\sqrt{2}})}{\pi}\tag{1}
\end{equation}
where
\begin{equation}
\eta(ix)=e^{-\frac{\pi x}{12}}\prod_{n=1}^\infty (1-e^{-2n\pi x})
\end{equation}
is the Dedekind eta function and
\begin{equation}
K(\tfrac{1}{\sqrt{2}})=\frac{\Gamma^2(\tfrac14)}{4\sqrt{\pi}}
\end{equation}
is the Elliptic integral singular value.
This value has been guessed using Inverse symbolic calculator and then checked numerically to a high precision, but I do not have a proof.
Question: Is (1) true?

A: The following solution uses the link between elliptic integrals and theta functions.

Let's use $q=e^{-\pi x} $ and then we define function $f$ via $$f(q) =q^{1/12}\prod_{n=1}^{\infty}(1-q^{2n})=\eta(ix)\tag{1}$$ Let $x=K(k') /K(k) $ where $k, k'$ are elliptic moduli complementary to each other and $K(k)=K $ is the complete elliptic integral of the first kind. From the theory of elliptic integrals and theta functions we have
\begin{align}
f(q)=\eta(ix)&=2^{-1/3}\sqrt{\frac{2K} {\pi}} (kk') ^{1/6}\tag{2a}\\
f(q^2)=\eta(2ix)&=2^{-2/3}\sqrt {\frac {2K}{\pi}}k^{1/3}k'^{1/12}\tag{2b}\\
f(q^4)=\eta(4ix)&=2^{-13/12}\sqrt{\frac{2K}{\pi}}\frac{k^{2/3}k'^{1/24}}{(1+k')^{1/4}}\tag{2c}
\end{align}
The integrand in question is $$\frac{f^8(q^2)} {f^2(q)f^2(q^4)}=2^{-5/2}\left(\frac{2K}{\pi}\right)^2kk'^{1/4}(1+k')^{1/2} $$ and we have $$\frac{dx} {dk} =\frac{dx}{dq}\cdot\frac {dq} {dk} =-\frac{1} {\pi q} \cdot\frac{\pi^2 q}{2kk'^2K^2} =-\frac{\pi} {2kk'^2K^2}\tag{3}$$ so that the desired integral is equal to $$\frac{1}{2\pi\sqrt{2}}\int_{0}^{1}k'^{-7/4}(1+k')^{1/2}\,dk=\frac{1}{2\pi\sqrt{2}}\int_{0}^{1}t^{-3/4}(1-t)^{-1/2}\,dt\tag{4}$$ (via substitution $k'=\sqrt{1-k^2}=t$) which is evaluated easily via Beta/Gamma functions to obtain desired result.

We were lucky that after switching from $x$ to $k$ the elliptic integral $K$ got cancelled and the resulting integral was having an algebraic function as an integrand. Thus the original integral appears to be designed to have such a nice evaluation. See this answer for another instance of this technique.


text:
Q: Embedding rCharts graph into slidify slide deck I am still trying to get a graph that I have produced using rCharts into a slidify slide deck. I have tried copying the script that rCharts produces into slidify's .Rmd file but all I get is an empty slide.
Here is the .Rmd file:
---
title       : Test Sankey
subtitle    :
author      : Matthew
job         :
framework   : io2012        # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      #
widgets     : [d3_sankey]   # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
---

Slide 1

---

The graph should be on the next slide.

---

When I compile the .Rmd file in R I get the following output:
slidify("index.Rmd")

processing file: index.Rmd
  |.................................................................| 100%
  ordinary text without R code

output file: index.md

Copying files to libraries/frameworks/io2012...
Copying files to libraries/highlighters/highlight.js...
Copying files to libraries/widgets/d3_sankey...
[1] "index.html"

Any idea on what I am doing wrong here? Thank you very much!


text:
Q: Mongoose mixed type schema is getting processed as an array of keys of type String, but no values I have a mongoose schema that looks something like this:
"datetime": {"type": Date}
"sequence": {"type": Number}
"extra": {"type": mongoose.Schema.Types.Mixed}

For some reason, the "extra" key in my model is processing dictionary's of key-value pairs as an array of strings, where each string is a key in the dictionary.  For example, the following data:
{
    "datetime": new Date(),
    "sequence": 10,
    "extra": {"val1": 5, "val2": "hello"}
}

is getting processed as follows:
{
    "datetime":  [Date object]
    "sequence": 10,
    "extra": ["val1", "val2"]
}

This data is being populated in Python, and the "extra" field is being provided as a Python dictionary.  The entire data set is then forwarded to a REST API via the requests module.  The contents of this "extra" field can vary quite considerably, which is why I had it defined as "mixed" in my model.
Does anyone know why mongoose is parsing this field this way?

A: I think my problem was related to the different between request's optional data / json parameters.  I was using:
request.post(url, myDictionary)

which defaults to the data key, when I should have been using:
request.post(url, json=myDictionary)

The problem with this, of course, is that a Python datetime object can not be serialized here, so I simply used time.time() instead.
In regards to my mongoose schema, the "extra" field doesn't have a defined schema, so that data is simply provided "as-is".
Hopefully this is useful in the event that someone has a similar problem at some point.


text:
Q: Detecting python functions using a regex? I want to pull out all of the python functions within a python script. Is there any single regex I can use to do this, e.g:
import re
all_functions = re.findall(regex, python_script)

I have implemented a very cumbersome way of doing this involving many if statements, but I feel there is a more elegant solution with regexes.
I think the regex should be something like this:
'def.*?\n\S'

because:

*

*Functions start with def

*Followed by anything (but we want to be non-greedy)

*A function ends when after a newline character \n, the starting character of the next line is not white space \S
However, I can't seem to get this to work over multiple lines.
Edit: Python functions may be contained in files that don't have .py extensions; e.g. they can be contained in IPython notebooks with .ipynb extension so I can't necessarily always import the code and use dir().

A: Don't use a regular expression. Have Python parse the code for you and find all the function definitions with the ast module:
import ast

with open(python_sourcefile) as sourcefile:
    tree = ast.parse(sourcefile.read(), sourcefile.name)

for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef):
        print(node.name)

If the code is contained in .ipynb files, parse the file and extract the code cells, then put the input source code from those through the same process.
Demo with the ast module source itself:
>>> import ast
>>> with open(ast.__file__.rstrip('c')) as sourcefile:
...     tree = ast.parse(sourcefile.read(), sourcefile.name)
...
>>> for node in ast.walk(tree):
...     if isinstance(node, ast.FunctionDef):
...         print(node.name)
...
parse
literal_eval
dump
copy_location
fix_missing_locations
increment_lineno
iter_fields
iter_child_nodes
get_docstring
walk
_convert
_format
_fix
visit
generic_visit
generic_visit

A: This regex might work out for you:
re.compile('def (?P<function>(?P<function_name>.*?)\((?P<function_args>.*)\)):')
I used groups so you could get information out easily using the groupdict() method of a match object, but if you just want the declaration line, you can use
    re.compile('def .*?\(.*)\):')
This regex could be tighter (it'll accept def do something(1,2,3): even though it's not a valid function), but if your python files are syntactically correct and you absolutely want to use a regex, this'll do the job for you.


text:
Q: How can i change the color per section in this line chart? So I am trying to do this chart

And I have this at this moment

I need to do this simple thing, with the data put this colored background

A: Assuming you already have an x axis set up, perhaps you could do something like this (adjust as necessary if you're using v5):
var overlays = [[0, 10], [30, 60]];

svg.selectAll('rect.overlay')
  .data(overlays)
  .enter()
  .append('rect')
  .attr('class', 'overlay')
  .attr('x', d => x(d[0])) // place the rectangle on the x axis based on the start point
  .attr('width', d => x(d[1]) - x(d[0])) // calculate the width
  .attr('y', 0)
  .attr('height', height)
  .attr('fill', '#00000022');


text:
Q: Exception when exposing $window.print on angular scope I'm exposing $window.print() on scope like so:
$scope.print = $window.print;

However, this results in an exception:

angular.js:13642 Exception message: Illegal invocation

I need to call print thru a separate function, like so to make it work:
$scope.print = printFn;
function printFn() { $window.print(); }

Any ideas why I can't use the first alternative?
Running Angular 1.5.5

A: It is safe to assume that every object method depends on this unless proven otherwise, so method should be bound to its context before it is assigned as another object's method.
window.print is native method, in Chrome it just throws Illegal invocation instead of complaining on inappropriate this context.
Instead of wrapper function, it may be
$scope.print = $window.print.bind($window);

or
$scope.print = angular.bind($window, $window.print);


text:
Q: Upload file could not be moved to wp-content/uploads I know it has been asked over and over again on the internet and i spend hours digging deeper into the web. But the no answer so far.
Why we get this error when you upload a file
The uploaded file could not be moved to wp-content/uploads

*

*I tried various file persimission on folders and files in the ftp.

*Tried a fresh install WP.

*I tried this code define( 'UPLOADS', 'wp-content/uploads' );

*I tried adding the path in the wp/options.php location for upload_path.

*I created the upload folder manually, because when i installed WP the wp-content folder does not have any folder named uploads
But nothing so far..
Local Server
There is no issue so far in the local server.
I am just a beginner and learning WordPress from scratch. The only issue i got stuck is this file upload thing.
Can anyone help me!

A: I experienced this error while preparing an AWS ec2 Bitnami micro-instance configured for WordPress.  This approach requires the command-line, so please launch a terminal-session and begin via SSH into the deployed production.

*

*cd into the application document-root:
/home/bitnami/apps/wordpress/htdocs:

*Execute the below command to identify the Apache web-server:
ps aux | egrep '(apache|httpd)'
Revealing daemon in this case, as captured within the terminal-output screenshot below:

*Ultimately, the below-command remediated the error; users should now have the ability to successfully media-upload content via the WordPress Content Management system/admin-panel:
sudo chown -R daemon:daemon wp-content
I recommend the following dox for guidance regarding the Linux-commands referenced herein:

*

*Finding out what user Apache is running as?

*what does this line mean on my ps aux ../apache2 -k start


text:
Q: C# Form modyfing in static methods I ran into some problems with my C# program. I want to create stopwatch (countdown from certain value), that is started, when a certain key is pressed. To handle keys i use low-level keyboard hook. But this class has static methods, so if I want to call a method from different class, that is not static, i have to create a new instance. With the countdown, I want to change the Text property of the TextBox element every tick (second). The problem is, how to change the properties of TextBox every tick (in the Countdown class), when I have to create a new instance of Countdown class in the static method, thus the TextBox will no longer response to the previous TextBox. My code works perfectly fine, the keys are recognized, the timer is counting down and showing the value of seconds in separate MessageBox'es (for debug), but it won't change the text in the form.
If it would help you to understand what I wrote above, I can give you my code. Just say so in the comment.
Thanks for help in advance.
The code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace stopwatch2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        InterceptKeys.InterceptInit();
    }

    private void Form1_Closing(object sender, CancelEventArgs e)
    {
        InterceptKeys.Unhook();
    }

    public void changeText(string text)
    {

        MessageBox.Show(text); //for debug
        textBox1.Text = text;
    }

    class InterceptKeys
    {

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        public static void InterceptInit()
        {
            _hookID = SetHook(_proc);
        }

        public static void Unhook()
        {
            UnhookWindowsHookEx(_hookID);
        }

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

        public static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {

            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);

                Countdown timer = new Countdown(); //creating new instance

                if ((Keys)vkCode == Keys.Home)
                {

                    timer.StartTimer();

                }

                if ((Keys)vkCode == Keys.End)
                {

                    timer.StopTimer();

                }

            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

    }

   public partial class Countdown : Form1
    {

        public System.Windows.Forms.Timer timer1;
        public int counter = 60;

        public void StartTimer()
        {

            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000; // 1 second
            timer1.Start();
            changeText(counter.ToString());

        }

        public void timer1_Tick(object sender, EventArgs e)
        {

            counter--;
            if (counter == 0)
                counter = 60;

            changeText(counter.ToString());

        }

        public void StopTimer()
        {
            timer1.Stop();
        }

     }

  }

}

A: So, first off, you don't want Countdown to extend Form1.  This is giving you the false impression that you're able to access the members of Form1, but you just can't.  You're creating an entirely new form each time you create a new Countdown instance with it's own textbox and it's own...everything.
Worse still, you create a new Countdown event each time your hook handler is fired, so you're not stopping the timer on the same instance of Countdown that you have previously started.
InterceptKeys also shouldn't be an inner class of Form1, it should be it's own stand alone class in its own file.
In all honesty, I don't even think the Countdown class should exist; it's methods should belong in one of the two other classes.
Let's start by looking at InterceptKeys.  You can see that 90% of the class is just creating the hooks and determining if it's an event that you "care about".  We then only have a little bit of code (that 10%) of doing whatever needs to happen when something we care about happens.
There is a way we can handle this more effectively to address "separation of concerns".  The InterceptKeys class only needs to handle the boilerplace code of setting up a keyboard hook and filtering out the ones we don't care about.  We would like to move the last 10% of code out of this class.  Events are a great way to do this.  Logically there are two "events" that happen here, one is when the home key is pressed, the other is when the end key is pressed.  So we'll start by creating these two events inside of InterceptKeys:
public static event Action HomePressed;
public static event Action EndPressed;

Now we can just fire these two events instead of calling the method of another class at the appropriate locations.  Just replace:
Countdown timer = new Countdown(); //creating new instance
if ((Keys)vkCode == Keys.Home)
{
    timer.StartTimer();
}
if ((Keys)vkCode == Keys.End)
{
    timer.StopTimer();
}

with:
if ((Keys)vkCode == Keys.Home)
{
    if(HomePressed != null) HomePressed();
}
if ((Keys)vkCode == Keys.End)
{
    if(EndPressed != null) EndPressed();
}

So, now InterceptKeys has two events, now what?  Now we go to where InterceptKeys is initialized in Form1 and handle the events.  Before we do this we'll first want to grab everything that was once inside of Countdown and and put it right in Form1, just move the whole thing.  With all of those methods there we can do this:
private void Form1_Load(object sender, EventArgs e)
{
    InterceptKeys.InterceptInit();
    InterceptKeys.HomePressed += ()=> StartTimer();
    InterceptKeys.EndPressed += ()=> StopTimer();
}

Now anytime one of those two keys are pressed the appropriate method is called on the existing method of this form.  On top of that, we have now moved all of the code that is manipulating the display of the form to that form's definition, while ensuring that all of that nasty keyboard hook stuff is off in it's own little world.  "Separation of concerns", everything is in it's own appropriate place.
On a side note, you should really make timer1 and counter private fields, not public fields.  You're not using them publicly, which is good, but you don't want to ever do so in the future.  You can create methods that provide limited access to those fields as needed (which is what you're currently doing).
There's just one thing left.  Chances are each time Home is pressed you don't want to start a new timer.  The old timer will still be around, so then you'll have two, three, or more timers.  What's more likely is that you just want to restart the existing timer.  This is easy enough to do.
In StartTimer you can just not create a new timer but instead manipulate the existing one.  Remove everything from it's body except:
timer1.Start();
changeText(counter.ToString());

Then just create and configure the Timer when the form is first loaded:
private void Form1_Load(object sender, EventArgs e)
{
    timer1 = new System.Windows.Forms.Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 1000; // 1 second

    InterceptKeys.InterceptInit();
    InterceptKeys.HomePressed += ()=> StartTimer();
    InterceptKeys.EndPressed += ()=> StopTimer();
}


text:
Q: Installation and configuration of DSPACE as Federated repository We already have dspace installed in various institutions across the country and want to deploy a centralized DSPACE repository as part of the federated repository. Contents from the branch repository will be synced to the centralized repository as soon as they are published. Contents from the centralized repository are then synced back to other branch repositories. Contents are not synced directly between branch repositories but only through the centralized repository.
Please we welcome ideas on how to achieve this as while we have various references including http://www.dlib.org/dlib/july06/tansley/07tansley.html and http://link.springer.com/chapter/10.1007/978-3-642-40276-0_21, we cant seem to make any headway.

A: For the first part of the puzzle, pulling the contents of your branch repositories into the central one, you could look at this feature:
https://wiki.duraspace.org/display/DSDOC5x/XMLUI+Configuration+and+Customization#XMLUIConfigurationandCustomization-HarvestingItemsfromXMLUIviaOAI-OREorOAI-PMH
The second challenge, having the branch repositories pull back changes/or new items from the central one, is quite another thing.
Unidirectional integrations where one repository is clearly the master record for a particular item is quite straightforward. However, bidirectional updates and managing the different cases and edge cases around changes happening in multiple places to the same items, is a big challenge.
So basically I'm advising you to reconsider your strategy and check if a scenario where one repository is always the master record for a particular item would also fit your use cases.


text:
Q: How to compare opening hours? I want to compare opening hours stored on my server with the current time.
Given the following:
start: 09.00
end:   00.30
I want the result if the store is open or closed. When the current time isn't in the given start and end time the store is closed.
The code i use until now does not work. I get the error:

TypeError: Cannot read property '3' of undefined

firebase.database().ref("v3/standalonelist/bars").on('value', function(snapshot) {

    $timeout(function() {
      $scope.content = snapshot.val();
      snapshot.forEach(function(childSnapshot) {

        $scope.data1 = [childSnapshot.val()];
        $scope.locations1 = $scope.data1

        $scope.locations1.forEach(function(item) {

        $scope.getMinutes = function(str) {
                var time = str.split('.');
                return time[0] * 60 + time[1] * 1;
              }
              $scope.getMinutesNow = function() {
                var timeNow = new Date();
                return timeNow.getHours() * 60 + timeNow.getMinutes();
              }
              var a = new Date();
              var day = a.getDay(); // 3
              var now = $scope.getMinutesNow();
              console.log(item.opens[day]); // returns 09.00
              var start = $scope.getMinutes(item.opens[day]); // 09.00
              var end = $scope.getMinutes(item.closes[day]); // 01.20
              if (start > end) {
                end += $scope.getMinutes('24.00');
              }

              if ((now > start) && (now < end)) {
                $scope.$apply(function() {
                  $scope.open = true; // Store is open
                })

              } else {
                $scope.open = false; // Store is closed
              }
         })
       })

A: I think you are making it a little more complicated than it has to be...
var today = new Date(),
    open = "Open",
    closed = "Closed",
    display = document.getElementById('display'),
    start = new Date(), end = new Date();

    // Set the opening hour:minutes
    start.setHours(10);
    start.setMinutes(5);
    // Set the closing hour:minutes
    end.setHours(18);
    end.setMinutes(30);

// Check the time based on milliseconds
if (
    today.getTime() >= start.getTime() &&
    today.getTime() < end.getTime()
) {
    display.innerHTML = open;
} else {
    display.innerHTML = closed;
}

Here is a working fiddle: http://jsfiddle.net/L770r2qk/
You might also want to take into account different days, such as a business that runs from late night to early morning. For that you would also want to use start.setDate(12) and end.setDate(13). You then might also want to take into account month changes where you would then use start.setMonth(10) and end.setMonth(11).
Those extra features are up to you and I will let you implement them into the example.


text:
Q: How do I drag click consistently on Zebronics Zeb transformer-M So I bought a Zebronics zeb transformer-M from here (I am still a kid, and so buying a better mouse is not an option). I am able to drag click (right)up to 10 cps, that too not very consistently, and I am unable to keep my mouse at the sane place while doing so. I want to learn how to god-bridge in minecraft. God bridging is a technique where we line up our mouse in the correct angle, and get a high cps rate, and walk backwards while drag clicking so we can bridge fast without shifting.
(drag clicking is a technique where we drag our hands across our mouse to create friction and due to the friction our hand bounces up and down clicking the mouse button rapidly for those who do not know what drag clicking is. Also I am learning it from here)
So, is it possible to do this consistently in my mouse, and if so, please give me some advice.
Thank you in advance.

A: I couldn't find the debounce time listed anywhere on the website, but if you want to try getting higher CPS while dragclicking, try using some regular tape on the mouse buttons or some Mouse Grip Tape by Razer (there's other brands too but this is generally the most popular.) It's for the Viper Mini, but most people use it on other mice just fine. If none of this works, you're better off just trying to butterfly click, it's your next best option. For your whole keeping your mouse in the same place, butterfly clicking is much more controllable, but if you want to keep your mouse in the same place for dragclicking you can try lowering your DPI and/or in-game sensitivity. If you really want to dragclick, I suggest getting another mouse all-together. I find it impressive that you've managed to get 10 CPS on this mouse, as it's only $5 USD. My personal recommendations are the Deathadder Elite for general clicking and butterflying since it has a nice big design, but the Razer Viper and Glorious Model O are great choices for general use and drag clicking. If you want a mouse that specializes in drag clicking, I've heard tons of positive reviews surrounding the Bloody A70 and Bloody A90. This video can help you pick between the two if you're interested.


text:
Q: difference between 'frustrating to me' and 'frustrating for me'
The need to check each new word in the dictionary has been quite
  frustrating to me.
The need to check each new word in the dictionary has been quite
  frustrating for me.

What's the difference in meanings?

A: You can see this example.May be find out the difference.
frustrating for me

*

*It's really frustrating for me.

*"It was frustrating for me, I can't lie," Davis said.

frustrating to me

*

*That attitude, he said, was "frustrating to me as the financial person".

*It was frustrating to me not to be able to make a difference.

A: If there is a nuanced difference, it is that to me can express an opinion

To me, it's a no-brainer: buy the car that offers the warranty.

whereas for me can express the idea of "having an effect upon me".

For me, the reorganization has been quite stressful, but some of my colleagues seem carefree.

The speaker who uses to me seems to be expressing a point-of-view, using "frustrating" indirectly as a criticism of the situation; the speaker who uses for me is speaking of the effect upon them.
But there is really no way to be sure, since these prepositions can overlap.

A: When do you say something is frustrating "to" you? when you already experienced something, right? In my opinion, "to" and "for" both sound fine.


text:
Q: How do I find the file and line number of a CrossRider error? We are using CrossRider to develop an extension for Internet Explorer. I tested our extension in debug mode on https://email14.secureserver.net/webmail.php?login=1, and I receive an error message.
Which file does this error come from? We have many files in our resources. How do I identify which file and line this error comes from?
Our Extension ID is 43889. I'm using Internet Explorer 11 but this extension should work on all versions of Internet Explorer.
Edit: I found out that the error comes from this line:
window.addEventListener("message", function(event) {}, false);

It only happens on https://email14.secureserver.net/webmail.php?login=1, not on other websites. Anyway I disabled this line in CrossRider.


text:
Q: Why does the ASP.NET Core Multi-Stage Dockerfile use 4 Stages This is the default multi-stage Dockerfile when you click on 'Add Docker Support' in Visual Studio on an ASP.NET Core site.
FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY WebApplication1.sln ./
COPY WebApplication1/WebApplication1.csproj WebApplication1/
RUN dotnet restore
COPY . .
WORKDIR /src/WebApplication1
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]

Why have they chosen to use four stages, starting and finishing with the base stage. Also, why create a publish stage using the same build base image. Why does the Dockerfile not look like this with three stages:
FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY WebApplication1.sln ./
COPY WebApplication1/WebApplication1.csproj WebApplication1/
RUN dotnet restore
COPY . .
WORKDIR /src/WebApplication1
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM microsoft/aspnetcore:2.0 AS final
WORKDIR /app
EXPOSE 80
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]

Is there some advantage to this that I am missing?

A: The file effectively equivalent to below
FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY WebApplication1.sln ./
COPY WebApplication1/WebApplication1.csproj WebApplication1/
RUN dotnet restore
COPY . .
WORKDIR /src/WebApplication1
RUN dotnet build -c Release -o /app
RUN dotnet publish -c Release -o /app

FROM microsoft/aspnetcore:2.0 AS base
EXPOSE 80
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]

Now the reason they may have chosen 4 build stage might be any of the two

*

*Presentational

*Future changes

So it may be that it depicts a
base -> build -> publish -> deploy the build

The size with 2 build stage would also the same as this one. So there is no obvious difference between the 2 stage and the 4 stage. It becomes a matter preference,  representation and all. Nothing technologically different

A: There is no programatic reason for using 4 stages.
In the first stage just configuration is changed. In the third stage the image is not changed. The only use of FROM build AS publish to have a new alias.
I think there is no use of taking care of later changes in the build structure of docker. (The 4 stage code probably does that.) Use versioned images, just like in your example. E.g. 2.0 instead of latest. This way incomatibility can be avoided. If there will be changes in the way of the build, you can catch up with it.
The docker recommendation works with no csproj name specified, as using *.csproj. That works for most of the projects, producing about 350MB image-size.


text:
Q: Ocaml pattern matching multiple elements in a list at once Lets say I have a list of type integer [1; 2; 3; 4; 5; 6; 7; 8] and I want to pattern match the first three elements at once. Is there any way to do this without nested match statements?
for example, can it be done like this?
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| [a; b; c]::rest -> (blah blah blah rest of the code here)
end

I could use the long nested method, which would be:
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| h1::t1 ->
  begin match t1 with
  | [] -> []
  | h2::t2 ->
     begin match t2 with
     | [] -> []
     | t3:: h3 ->
        (rest of the code here)
     end
  end
end

Thanks!

A: Yes, you can do that.  The syntax is like this:
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| a::b::c::rest -> (blah blah blah rest of the code here)
end

but you'll notice that this will fail if the list has fewer than three elements.  You can either add cases for single and two element lists, or just add a case that matches anything:
let rec f (x: int list) : (int list) =
  match x with
  | a::b::c::rest -> (blah blah blah rest of the code here)
  | _ -> []


text:
Q: Why does this Facebook page can't be displayed within a StageWebView? By trying to open the website https://www.facebook.com/nike within a StageWebView, I received the following error:

ReferenceError: Can't find variable: console  at
  https://fbstatic-a.akamaihd.net/rsrc.php/v2/y2/r/KK4271o6DmT.js : 95
  TypeError: Result of expression 'bigPipe' [undefined] is not an
  object.

The website stopped loading and couldn't be displayed completly.
This is the Air/AS3 code I'm using:
var webView:StageWebView = new StageWebView();
webView.stage = this.stage;
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);
webView.loadURL("https://www.facebook.com/nike")

How to get to load the website within StageWebView completely?
(Is there a way to ignore the errors?)
I'm using Flash CS6 and Adobe Air 3.9

A: I think this is a Embedded WebKit issue, you can Switch your webkit engine from Embedded to System browser engine. I tested using system browser its working fine, because it take our systems browser, you can switch your webkit engine by StageWebView( true ).
 private var webView : StageWebView;

 webView  = new StageWebView( true );
 webView.stage = this.stage;
 webView.viewPort = new Rectangle( 0, 0, 1024, 768 );


text:
Q: How do you create a physical volume? I'm having issues running pvcreate. I guess it's not recognizing my partition tables?

A: Thanks for the help. As ByteCommander has said, You must use an external drive to create a physical volume. You can not use a mounted hard drive. I set up my usb drive into my virtual machine and used gparted to make a new partition table. From there i could make the physical volume.


text:
Q: Resharper: Disable "Path not found" for friendly urls I'm using Visual Studio 2012 and I am making an ASP.NET forms project that uses friendly urls.
For example, a friendly url for the page located at "~/About.aspx" would be "~/About".
Resharper reports a "path not found" error for all links to a page that use a friendly url.  This is problematic, because the page does exist and therefore Resharper is reporting a false positive. How do I configure Resharper to know about friendly urls and thereby not report the issue when the mapped page exists?


text:
Q: (Lua 5.1) '=' expected near 'outer' | trying to execute a Lua script I am trying to get this code to work, but I don't understand why. It says that it wants an "=" to make 'goto' a variable, but it should be running a function. I am running Lua 5.1.
ftm2mid.lua:209: '=' expected near 'outer'
    local mstr = rv.frame .. ":" .. rv.row
    if loop[mstr] == setting.loops then break end

    for _, v in pairs(rv.lastFX) do
      if v.name == FX.HALT then
        goto outer   -- <--- Here it is
      elseif v.name == FX.SPEED then
        if v.param >= ftm.param.FxxSplit then
          if cTempo ~= v.param then newTempo = true end
          cTempo = v.param
        else...

A: You're trying to run a script designed for Lua 5.2 or newer on Lua 5.1 or older, which doesn't work. The clue is that line 209 is goto outer, and goto is new to Lua 5.2.


text:
Q: Why did the ships fall into orbit? When the first Star Destroyer is disabled it just angles down slightly but doesn't fall into orbit or crash. However when they both crash into each other they both start falling into orbit and crash into the ring.
Why is this?

A: It's known that Star Destroyers can hover in atmosphere, but that it takes an astonishing amount of power for them to do so (presumably to counteract the gravitational force between the planet and the ship).
The novelization describes the collision between the Star Destroyer and the Lightmaker (Hammerhead corvette) in terms reminiscent of momentum interactions:

Raddus watched the Lightmaker descend like a spear into the mass of the disabled behemoth. Metal sheared and crumpled, and Raddus feared for a moment that Oquoné's velocity had been too great — that the Lightmaker would be dashed to nothingness and the most delicate part of the plan, still to come, had failed. Yet the Destroyer absorbed the impact and began to tumble away, its frame marred but intact.
Rogue One: A Star Wars Story - Official Novelization Chapter 20

Presumably the momentum transfer of the Lightmaker was enough to push the Star Destroyer past a point where its engines could provide enough power to keep it aloft.

A: Knowing the orbital parameters of Scarif is impossible. If it had similar density, rotation rate, and size to earth a synchronous orbit would be impossible at that altitude and the ships indeed would need huge amounts of power to maintain their position, but there is no reason to believe any of these things are the same or even similar.
To push something out of orbit that fast would require a huge amount of force (in Earth Human terms), and as you should know F = MA, so we would need to know the acceleration provided by the engines on the hammerhead, and the mass of the combined system. Both are probably very difficult to find canon sources for.


text:
Q: Is there a name for the concept of adding "wind" to a metric space? Let say we have a metric space $(M,d)$ (in particular, we will require it to be a length metric space). If an airplane in that space that moves at speed of 1, then it can get from point $a$ to point $b$ in $d(a,b)$ time.
Now let us suppose we add wind to this space. By wind, I mean we assign to each point $x$ a vector $w(x)$.
When the airplane is at point $a$ moving in direction $v$ (which is a unit vector), it "moves" according to $v + w(a)$. In affect, the wind is blowing against it.
We know define a quasimetric (M, d') as follows. $d'(a,b)$ is defined as the shortest possible amount of time it would take the airplane to get from point $a$ to point $b$ (or $\infty$ if the airplane can't get to $a$ from $b$).
Is there a name for this concept of turning a metric into a quasimetric by adding "wind" to the space?
Examples:

*

*If we define $w(x)=\vec 0$ for all $x$, then $(M,d) = (M,d')$.

*If we take a circle, and define $w(x)$ as a unit vector going clockwise, we get the quasimetric defined in the first paragraph in this answer (except the distances are halved).

A: This sort of thing is modelled using Finsler metrics.
If you like wind, then Zermelo navigation metrics is what you want.

A: If you deal with a riemannian manifold, let $g_p $ be the inner product in $T_pM$ (a positive definite matrix whose entries vary smoothly) . Given a scalar smooth function $w(p) > 0$, consider the new inner product $h_p= w(p) g_p$ (you multiply the entire matrix by a number).
Recall that the length of a path $\gamma: (-1,1) \to M$ is
$$\int_{-1}^{1} \gamma'(t) ^T g_{\gamma(t)} \gamma'(t) dt $$
With the modified version of metrics, you have an extra factor $w(\gamma(t)) $. If you started with an airplane having velocity 1 in the old metrics, you have $\gamma'(t) ^T g_{\gamma(t)} \gamma'(t)=1$; so with the extra factor you get that the new distance is $\int w(\gamma(t)) dt $.This means that in points with "high" wind you will have high $w(p) $ (which in some sense measure how much it is difficult to go over a point).
This is not exactly what you wanted because this change is linear, but it can be a good approximation when the wind is little and it can be assumed to be proportional to the velocity.


text:
Q: How can I get webpack to shut up about "Critical dependency: require function is used in a way..."? Getting rid of this warning is my immediate desire. Perhaps, however, what is needed is an entirely different strategy altogether.
I've created an npm library for various date/time functions. Nearly all of the code is general-purpose code that works for Node.js or a web browser. There's one feature, however, that requires some optional, platform-specific code: polling a remote URL for timezone updates. (The rules for when Daylight Saving Time begins and ends are constantly in flux around the world).
With a bit of ugly hacking I can make my code compile for both web and for Node, but there's still a webpack warning:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Different variations I've tried simply result in different warnings related to require, or the code being required.
I can suppress the warnings using FilterWarningsPlugin, but that only suppresses the warnings for me when I build my npm package. Any consumer of my package will still get this warning. If they suppress the warning using FilterWarningsPlugin, then any consumer of their code could still get the warning, etc.
Here's what I've got now:
import { IZonePoller } from './i-zone-poller';

// The following crazy mess allows @tubular/time to be compiled for Node.js or for browsers
// without pulling in Node.js dependencies.
//
// eslint-disable-next-line no-new-func
const requestText: (url: string) => Promise<any> = new Function('require', `
  try {
    return require('by-request').requestText;
  }
  catch {
    return null;
  }
`)(require);

export const zonePollerNode: IZonePoller = {
  async getTimezones(url: string): Promise<{ [p: string]: string }> {
    if (!requestText) {
      const msg = 'npm package "by-request" should be installed to use zonePollerNode';
      console.error(msg);
      throw new Error(msg);
    }

    const zones = (await requestText(url)).replace(/^.*?=\s*/, '');

    return JSON.parse(zones);
  }
};

I've tried (and failed) to find some sneaky way to refer to require that webpack will ignore. webpack's "magic comments" don't appear to offer anything that will help.
One possible solution is to make an entirely separate npm package out of this one little bit of functionality, but that seems like overkill, and an awful reason to create a separate package.
Any brilliant ideas out there? Is there a platform-neutral technique, that won't cause browser CORS issues, to fetch web resources that I could use for Node and browsers?

A: This approach using dynamic import finally worked for me:
import { IZonePoller } from './i-zone-poller';

let requestText: (url: string) => Promise<string>;

export const zonePollerNode: IZonePoller = {
  async getTimezones(url: string): Promise<{ [p: string]: string }> {
    if (!requestText) {
      try {
        // @ts-ignore
        requestText = (await import(/* webpackIgnore: true */ 'by-request')).requestText;
      }
      catch {}
    }

    if (!requestText) {
      const msg = 'npm package "by-request" should be installed to use zonePollerNode';
      console.error(msg);
      throw new Error(msg);
    }

    const zones = (await requestText(url)).replace(/^.*?=\s*/, '');

    return JSON.parse(zones);
  }
};

I didn't think this would work because the very first time I typed in import(... my editor quickly place a squiggly red line below the import, with this error message:

TS1323: Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'.

I wanted to leave the module format at ES2015, so this didn't seem like an option. And I didn't think import() was going to work when compiled for a browser target either.
But, lo and behold, simply ignoring the error with // @ts-ignore miraculously worked, along with the webpack "magic comment", to solve all of my compilation and warning-suppression desires.


text:
Q: how to create a xsd schema for this xml? how can i create a xsd schema for this xml file?
Trying to create a ssis package to import multiple xml and i don't know to create the xsd schema.
<?xml version="1.0"?>
-<recordedData>
    <machine>ZSK40-2</machine>
    <date>2013/09/21</date>
    <hour>05:32</hour>-<CollectedData>-<variable>
            <Name>PRODUCT</Name>
            <Value>FILLER 580</Value>
        </variable>-<variable>
            <Name>LOT_NUMBER</Name>
            <Value>CG 00063 0</Value>
        </variable>-<variable>
            <Name>SHIFT_SUPERVISOR</Name>
            <Value>  covaliu l</Value>
        </variable>-<variable>
            <Name>KGH_ALL_SET</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>KGH_ALL_REAL</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>KGH_F1_SET</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>KGH_F1_REAL</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>K_F1</Name>
            <Value>43</Value>
        </variable>-<variable>
            <Name>SCREW_RPM_SET</Name>
            <Value>550</Value>
        </variable>-<variable>
            <Name>SCREW_RPM_REAL</Name>
            <Value>550.085388183594</Value>
        </variable>-<variable>
            <Name>TORQUE</Name>
            <Value>1.21340000629425</Value>
        </variable>-<variable>
            <Name>CURRENT</Name>
            <Value>60.1959991455078</Value>
        </variable>-<variable>
            <Name>KW_KG</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>KW</Name>
            <Value>-0.990000009536743</Value>
        </variable>-<variable>
            <Name>MELT_PRESSURE</Name>
            <Value>0</Value>
        </variable>-<variable>
            <Name>MELT_TEMPERATURE</Name>
            <Value>214</Value>
        </variable>-<variable>
            <Name>PV1</Name>
            <Value>216</Value>
        </variable>-<variable>
            <Name>SP1</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV2</Name>
            <Value>239</Value>
        </variable>-<variable>
            <Name>SP2</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>PV3</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>SP3</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>PV4</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>SP4</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>PV5</Name>
            <Value>209</Value>
        </variable>-<variable>
            <Name>SP5</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV6</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>SP6</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV7</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>SP7</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV8</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>SP8</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV9</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>SP9</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV10</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>SP10</Name>
            <Value>210</Value>
        </variable>-<variable>
            <Name>PV11</Name>
            <Value>220</Value>
        </variable>-<variable>
            <Name>SP11</Name>
            <Value>220</Value>
        </variable>
    </CollectedData>
</recordedData>

At least something to get me started with, as i am in a situation where the time presses me.

A: Microsoft XSD Inference tool.
Check that:
http://msdn.microsoft.com/en-us/library/x6c1kb0s%28VS.80%29.aspx
Download the tool, put the sample XML in a file, and then run the tool from the command line passing the complete path of your XML file.
Like >>xsd c:\test.xml
You will notice that a file named test.xsd is created on the C drive.
Note: don't forget to remove the "-" character from your input xml file

A: You can do it online easily : Convert XML to XSD online
Here is the XSD for the XML that you have mentioned :
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="recordedData">
 <xs:complexType mixed="true">
  <xs:sequence>
    <xs:element type="xs:string" name="machine"/>
    <xs:element type="xs:string" name="date"/>
    <xs:element type="xs:string" name="hour"/>
    <xs:element name="CollectedData">
      <xs:complexType mixed="true">
        <xs:sequence>
          <xs:element name="variable" maxOccurs="unbounded" minOccurs="0">
            <xs:complexType>
              <xs:sequence>
                <xs:element type="xs:string" name="Name"/>
                <xs:element type="xs:string" name="Value"/>
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

A: There is a build in generator in the XML source editor. It doesnt work all the time, but you should give it a try.


text:
Q: Use of 'wd=' in beanplot{beanplot} to dynamically change the width of the beans I am using the beanplot function of the beanplot package, and I cannot figure out a way to use the wd= parameter with a good result.
What I want

*

*display beanplots whose width depends on the size of the sample.

*(and now) understand what is the use of 'wd=' and how to use it.

So far, when I try to use the wd parameter, as a list it gives me an error, as a vector, it gives me something weird (wd seems to be multiplied to the density estimates values)
Example
library(beanplot)
set.seed(2000)
Test <- data.frame(
  x=rnorm(30),
  f1 = factor(c(rep('A', 10), rep('B',20))),
  f2=factor(c('M','F'))
  )

beanplot(x~f1,Test,
         col=list('orange','yellow'),
         wd=c(1:2/2),
         boxwex = 1
)

A: Okay, after a bit of personal trial/error, I got my two answers:
First, after looking into the code, wd is not supposed to be used that way, and does not support to have several values (unlike 'col='). It seems that 'wd=' is not meant to be used directly for specifying the beanplot width in a normal use. Indeed, when no 'wd' (or wd=NA) is provided, wd is computed from 'maxwidth=', but normalized to the highest value of all the density functions. Hence it seems more appropriate to specify 'maxwidth=' if one wants to control the width of the beans.
Second, I wrote some code to actually achieve what I want. It may be messy, please fell free to enhance it. This example can be used for any variation of parameter that is not supported by the function beanplot natively.
You will notice that the code shows an example of why 'wd=' is still important, since we want all the width values of the bean to be normalized one time, for all the density plots.
col_list = list('orange','yellow')
wd_fac = aggregate(x~f1,Test,length)$x # get the size relative to the number of points in each bean
wd_fac <- wd_fac/max(wd_fac)

par(mfrow=c(1,2))
## Normal plot
beanplot(x~f1,Test, col=col_list)
## Our plot
bp <- beanplot(x~f1,Test,what=c(T,F,F,F)) # plots the line and frames + get the general parmeters
sapply(1:length(levels(Test$f1)),
       function(X){
         beanplot(subset(Test, f1 == levels(f1)[X])$x,
                  col=col_list[X],
                  bw = bp$bw, # we may want to keep the bandwidth
                  wd= bp$wd*wd_fac[X],
                  at=X,
                  what=!c(T,F,F,F),
                  add = T)}
)


text:
Q: PHP: Could not connect to host. Howto add external certificate to trusted using OpenSSL? My college downloaded cert-name.crt file from external host. Now we need to connect to web service platform, obviously using their SSL certificate. We are a bit confused by OpenSSL documentation. Research didn't help either. All we get is 'Could not connect to host' PHP exception. Just to clear things, interface worked perfectly fine over unsecured HTTP. We use pure Soap library. As an act of desperation we also tried to connect with host without verification by disabling verify_peer variable in SoapClient stream context. Please help, we are under pressure.

A: To get your started:
By default, PHP looks for the CA file on UNIX systems in, make sure it is readable by the PHP invoker (user via cli, Apache user, etc..), and place the .crt file here:
/etc/pki/CA