text:
Q: PHP scraping table I've been on a mission to learn how to use PHP and scrape data, create a database etc.
I've been trying to scrape data from http://www.basketball-reference.com/leagues/NBA_2015.html#all_team_stats
So far I've managed to scrape just that whole section by doing this:
<?php
$ch = curl_init("http://www.basketball-reference.com/leagues/NBA_2015.html#all_team_stats");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$cl = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($cl);
$table = $dom->getElementById("all_team_stats");
echo "<pre>";
print_r($table);
?>

I'm kind of lost on how to go about scraping the individual values. I'm guessing I have to run a loop for the <TD> tags or something?

A: $rows = $table->getElementsByTagName('tr');
for($i=0; $i<$rows->length; $i++){
    $cols = $rows->item($i)->getElementsByTagName('td');
    for($j=0; $j<$cols->length; $j++){
        print($cols->item($j)->textContent);
    }
}


text:
Q: DecisionTreeRegressor isnt using my x variable? I'm using the pandas library and using sklearn for the DecisionTreeRegressor, I imported a CSV file that I'm using and it has data on different bikes, the columns that I need are model_year,kms_driven, owner(which is the number of owners), price,and power.
while fiting the DecisionTreeRegressor() to the CSV and trying to make it predict the price of a bike model_year=2015, kms driven 30000 and 1 owner it gives me the error
/usr/local/lib/python3.7/dist-packages/sklearn/base.py:451: UserWarning: X does not have valid feature names, but DecisionTreeRegressor was fitted with feature names
  "X does not have valid feature names, but"

here is my code
# import libraries
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
# read the data file and create two data arrays

# cleaned dataset without hp (horsepower)
df1 = pd.read_csv("/content/KMS_bikes_cleaned.csv")

# cleaned dataset without kms (kilometers driven)
df2 = pd.read_csv("/content/POWER_bikes_cleaned.csv")

# print the df1 and df2 data arrays
print(df1)
print(df1)

output:
 model_year  kms_driven  owner   price
0           1970        5000      3  190000
1           1986        8990      2  100000
2           1986       50000      3  110000
3           1990       32000      2   63750
4           1990       13031      3  100000
...          ...         ...    ...     ...
5598        2021        2700      1  155600
5599        2021        3000      1  160000
5600        2021         850      2   70000
5601        2021         100      1  300000
5602        2021        7200      1  195400

[5603 rows x 4 columns]
      model_year  kms_driven  owner   price
0           1970        5000      3  190000
1           1986        8990      2  100000
2           1986       50000      3  110000
3           1990       32000      2   63750
4           1990       13031      3  100000
...          ...         ...    ...     ...
5598        2021        2700      1  155600
5599        2021        3000      1  160000
5600        2021         850      2   70000
5601        2021         100      1  300000
5602        2021        7200      1  195400

# select predictors
X1 = df1.drop(columns='price')
Y1 = df1 ['price']
# print the X1 and Y2 variables
print(X1)
print(Y1)

output:
 model_year  kms_driven  owner
0           1970        5000      3
1           1986        8990      2
2           1986       50000      3
3           1990       32000      2
4           1990       13031      3
...          ...         ...    ...
5598        2021        2700      1
5599        2021        3000      1
5600        2021         850      2
5601        2021         100      1
5602        2021        7200      1

[5603 rows x 3 columns]
0       190000
1       100000
2       110000
3        63750
4       100000
         ...
5598    155600
5599    160000
5600     70000
5601    300000
5602    195400
Name: price, Length: 5603, dtype: int64

# name model
model1 = DecisionTreeRegressor()
# fit the model into all of the data
model1.fit (X1,Y1)
# predicted price of a 2015 bike driven 30,000 km sold by its first owner
predict1 = model1.predict ([[2015, 30000, 1]])
#print predict1
print(predict1)

# select predictors
X2 = df2.drop(columns="price")
Y2 = df2["price"]
# print the X and Y variables
print(X2)
print(Y2)

model_year  owner  power
0           1970      3  19.80
1           1986      2  19.80
2           1986      3  19.80
3           1990      2  11.00
4           1990      3  19.80
...          ...    ...    ...
5598        2021      1  14.30
5599        2021      1  14.50
5600        2021      2  10.72
5601        2021      1  30.00
5602        2021      1  19.10

[5603 rows x 3 columns]
0       190000
1       100000
2       110000
3        63750
4       100000
         ...
5598    155600
5599    160000
5600     70000
5601    300000
5602    195400
Name: price, Length: 5603, dtype: int64

# name model
model2 = DecisionTreeRegressor()
# fit the model into all of the data
model2.fit (X2,Y2)
# predicted price of a 2018 bike with 50 bph sold by its second owner
output2 = model2.predict ([[2018, 2, 50.0]])
#print output2
print(output2)

output:
/usr/local/lib/python3.7/dist-packages/sklearn/base.py:451: UserWarning: X does not have valid feature names, but DecisionTreeRegressor was fitted with feature names
  "X does not have valid feature names, but"

A: To customize my answer to the proposed duplicate: pass the new data to predict on as a dataframe:
test1 = pd.Dataframe({
    "model_year": 2015,
    "kms_driven": 30000,
    "owner": 1,
})

A: I could not reproduce the warning message, but I found a similar question here: SKLearn warning "valid feature names" in version 1.0
It seems like this problem is specific to version 1.0. (I'm still using 0.24.2).
If you pass the values of the dataframe, there should be no more warnings.
model2.fit(X2.values, Y2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding date and time of Digital Elevation Model I downloaded a DEM from the Copernicus site.
I can provide the link: https://land.copernicus.eu/imagery-in-situ/eu-dem/eu-dem-v1-0-and-derived-products/eu-dem-v1.0?tab=download
I would like to find the date of my DEM, so as to compute sun elevation and azimuth..
Do you have any suggestions on how to do that?
I tried to find a metadata file.
I was trying to find out an xml file or a text file, but when i found it, it doesn't include the specific information.

A: Looking over the link, the data you are accessing is a culmination of various data sources to create a seamless grid of elevation data.
The "metadata" for the dataset:
https://land.copernicus.eu/imagery-in-situ/eu-dem/eu-dem-v1-0-and-derived-products/eu-dem-v1.0?tab=metadata
states:

The EU-DEM v1.0 is derived from an automated data fusion process using
  SRTM and ASTER GDEM digital surface model (DSM) data. Intermap's
  NEXTMap Europe dataset is utilized to remove any consistent horizontal
  bias in the GDEM data. The EU-DEM v1.0 is edited to ensure that water
  features are adequately represented and consistent with the
  hydrography layer. Residual clouds within the GDEM data are identified
  and removed same as suspect data extremely differing from the SRTM
  data.

There are a few lines that explain that this dataset is derived from both SRTM and ASTER datasets with some intervention to fix clouds, water features and horizontal bias.
Even though the data was published in April 2016, the metadata states that the datasets used are from around the year 2000...so would be a mix of images acquired over that year.
Therefore to answer your question, I don't think it is possible to extract a date and time for a given area.

A: A digital elevation model is not representing an optical property of the earth's surface, such as its reflectivity at certain wavelengths, nor is it influenced by the phenomena of refraction or diffusion that occur in the atmosphere.
Instead, it represents the elevation of the topographic surface with respect to a reference surface.
Although the model can be considered to represent these elevations at a given time, it is generally not a kind of instantaneous shot but rather the result of several measurements, even by different methods, at different dates and at different times.
Therefore, as reported by the site that provides the information, the information provided may be considered valid during the course of the year 2000.
Now, it is usual, that for illustrative purposes, we represent the shadows that this elevation model would produce on the surface at a particular time. We call the result of that representation: "hillshade".
If what you need is the apparent position of the sun in the celestial sphere, for a day, at a time and for a particular earth position, there are ways to find out. If you only want to make a shading for illustrative purposes, you could experience the parameters that make your representation produce the meaning you are looking to communicate.


text:
Q: Finding a generalized form for taking the n$^{th}$ derivative of a falling factorial I would like to make
$$
\frac{d^n}{dx^n}[(x)_c] = n! \times e_{c-n}(x,x-1,\cdots,x-c+1)
$$
Where $e_{c-n}(x,x-1,x-2,\cdots,x-c+1)$ is the elementary symmetric polynomial function
But lets say that i have
$$
\sum_{k=0}^{n-c}f(k) \frac{d^k}{dx^k}[(x)_c]
$$
If $k>c$ then the derivative is zero, But if i replace $\frac{d^k}{dx^k}[(x)_c]$with $k!\times e_{c-k}(x,x-1,\cdots,x-c+1)$ then i get
$$
\sum_{k=0}^{n-c}k!f(k) e_{c-k}(x,x-1,\cdots,x-c+1)
$$
If $k>c$ then would $e_{c-k}(x,x-1,\cdots,x-c+1)=0$? If not how can i fix this problem?


text:
Q: How can I get the same CTRL+W behaviour from Sublime Text In the past, ctrl+w used to close a single tab in Sublime Text (3), and if there were no tabs left open, it would close the text editor. How can I achieve the same behaviour in the updated Sublime Text? ST 4
EDIT: The setting I was looking for is "close_windows_when_empty": true

A: Sublime Text 4 behaves for me as described - it closes all open files and when no files are open, it closes the editor.
However, you may have had your key bindings changed by a plugin/misconfiguration etc.
Preferences > Key Bindings will open up a file.
Ensure that for ctrl+w, the command is set to close not close_file.
Once changed, restart Sublime.
It should look like below:
...
{ "keys": ["ctrl+w"], "command": "close" },
...

A: Really strange, for me this settings wasn't working:
"close_windows_when_empty": true

tried and tested everything else, finally I've completely uninstalled Sublime 4 and reinstalled it (using AppCleaner, deleted all configs etc).
Now:
"close_windows_when_empty": false

is really set to false, BUT the last window is always closing "everything". exacty what I wanted. It works even the settings tells something else.
So: Reinstall possibly helps


text:
Q: When running hadoop example, I encountered ".staging/job_1541144755485_0002/job.splitmetainfo does not exist", what can I do? My configuration is below:
I used two machines for the Hadoop experiment, the pc720 (10.10.1.1) and the pc719 (10.10.1.2) respectively.
jdk(version 1.8.0_181) is installed by apt-get. Hadoop2.7.1 is download from https://archive.apache.org/dist/hadoop/common/hadoop-2.7.1/, and put in /opt/
Step1:
I configured the /etc/bash.bashrc, adding
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export PATH=${JAVA_HOME}/bin:${PATH}
export HADOOP_HOME=/opt/hadoop-2.7.1
export PATH=${HADOOP_HOME}/bin:${PATH}
export PATH=${HADOOP_HOME}/sbin:${PATH}

and then run "source /etc/profile"
Step2:
I configure the xmls:
Slaves:
10.10.1.2

Core-site.xml
<property>
        <name>fs.defautFS</name>
        <value>hdfs://10.10.1.1:9000</value>
</property>

<property>
        <name>io.file.buffer.size</name>
        <value>131072</value>
</property>
<property>
        <name>hadoop.tmp.dir</name>
        <value>file:/root/hadoop_store/tmp</value>
</property>

Hdfs-site.xml
<property>
    <name>dfs:replication</name>
    <value>2</value>
</property>

<property>
        <name>dfs.namenode.name.dir</name>
        <value>file:/root/hadoop_store/hdfs/namenode</value>
</property>

<property>
        <name>dfs.datanode.data.dir</name>
        <value>file:/root/hadoop_store/hdfs/datanode</value>
</property>
<property>
    <name>dfs.namenode.secondary.http-address</name>
    <value>10.10.1.1:9001</value>
</property>

<property>
        <name>dfs.namenode.rpc-address</name>
        <value>10.10.1.1:8080</value>
</property>
<property>
        <name>dfs.webhdfs.enabled</name>
        <value>true</value>
</property>

Mapred-site.xml
<property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
</property>

<property>
        <name>mapreduce.jobtracker.address</name>
        <value>10.10.1.1:9002</value>
</property>

<property>
        <name>mapreduce.jobhistory.address</name>
        <value>10.10.1.1:10020</value>
</property>

<property>
        <name>mapreduce.jobhistory.webapp.address</name>
        <value>10.10.1.1:19888</value>
</property>

<property>
        <name>mapred.acls.enabled</name>
        <value>true</value>
</property>

Yarn-site.xml
<property>
        <name>yarn.nodemanager.aux-services</name>
        <value>mapreduce_shuffle</value>
</property>

<property>
        <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
        <value>org.apache.hadoop.mapred.ShuffleHandler</value>
</property>

<property>
        <name>yarn.resourcemanager.hostname</name>
        <value>10.10.1.1</value>
</property>

<property>
        <name>yarn.resourcemanager.address</name>
        <value>${yarn.resourcemanager.hostname}:8032</value>
</property>

<property>
        <name>yarn.resourcemanager.scheduler.address</name>
        <value>${yarn.resourcemanager.hostname}:8030</value>
</property>

<property>
        <name>yarn.resourcemanager.webapp.address</name>
        <value>${yarn.resourcemanager.hostname}:8088</value>
</property>

<property>
        <name>yarn.resourcemanager.webapp.https.address</name>
        <value>${yarn.resourcemanager.hostname}:8090</value>
</property>

<property>
        <name>yarn.resourcemanager.resource-tracker.address</name>
        <value>${yarn.resourcemanager.hostname}:8031</value>
</property>

<property>
        <name>yarn.resourcemanager.admin.address</name>
        <value>${yarn.resourcemanager.hostname}:8033</value>
</property>

<property>
        <name>yarn.scheduler.maximum-allocation-mb</name>
        <value>8182</value>
</property>

<property>
        <name>yarn.nodemanager.vmem-pmem-ratio</name>
        <value>2.1</value>
</property>
<property>
        <name>yarn.nodemanager.resource.memory-mb</name>
        <value>2048</value>
</property>

<property>
        <name>yarn.nodemanager.vmem-check-enabled</name>
        <value>false</value>
</property>

Step3:
In /root/, established several directories:
mkdir hadoop_store
mkdir hadoop_store/hdfs
mkdir hadoop_store/tmp
mkdir hadoop_store/hdfs/datanode
mkdir hadoop_store/hdfs/namenode

Then I turned into /opt/Hadoop-2.7.1/bin, run
./hdfs namenode –format
cd ..
cd sbin/
./start-all.sh
./mr-jobhistory-daemon.sh start historyserver

After run jps, pc720 shows

pc719 shows

Reaching here, I think my hadoop2.7.1 was successfully installed and configured. But the problems came.
I turned in /opt/hadoop-2.7.1/share/hadoop/mapreduce/ which shows

Then I ran hadoop jar hadoop-mapreduce-examples-2.7.1.jar pi 2 2
The logs are below
Number of Maps  = 2
Samples per Map = 2
Wrote input for Map #0
Wrote input for Map #1
Starting Job
18/11/02 08:14:48 INFO client.RMProxy: Connecting to ResourceManager at /10.10.1.1:8032
18/11/02 08:14:48 INFO input.FileInputFormat: Total input paths to process : 2
18/11/02 08:14:48 INFO mapreduce.JobSubmitter: number of splits:2
18/11/02 08:14:48 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1541144755485_0002
18/11/02 08:14:49 INFO impl.YarnClientImpl: Submitted application application_1541144755485_0002
18/11/02 08:14:49 INFO mapreduce.Job: The url to track the job: http://node-0-link-0:8088/proxy/application_1541144755485_0002/
18/11/02 08:14:49 INFO mapreduce.Job: Running job: job_1541144755485_0002
18/11/02 08:14:53 INFO mapreduce.Job: Job job_1541144755485_0002 running in uber mode : false
18/11/02 08:14:53 INFO mapreduce.Job:  map 0% reduce 0%
18/11/02 08:14:53 INFO mapreduce.Job: Job job_1541144755485_0002 failed with state FAILED due to: Application application_1541144755485_0002 failed 2 times due to AM Container for appattempt_1541144755485_0002_000002 exited with  exitCode: -1000
For more detailed output, check application tracking page:http://node-0-link-0:8088/cluster/app/application_1541144755485_0002Then, click on links to logs of each attempt.
Diagnostics: File file:/tmp/hadoop-yarn/staging/root/.staging/job_1541144755485_0002/job.splitmetainfo does not exist
java.io.FileNotFoundException: File file:/tmp/hadoop-yarn/staging/root/.staging/job_1541144755485_0002/job.splitmetainfo does not exist
    at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:606)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:819)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:596)
    at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:421)
    at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:253)
    at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:63)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:361)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:358)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:62)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Failing this attempt. Failing the application.
18/11/02 08:14:53 INFO mapreduce.Job: Counters: 0
Job Finished in 5.08 seconds
java.io.FileNotFoundException: File file:/opt/hadoop-2.7.1/share/hadoop/mapreduce/QuasiMonteCarlo_1541168087724_1532373667/out/reduce-out does not exist
    at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:606)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:819)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:596)
    at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:421)
    at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1752)
    at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1776)
    at org.apache.hadoop.examples.QuasiMonteCarlo.estimatePi(QuasiMonteCarlo.java:314)
    at org.apache.hadoop.examples.QuasiMonteCarlo.run(QuasiMonteCarlo.java:354)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.examples.QuasiMonteCarlo.main(QuasiMonteCarlo.java:363)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
    at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
    at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

I have tried many solutions, but seemed useless. This problem has confused me for about 1 week. Are there any mistakes in my configuration? What can I do? Please help me.
Thanks!

A: I believe that you missed a / a the end offs.defaultFS value would be         <value>hdfs://10.10.1.1:9000/</value>
Note that /tmp/hadoop-yarn/staging/root/.staging/job_1541144755485_0002/job.splitmetainfo  is configured by yarn.app.mapreduce.am.staging-dir which is normally held in HDFS. This gives us a hint that is a HDFS problem.
SOURCE: https://www.cloudera.com/documentation/enterprise/5-15-x/topics/cdh_ig_hdfs_cluster_deploy.html

A: By running hadoop dfs -ls /tmp, it shows
Found 17 items
drwxrwxrwt   - root root       4096 2018-11-01 22:33 /tmp/.ICE-unix
drwxrwxrwt   - root root       4096 2018-11-01 22:33 /tmp/.Test-unix
drwxrwxrwt   - root root       4096 2018-11-01 22:33 /tmp/.X11-unix
drwxrwxrwt   - root root       4096 2018-11-01 22:33 /tmp/.XIM-unix
drwxrwxrwt   - root root       4096 2018-11-01 22:33 /tmp/.font-unix
drwxr-xr-x   - root root       4096 2018-11-04 23:45 /tmp/Jetty_0_0_0_0_50070_hdfs____w2cu08
drwxr-xr-x   - root root       4096 2018-11-04 23:45 /tmp/Jetty_10_10_1_1_8088_cluster____.kglkoh
drwxr-xr-x   - root root       4096 2018-11-04 23:46 /tmp/Jetty_node.0.link.0_19888_jobhistory____.ckp60y
drwxr-xr-x   - root root       4096 2018-11-04 23:45 /tmp/Jetty_node.0.link.0_9001_secondary____.h648yx
drwxr-xr-x   - root root       4096 2018-11-02 01:13 /tmp/hadoop-root
-rw-r--r--   1 root root          6 2018-11-04 23:45 /tmp/hadoop-root-namenode.pid
-rw-r--r--   1 root root          6 2018-11-04 23:45 /tmp/hadoop-root-secondarynamenode.pid
drwxr-xr-x   - root root       4096 2018-11-02 01:14 /tmp/hadoop-yarn
drwxr-xr-x   - root root       4096 2018-11-05 00:02 /tmp/hsperfdata_root
-rw-r--r--   1 root root          6 2018-11-04 23:46 /tmp/mapred-root-historyserver.pid
-rw-r--r--   1 root root        388 2018-11-01 22:33 /tmp/ntp.conf.new
-rw-r--r--   1 root root          6


text:
Q: How to delete duplicated rows with the same day? My table looks like:
id      name        value       date
1       John        25      2013-03-23 16:42:35
2       John        25      2013-03-23 13:52:24
3       John        26      2013-03-22 03:12:43
4       Gabriel     18      2013-03-23 10:21:07
5       Rick        32      2013-03-21 04:37:29

How to remove the rows with the same name and the timestamp date with the same day? For example, the table above should be:
id      name        value       date
1       John        25      2013-03-23 16:42:35
3       John        26      2013-03-22 03:12:43
4       Gabriel     18      2013-03-23 10:21:07
5       Rick        32      2013-03-21 04:37:29

A: There are many ways to do it. One is by using a subquery which gets one record of name in each day and the result of the subquery is then joined back on the table. The non matching rows will then be filtered and deleted.
DELETE  a
FROM    tableName a
        LEFT JOIN
        (
            SELECT  name, date(date) dateOnly, MIN(ID) min_ID
            FROM    tableName
            GROUP   BY name, date(date)
        ) b ON  a.name = b.name AND
                Date(a.date) = b.dateonly AND
                a.ID = b.min_ID
WHERE   b.name IS NULL

*

*SQLFiddle Demo


text:
Q: Predicting a ratio, max values known. Should they be inputs? I am trying to predict the ratio between variables $a$ and $b$. I know the max values $a$ and $b$ can take and qualitatively the ratio "should" either be close to $\frac{\max(a)}{\max(b)}$ or to $1$ (and it drops to $1$ as total load $a+b$ decreases).
I do not know the value for either $a$ or $b$, those are outputs of the calculation. I do know $a+b$. In total I have nine input variables and about 200 data points. I want to avoid overfitting as much as possible, but I have to hit the target to less than 1% or the model will be scrapped.
I am considering using a neural net, or possibly (simpler) a linear regression with higher order terms of the inputs. My question is, is there any way to get more information out of the max values then simply using them for inputs? Any suggestions as to a model that leverages those knowns is also appreciated.
The problem comes from engineering, basically we are doing load balancing between two machines. Both machines will run near their maximum capacity until the load drops and they should share more equally.


text:
Q: Rotating image on canvas around the center of the image I'm want to animate a rotation of my image. Now my image is rotating, but around one point. I want to make animation without moving my image(around the center of the image). I hope you know what I mean. Here is the part of my code:
ctx.save();
        ctx.translate(player.x+step, player.y+step);
        ctx.rotate(Math.radians(this.step%360));
        ctx.translate(-(player.x+step), -(player.y+step));

        ctx.drawImage(
            skeletonImage, 60, 65,
            this.width, this.height,
            this.x, this.y,
            this.width, this.height);

        ctx.restore();

Where step is increased in each frame.

A: You can translate the canvas to the location you wish to draw at, rotate the canvas on this point, then draw the image with the following call:
ctx.drawImage(
  img,
  img.width / -2,   // x
  img.height / -2,  // y
  img.width,
  img.height
);

Moving the x and y away from the center by half the width and height respectively places the center of the image (width / 2, height / 2) at 0, 0 on the canvas (the rotation point).
Here's a minimal, complete example:

const degToRad = deg => deg * Math.PI / 180;
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = canvas.height = 180;
const ctx = canvas.getContext("2d");
const player = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  angle: 0,
  img: new Image()
};
player.img.onload = function () {
  (function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(player.x, player.x);
    ctx.rotate(degToRad(player.angle++ % 360));
    ctx.drawImage(
      player.img,
      player.img.width / -2,
      player.img.height / -2,
      player.img.width,
      player.img.height
    );
    ctx.restore();
    requestAnimationFrame(update);
  })();
};
player.img.src = "http://placekitten.com/100/100";

While I'm not sure what the specifics are for your game, I'd keep step out of the rendering calculation. Use it purely to update the position, then render only when all new positions for entities have been calculated. Keep step sizes, velocities, etc, out of the rendering stage.


text:
Q: How to use typedef in ctypes I am trying to wrap a C library in Python using ctypes library.
I wrap structs this way
file.c
typedef struct {
    int x;
    int y;
} Point;

file.py
import ctypes

class Point(ctypes.Structure):
    _fields_ = [("x": ctypes.c_int), ("y", ctypes.c_int)]

But I have a statement like this and cannot find out how to wrap it and get the type MyFucntion.
typedef char* (*MyFunction)(char*);

A: Check [Python 3.Docs]: ctypes - A foreign function library for Python.
That's a function pointer. You can wrap it like this:
FuncPtr = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_char))

But it very much depends on how are you going to make use of it.
As a side note, typedef doesn't have anything to do with ctypes: for example Point definition would be the same without typedef (struct Point { ... };).


text:
Q: Why do I get an exception when using WebClient.DownloadData for a url? I have 2 urls:
https://static.summitracing.com/global/images/prod/xlarge/cse-5160_xl.jpg
http://www.americanbassusa.com/Subwoofers/DX-Series-Images/DX/DX-front.jpg
Both download the corresponding images correctly when opened in Chrome but when using the following console application to download them using WebClient.DownloadData(String), the second url causes a System.Net.WebException to be thrown.
Can any one provide me with an understanding as to why this is happening?
class Program
{
    static void Main(string[] args)
    {
        const string WorkingUrl = "https://static.summitracing.com/global/images/prod/xlarge/cse-5160_xl.jpg";
        const string NonWorkingUrl = "http://www.americanbassusa.com/Subwoofers/DX-Series-Images/DX/DX-front.jpg";

        try
        {
            using (var client = new WebClient())
            {
                byte[] fileData = client.DownloadData(NonWorkingUrl);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }
}

The exception details are:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
   at System.Net.WebClient.DownloadData(Uri address)
   at System.Net.WebClient.DownloadData(String address)
   at ConsoleApp4.Program.Main(String[] args) in C:\\Users\\davidandrewpowell\\source\\repos\\ConsoleApp4\\ConsoleApp4\\Program.cs:line 17

A: This particular server wants a useragent string that indicates a browser is in use. This works:
    using (var client = new System.Net.WebClient())
        {
             client.Headers.Add(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134");
             client.DownloadFile(NonWorkingUrl, "c:\\temp\\a");
        }
    }

No particular reason I used downloadfile- just playing around with stuff. If you need the byte array in your app then surely use downloaddata :)


text:
Q: Stuck with broken library for TradeSatoshi exchange I'm trying to write a trading robot for TradeSatoshi-exchange. I'm using this small library https://github.com/ShuffleDATMT/TradeSatoshiAPI
It's probably a quick simple fix, but I'm new to C# so I'm asking for some help here.
I am getting a parsing error when trying to fetch my balance from TradeSatoshi API. Others are writing that they're getting the loginscreen instead of the jason string. So there's something wrong in these attached methods.
The code that I use to call it is just the demo code in the TesterProject but with my key and secret filled in.
This is the error I get.
JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Which probably is explained by getting the wrong format/page back.
If anyone could help out I would be really grateful!.
public static async Task<GetBalanceReturn> GetBalance(string Currency)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                string uri = "https://tradesatoshi.com/api/private/getbalance";
                string nonce = Guid.NewGuid().ToString();
                JObject post_params = new JObject();
                post_params.Add("Currency", Currency);
                string signature = GetSignature(uri, nonce, JsonConvert.SerializeObject(post_params)).Result;
                string authenticationString = "Basic " + GlobalSettings.API_Key + ":" + signature + ":" + nonce;
                client.DefaultRequestHeaders.Add("Authentication", authenticationString);
                return JsonConvert.DeserializeObject<GetBalanceReturn>(await client.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(post_params), Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync());
            }
            catch(Exception e) { throw e; };
        }
    }

And here is the method creating the HMAC signature.
    private static Task<string> GetSignature(string uri, string nonce, string post_params = null)
    {
        string signature = "";
        if (post_params != null)
        {
            post_params = Convert.ToBase64String(Encoding.UTF8.GetBytes(post_params));
            signature = GlobalSettings.API_Key + "POST" + uri + nonce + post_params;
        }
        else
        {
            signature = GlobalSettings.API_Key + "POST" + uri + nonce;
        }
        byte[] messageBytes = Encoding.UTF8.GetBytes(signature);
        using (HMACSHA512 _object = new HMACSHA512(GlobalSettings.Secret_Key))
        {
            byte[] hashmessage = _object.ComputeHash(messageBytes);
            return Task.FromResult(Convert.ToBase64String(hashmessage));
        }
    }

A: The TradeSatoshi API is broken for the getbalance endpoint (for some reason the service always produces the error "Somthing went wrong, please try again later.").  The getbalances endpoint does work, so you can filter the results from getbalances to retrieve the balance for a particular currency.  I use something similar to the code shown below and it works for most private API calls to tradesatoshi.
If you need help with private or public calls to tradesatoshi using C#, I have an unfinished (as of yet) client I can post to github.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace TradeSatoshi.Console
{
    public class TradeSatoshiResponse<T>
    {
        [JsonProperty(PropertyName = "success")]
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        [JsonProperty(PropertyName = "result")]
        public T Data { get; set; }
    }

    /// <summary>
    /// A <see cref="BalanceInfo"/> instance is one returned from the  https://tradesatoshi.com/api/private/getbalance URI
    /// </summary>
    public class BalanceInfo
    {
        public string Currency { get; set; }
        [JsonProperty(PropertyName = "CurrencyLong")]
        public string CurrencyLongName { get; set; }
        public decimal Available { get; set; }
        public decimal Total { get; set; }
        public decimal HeldForTrades { get; set; }
        public decimal Unconfirmed { get; set; }
        public decimal PendingWithdraw { get; set; }
        public string Address { get; set; }

        public override string ToString()
        {
            return $"Currency: {Currency}, CurrencyLongName: {CurrencyLongName}, Available: {Available}, Total: {Total}, HeldForTrades: {HeldForTrades}, Unconfirmed: {Unconfirmed}, PendingWithdrawl: {PendingWithdraw}, Address: {Address}";
        }
    }

    class StackExchangeQuestion
    {
        private const string PUBLIC_API_KEY = "your public key";
        private const string PRIVATE_API_KEY = "your private key";

        public static async Task GetBalance(string Currency)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var uri = new Uri("https://tradesatoshi.com/api/private/getbalances");
                    string nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
                    JObject post_params = new JObject();
                    post_params.Add("Currency", "BTC"); //not needed for getbalances, but I left it in here to show how post params would be used
                    string serializedParms = JsonConvert.SerializeObject(post_params);
                    string signature = CreateSignature(uri, serializedParms, nonce);
                    var content = CreateHttpContent(serializedParms);
                    var request = CreateHttpRequestMessage(uri, signature, content, nonce);
                    var result = await client.SendAsync(request).Result.Content.ReadAsStringAsync();
                    var response = JsonConvert.DeserializeObject<TradeSatoshiResponse<IList<BalanceInfo>>>(result);
                    var balance = ((IList<BalanceInfo>)response.Data).Single(x => x.Currency == "BTC");
                    System.Console.WriteLine(balance);

                }
                catch (Exception e) { throw e; };
            }
        }

        public static string CreateSignature(Uri uri, string parameters, string nonce)
        {
            //SIGNATURE: API_KEY + "POST" + URI + NONCE + POST_PARAMS(signed by secret key according to HMAC - SHA512 method.)
            string endpoint = WebUtility.UrlEncode(uri.ToString()).ToLower();
            parameters = Convert.ToBase64String(Encoding.UTF8.GetBytes(parameters ?? ""));
            var signature = $"{PUBLIC_API_KEY}POST{endpoint}{nonce}{parameters}";
            using (var hashAlgo = new HMACSHA512(Convert.FromBase64String(PRIVATE_API_KEY)))
            {
                var signedBytes = hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(signature));
                return Convert.ToBase64String(signedBytes);
            }
        }

        public static HttpContent CreateHttpContent(string jsonParams)
        {
            return new StringContent(jsonParams ?? "", Encoding.UTF8, "application/json");
        }

        public static HttpRequestMessage CreateHttpRequestMessage(Uri uri, string signature, HttpContent content, string nonce)
        {
            var header = $"Basic {PUBLIC_API_KEY}:{signature}:{nonce}";
            var message = new HttpRequestMessage(HttpMethod.Post, uri);
            message.Headers.Add("Authorization", header);
            message.Content = content;
            return message;
        }

    }
}


text:
Q: Feign client response validation I have two applications A and B communicating with each other using FeignClient.
As an application A I want to have validation on the data that is returned by application B. If I want to validate request parameters I can easily use @Valid annotation and annotate object with correct spring validation annotations. What about response ?
@FeignClient()
public interface AccountClient {
   @PostMapping("/accounts/account/create")
   void createAccount(@Valid CreateAccountRequest request);

   @PostMapping("/accounts/account/get")
   AccountResponse getAccount(AccountRequest request);

}

public classs AccountResponse {
   @NotNull
   public String status;
}

Code as an example. I can easily validate CreateAccountRequest in application B. But what about AccountResponse? In that case @NotNull is not working. I would prefer to avoid getting the response and manually checking if status != null cause I would have much more fields like this.

A: In this case, the response validation should work if you place @Validated onto AccountClient interface and then @Valid onto getAccount method.
This is standard Spring validation feature, applicable not only for Feign
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@Validated
@FeignClient
public interface AccountClient {
   @PostMapping("/accounts/account/create")
   void createAccount(@Valid CreateAccountRequest request);

   @Valid
   @PostMapping("/accounts/account/get")
   AccountResponse getAccount(AccountRequest request);

}


text:
Q: wso2 carbon hacking - eclipse development environment set up steps It would be great if the carbon source tree could be set up in eclipse so that eclipse can be used for building and running carbon.  Is this possible?  How do the WSO2 carbon developers set up their development environments?
For example based on eclipse 4.3 RC2 Java EE:

*

*$ svn checkout http://svn.wso2.org/repos/wso2/carbon/kernel/branches/4.1.0 wso2carbon

*$ cd wso2carbon

*$ mvn install -Dmaven.test.skip=true  (first ensure you have enough permgen space, e.g. set MAVEN_OPTS=-Xmx512M -XX:MaxPermSize=512M)

*$ mvn eclipse:eclipse

*ensure eclipse M2_REPO variable points to your ~/.m2/repository folder

*import all'dependencies/axiom' sub-projects into eclipse (Existing Projects into Workspace)

*select all maven projects, right click and Disable Maven Nature

*repeat step 6 and 7 for which projects???

What are the steps?  Should I expect errors be shown (see screenshot, below) in the eclipse error window after the import has completed and eclipse build has finished?

A: After importing, you need to set the classpath. for that,buildpath-->configure buildpath, you will see libraries are listed under M2_REPO,folder.
So, you might need to create a variable called M2_REPO,its path has to point your local m2-repository;
eg:
Name: M2_REPO
path: C:/Users/TOSH/m2-repo/repository


text:
Q: changing the output format in blitz I use blitz library regularly in c++. It has quite a few nice facilities like to print a 2-dimensional array one just needs to
cout<<A<<endl;

However, the output comes out like (for 2x2 arrays)
2 x 2
[ 4  5
  2  1]

Now, I wish to get rid of the 2x2 dimension and the brackets it places, because it sometimes creates problem when I wish to directly use the file to plot something. How do I do this?

A: You need to write your own output routine.
Probably the simplest way to do that is to create a proxy class template:
template <typename blitzarray>
struct printer
{
    printer (const blitzarray& ba_) : ba(ba_) {}
    const blitzarray& ba;
};

which outputs the array it has just the way you like:
template <typename blitzarray, typename stream>
stream& operator<< (stream& s, printer<blitzarray> pb)
{
    // <-- print the array here <--
    return s;
}

and then have a little helper function that helps deducing the template argument:
template <typename blitzarray>
printer<blitzarray> myprint(const blitzarray& ba)
{
    return printer<blitzarray>(ba);
}

The use is just:
cout << myprint(A) << endl;

You probably can borrow from the original blitz++ output routine.


text:
Q: How to set jqgrid value dynamically calculated from editform I have jqgrid with columns transaction id, debit, credit and balance.
Debit and credits are populated from database and balance is set by calculations from difference of credit - debit.
The editing is done in editform. Once, user changes one of the values of debit or credit, I need the balance column to update in the selected row of the grid.
Any help is greatly appreciated.
$myGrid.jqGrid({
url: myURL + '?method=GetTranactions',
postData: {
    prID: function() { return getProv(); },
    mn: function() { return $("#month option:selected").val(); },
    yr: function() { return $("#year option:selected").val(); }
},
datatype: 'json',
mtype: 'POST',
colNames:['Trx ID','Debit','Credit','Balance',],
colModel :[
    {name:'accttrx_id',index:'accttrx_id', width:75, sorttype:"int", editable:true},
    {name:'debit',index:'debit',
        width:70,
        align:"right",
        formatter:'number',
        sorttype:"number",
        editable:true,
        edittype:"text",
        editoptions:{
            size:20,
            defaultValue:'0',
            dataEvents: [
                {
                    type: 'change',
                    fn: function(e) {
                        var db = $(e.target).val();
                        var cr = $('#credit').val();
                        bal = cr - db;  // got the balance
                        alert(bal); // how to update balance column for current row?
                        }
                    }
                ]

            },
        editrules:{required:true},
        formoptions:{elmprefix:"(*)"}
        },
    {name:'balance',index:'balance',
        width:70,
        align:"right",
        formatter:'number',
        sorttype:"number",
        editable:false},....

....................................................................
$myGrid.navGrid('#pager', {
search:false,
edit:true,edittitle:"Edit Transation",
add:true,addtitle:"Add Transaction",
refresh:true,
del:true,deltitle:"Delete Transaction"
},
{
beforeShowForm:
    function(form) {
        $('#tr_accttrx_id', form).hide();
    },
    afterSubmit:
    ..... update balance after submit?

A: For custom calculations in the editForm, like you have described here, I usually put the code in the beforeShowForm function as you have described here.  Please use something similar to this:
beforeShowForm: function() {
    $('#debit,#credit').change(function(){
        $('#balance').val( parseFloat($('#credit').val()) - parseFloat($('#debit').val()) );
    });
},
reloadAfterSubmit: true,
...

The jQuery selectors ( $('#balance') for example) uses the name of the jqGrid column as the ID selector.  I do this because I know jqGrid makes the column name into the input element ID in the edit form.
Reload After Submit (show updated info in Grid)
In order to see your new balance value show up in the grid, use the reloadAfterSubmit property of the edit form, which I included in the above example.  Please verify, you are using form Editing or In-Line editing?  If you are using form editing, then the code in my answer should work, if should be used with the editGridRow method.  See here: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing
Little Problem with parseFloat and money
While the above code should work for the most part, please not that the parseFloat command should not be used to do calculations with money.  I have run into rounding issues with this before.  Instead you can use the BigDeciaml package.


text:
Q: JQGrid How do I removed the annoying horizontal scrollbar when autowidth = true? (In IE) I seem to be getting an annoying horizontal scrollbar when using autowidth=true in IE
What is going on here and how do I get rid of it?

A: I got perfect Solution. The problem is in CSS. In ui-jqgrid.css the table layout is in Fixed. Make it as auto it will work perfectly. I just copied the same class i.e.,
.ui-jqgrid .ui-jqgrid-btable
{
  table-layout:auto;
}

A: Make your grid tall enough to contain all the rows. The horizontal scrollbar is there because the vertical scrollbar is taking up some of the width normally used by the rows.

A: Set the scrollOffset option to something like 20 - 30, this will fix the horizontal scrollbar adjustment problem.

A: Set the scrollOffset to 18 - it's solve the problem.
Quick and effective.
Thanks, Corey Schomer!

A: setting table-layout: auto could be slow. if you have lots of data
this is from w3school (http://www.w3schools.com/cssref/pr_tab_table-layout.asp)
Automatic table layout algorithm (this is default):
The column width is set by the widest unbreakable content in the cells
Can be slow, since it needs to read through all the content in the table, before determining the final layout


text:
Q: PHP integer exponentiation (super large numbers) Using PHP I want to do millions of 2^n exponentiation but so far I only got up to n^1023 before PHP printed INF.
Any ideas?

A: As Greg said, BC Math is fine, but if you really need efficiency, try GMP instead.

A: You can use the BC Math functions:
  $num = bcpow(2, 1000000); // Takes a few seconds to run!


text:
Q: Is it possible to have multiple level Nested Route in Angular2 Is it possible to have multiple level nesting for angular routing. I am trying to achieve below but it says [Child routes are not allowed for "/cash/..". Use "..." on the parent's route path].
Intended route
/storeselector
/forms - shows all forms
/forms/cash/ - user select cash form from list of forms and on load it will shows all orders
/forms/cash/id:1/ shows order details
/forms/cash/edit/1 edit order 1
below is my code.
app component
@Component({
    selector : 'forms-app',
    templateUrl : 'app/app.component.html',
    styleUrls : ['app/app.component.css'],
    directives: [ROUTER_DIRECTIVES],
    providers: [HTTP_PROVIDERS]
})
@RouteConfig([
  { path: '/storeselector', name: 'StoreSelector', component: StoreSelectorComponent, useAsDefault: true },
  { path: '/forms/...', name: 'Forms', component: FormsComponent }
])

forms component

@Component({
    selector : 'forms-root',
    template: '<router-outlet></router-outlet>',
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path: '/', name: 'Forms', component:FormsListComponent, useAsDefault: true },
    { path: '/cash/..', name: 'CashForm', component:CashFormOrderComponent, useAsDefault: false}
])
export class FormsComponent {
  constructor(private _logger : LogService) {
    this._logger.info("FormsComponent loaded");
  }
}

cashform components
@Component({
    selector : 'forms-cash',
    template: '

',
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path: '/', name: 'Orders', component:CashOrdersListComponent, useAsDefault: true },
    { path: '/:id', name: 'Order', component:CashOrderComponent },
  { path: '/edit/:id', name: 'Order', component:CashOrderComponent  }
])
export class CashFormOrderComponent {
  constructor(private _logger : LogService) {
    this._logger.info("CashFormOrderComponent loaded");
  }
}

A: { path: '/cash/..', name

should be
{ path: '/cash/...', name

To indicate there are child routes 3 . are required


text:
Q: Math notation and Fonts I'm creating a rather large document/thesis/book that will contain a lot of math. I'm having problems getting a consistent set of math fonts or notation for different types of variables. Specifically, I have scalar variables, vectors, matrices, and tensors that I would like to all look different.
I had sort of settled on the following:

*

*scalar - 'regular' italicized

*vector - same as scalar, but with an arrow (latex \vec)

*matrix - bold (preferably upright as well)

*tensor - preferably blackboard font, but also maybe the same as a matrix

That's all well and good, except my field uses many Greek letters, both lower and uppercase. In addition, after writing a long section with latex's \vec, it looks
ugly and crowded, particularly when combined with superscripts. Most documents I've seen fudge many of them together.
So any mathematicians/latexticians have opinions on getting a consistent notation for a large document? As a side note, I'm currently using kpfonts, and would like to keep that (or Palatino) for the main text.

A: isomath defines \vectorsym, \matrixsym and \tensorsym to typeset vectors, matrices and tensors in an ISO-conformant way. It also loads fixmath to provide correct typesetting for the greek alphabet.


text:
Q: Creating an SKSpriteNode class with Swift 4 I've coded a simple game using Swift 4 and XCode, and I've coded everything in the GameScene. All my elements (the monsters, the player, the projectile, etc.) are coded in the GameScene.
I want to transfer my code into dedicated classes (Class Player, class monster, etc.)
I would like to know what the basic structure of a SKSpriteNode class and the call of that class in the GameScene, to be more efficient at adapting my code.
Here's an example of what I've tried :
class Vaisseau: SKSpriteNode /*: Creatures */{

var coeur: Int = 0

init(texture: SKTexture, size: CGSize)
{
    let texture = SKTexture(imageNamed: "player")
    super.init(texture: texture, color: UIColor.clear, size: texture.size())
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

And the initialization in the GameScene :
 let player = Vaisseau()

Here's how it is actually defined in the GameScene :
let player = SKSpriteNode(imageNamed: "player")

A: you are declaring your init to have two parameters (texture: SKTexture, size: CGSize) but you are not passing the parameters in your initialization call
let player = Vaisseau()

you either need to change the initialization to...
let texture = SKTexture(imageNamed: "player")
let player = Vaisseau(texture: texture, size: texture.size())

and change the init to
init(texture: SKTexture, size: CGSize) {
    super.init(texture: texture, color: UIColor.clear, size: size)
}

OR change the init in the class to...

init() {
    let texture = SKTexture(imageNamed: "player")
    super.init(texture: texture, color: UIColor.clear, size: texture.size())
}

and leave your initialization call as...
let player = Vaisseau()
player.position = CGPoint(x: 500, y: 500)
addChild(player)

EDIT added the above 2 lines to show you that those need to be in the scene
  but other items such as alpha, zPosition, actions, zRotation etc. can be inside of the class

What you need to ask yourself to figure out which one to use is "will the texture for the player ever be different?" if so you may want to consider the first option where you pass in the texture.


text:
Q: MVC startdate and end date validations I am having difficulties getting this to work. I want to allow a user to choose start date and end date, if the start date is greater than the end date I want an error message to display. I am using MVC. This is the code I have on my model.
 public class ModelClass : IValidatableObject
{
    [Required(ErrorMessage = "ID Number is required")]
    [Display(Name = "ID Number:")]
    [RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")]
    public Int64 ID_Number { get; set; }
     [Required(ErrorMessage = "The start date is required")]
    [Display(Name = "Start Date:")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime Start_Date { get; set; }
    [Required(ErrorMessage = "The end date is required")]
    [Display(Name = "End Date:")]
    [GreaterThan("Start_Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime End_Date { get; set; }

    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
    {
        if (End_Date < Start_Date)
        {
            yield return new ValidationResult("EndDate must be greater than StartDate");
        }
    }
}

A: This is how your model should look like:
 public class ModelClass : IValidatableObject
{
    [Required(ErrorMessage = "ID Number is required")]
    [Display(Name = "ID Number:")]
    [RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")]
    public Int64 ID_Number { get; set; }
    [Required(ErrorMessage = "The start date is required")]
    [Display(Name = "Start Date:")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime Start_Date { get; set; }
    [Required(ErrorMessage = "The end date is required")]
    [Display(Name = "End Date:")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime End_Date { get; set; }

    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
    {
        if (End_Date < Start_Date)
        {
            yield return new ValidationResult("EndDate must be greater than StartDate");
        }
    }
}

After the user pressed on the submit button we need to check that the model is valid.

ModelState.IsValid

will go to you model and will validate the model, If the post model is valid(keeping the rules you decided in your model) then it's valid.
And this is how your action should look like:
[HttpPost]
public ActionResult Create(ModelClass modelClass)
{
    if (ModelState.IsValid)
    {
        db.modelClass.Add(modelClass);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(modelClass);
}


text:
Q: Открытие/закрытие balloon при ховере и его позиционирование
Cделал карту участков (с помощью полигонов), и при ховере открывается баллун с инфой об участке, но баллун позиционируется не правильно.
Есть кейс когда ты пытаешься навести курсор на баллун (допустим, нажать кнопку) и ховер срабатывает на другом участке, соответственно отрывается другой баллун а старый закрывается.
Можно ли сделать так, чтобы баллун позиционировался в плотную к участку?
Код:
(function () {

for (let i = 0; i < areas.length; i++) {

let num = areas[i]['number'];

let coords = areas[i]['coords'];

let status = areas[i]['status'];

let price = areas[i]['price'];

let area = areas[i]['area'];

let opacity = 0.5;

let newCoords = new Array();

for (let q = 0; q < coords.length; q++) {

let item = [];

item.push(coords[q]['latitude']);

item.push(coords[q]['longtitude']);

newCoords.push(item);

}

if (status == 0) {

status = statusFree;

opacity = 1;

} else if (status == 1) {

status = statusSold;

} else {

status = statusReserved;

}

let Land = new ymaps.Polygon([

newCoords

], {

balloonContent: descriptionFormation(status, num, area, price),

balloonAutoPan: false,

}, {

fillColor: status,

fillOpacity: opacity,

zIndex: 1,

zIndexHover: 1,

});

mapLand.geoObjects.add(Land);

mapLand.options.set('balloonAutoPan', false);

Land.events.add('mouseenter', function () {

Land.balloon.open();

});

}

function descriptionFormation(status, num, area, price, house) {

if (status == statusFree) {

if (house == true) {

let tmp = '
';

tmp += '
Участок №' + num + '
';

tmp += '
';

tmp += '
Площать
';

tmp += '
' + area + '
';

tmp += '
';

tmp += '
';

tmp += '
Постройки
';

tmp += '
' + house + '
';

tmp += '
';

tmp += '
Свободен
';

tmp += '
'+ price * 1000 +'
';

tmp += '

';

tmp += '
';

return tmp;

}

else{

let tmp = '
';

tmp += '
Участок №' + num + '
';

tmp += '
';

tmp += '
Площать участка
';

tmp += '
' + area + ' сот.
';

tmp += '
';

tmp += '
Свободен
';

tmp += '
' + price * 1000 + ' рублей
';

tmp += '
Оставить заявку
';

tmp += '
';

return tmp;

}

}

else if (status == statusReserved) {

let tmp = '
';

tmp += '
Участок №' + num + '
';

tmp += '
Забронирован
';

tmp += '
';

return tmp;

}

else if (status == statusSold) {

let tmp = '
';

tmp += '
Участок №' + num + '
';

tmp += '
Продан
';

tmp += '
';

return tmp;

}

}

$('body').on('click', '.ymap-content__button', function () {

clickOnPolygon();

});

function clickOnPolygon() {

$('.modal-window_contacts').addClass('modal-window_display');

setTimeout(function () {

$('.modal-window_contacts').addClass('modal-window_show');

}, 10);

}

})();


text:
Q: Removing first case insensitive duplicate of an ArrayList I have an arraylist containing some strings:
ArrayList<String> strList = new ArrayList<String>();
strList.addAll(Arrays.asList("interface", "list", "Primitive", "class", "primitive", "List", "Interface", "lIst", "Primitive"));

I have wrote a method to remove the case insensitive strings of the arraylist:
public static ArrayList<String> removeDuplicates(ArrayList<String> strList) {

    for(int i = 0; i < strList.size(); i++) {
        for(int j = i + 1; j < strList.size(); j++) {
            if(strList.get(i).equalsIgnoreCase(strList.get(j))){
                strList.remove(j);
                j--;
            }
        }
    }
    return strList;
}

Ouput:
[interface, list, Primitive, class]

However, I am trying to remove just the first occurance of the strings. I am trying to make it so my output would equal:
[Interface, lIst, Primitive, class]

Which would be the last occurrences of the duplicates in the arraylist
What I'm trying to do specifically:

The version of the string that remains is the same as the last occurrence. In other words, the
  version of the last occurrence stays at the location of the first occurrence

A: I think that remove from the ArrayList is not good idea. It is better using Map to create new list:
public static List<String> removeDuplicates(List<String> strList) {
    Map<String, String> map = new LinkedHashMap<>();
    strList.forEach(item -> map.put(item.toLowerCase(), item));
    return new ArrayList<>(map.values());
}

Input: [interface, list, Primitive, class, primitive, List, Interface, lIst, Primitive]
Output: [Interface, lIst, Primitive, class]
P.S.
Same with one line Stream, but a bit not so clear:
public static List<String> removeDuplicates(List<String> strList) {
    return new ArrayList<>(strList.stream().collect(Collectors.toMap(String::toLowerCase, str -> str, (prev, next) -> next, LinkedHashMap::new)).values());
}

A: Right now it keeps the first occurrence, so if you want to keep the last occurrence you can just go through the list in reverse:
for(int i = strList.size() - 1; i >= 0; i--) {
    for(int j = i - 1; j >= 0; j--) {
    ...


text:
Q: ElasticSearch: update by query from a different index I have the following problem with ElasticSearch. Let's say I have one index called "products". In general, its documents have the following fields:

*

*productId

*productPackId

*productName

*price

And then (for reason that I cannot explain here, but let's say weren't my decision) I have another index called "productPacks" with:

*

*productPackId

*name

*imageUrl

Now, I need to get the imageUrl field of the index "productPacks" in the "products" index according to which *productPackId" each document on the "products" index has. To clarify: let's say that in "productPacks" the document with
"productPackId" = 1
has as
imageUrl: "https://mywebsite.com/image1.jpg",
what I need is that all documents on the "products" index that have "productPackId" === 1 get then
imageUrl: "https://mywebsite.com/image1.jpg"
I can't find a way of doing it.
Thanks in advance!
(This, of course, would be super easy on a SQL database.)

A: What you basically want to do is join the two indices, on the "productPackId".
This is not possible in elasticsearch over two different indices.
There is a simple solution:
Iterate over each and every document in the index with the image url's(Index 2) and update by query into index 1, use the productPackId to make the query. That way you will be able to add the image_urls into index1.
Elasticsearch does not have any concept of Join's across indexes.
HTH.

A: The result you expect, you can only do it with a SQL request
https://www.elastic.co/guide/en/elasticsearch/reference/master/xpack-sql.html


text:
Q: Linking python virtual environment to eclipse I have Python2.7 installed and Python3.5 installed on my windows machine.These are at locations C:\Python27 and C:\Python35-32. Both these are added in System Path environment variables and can be accessed from any directory.
Now i create a virtualenv in Python35-32 directory successfully under a sub-directory CODING_LABS.
I try to link/point my Eclipse python interpreter to the python.exe file contained in  CODING_LABS. This is done OK.
However, when i run my script from eclipse,it still points to Python27.Unable to figure out why?

A: Not sure... by default, any run will get the 'default' interpreter (which is the first interpreter in Preferences > PyDev > Interpreters > Python interpreter -- you may reorder those using the up/down button in that screen).
Now, that's the default, you may also configure to use a different interpreter per project (select project > alt+Enter for its properties > PyDev - Interpreter/Grammar > Interpreter).
Or you can choose a different one per launch:
Menu > Run > Run Configurations > Select launch > Interpreter.
Also, you may want to double check to make sure that the paths in the interpreter configuration window (Preferences > PyDev > Interpreters > Python interpreter > select interpreter) actually map to the proper site-packages/external libs you expect.


text:
Q: Re-trigger Css3 Keyframe animations on jQuery/Javascript time delay This has been bugging me for a while now, any help would be greatly appreciated!
I've been using css3 keyframe animations, I've run into a problem, I'm trying to get my animation  element to re-trigger after a timed delay, all the other questions are asking and receiving similar ones for onclick triggers.
http://codepen.io/stoikerty/pen/mBAcs is a great example, just how would it be done on a time delay

Document

Div Element on document

Animation settings

.banner-RunAnimation{-webkit-animation: bannerImg-animation1 3s 0s 1 ease-in-out, bannerImg-animation2 5s 5s 1 ease-out forwards;}

Animation keyframes

@-webkit-keyframes bannerImg-animation1 {
  0% {
    -webkit-transform: scale(.3);
    opacity: 0;
  }
  50% {
    -webkit-transform: scale(1.05);
    opacity: 1;
  }
  70% {
    -webkit-transform: scale(.9);
  }
  100% {
    -webkit-transform: scale(1);
  }
}

@-webkit-keyframes bannerImg-animation2 {
  0% {
    -webkit-transform: translateY(-0px);
  }
  50% {
    -webkit-transform: translateY(-150px);
    opacity: 1;
  }
  75% {
    opacity: 0.8;
  }
  100% {
    -webkit-transform: translateY(-150px);
    opacity: 0;
  }
}

Script


text:
Q: Can I solder a plug to the end of my irrigation system power supply? I got a new sprinkler head unit that only takes power input from a barrel plug, here is an ebay listing for the transformer it came with. It's 24VAC AC/AC transformer.
Problem is my old head unit was wired with a power supply that had exposed wires to a screw terminal. I have no outlets near my sprinkler unit, and the power supply for the old unit is wired behind the walls. I confirmed that the power supplies are compatible, so I am going to connect the exposed wires to a plug for the new unit.
My only two concerns are:

*

*I can only find "DC" plugs like these, I am going to try them, but does it matter is says they are "DC" when my transformer is AC/AC? It's probably a dumb question.

*My old head unit had a screw terminal for ground, do I need to find a plug that takes a ground wire too, or should I ignore the ground wire in this case?

A: There would be no necessity to use a soldering-type barrel connector.
The screw-terminal-type barrel connector may be used, provided it is compatible with the barrel socket on the new sprinkler head.
You may ground the new sprinkler head, should it be all-metal and has a screw where you can connect the ground wire.


text:
Q: how to convert network to host address in tcl convert this code in tcl and how to make a function network to host in tcl
capturedTlpData[i] = (UInt32)IPAddress.NetworkToHostOrder(BitConverter.ToInt32((byte[])retValbuffer,i*4));

here NetworkToHostOrder is:-
`
public static int NetworkToHostOrder(int network`)

A: You've read four bytes from the network in network-endian form and want to convert it to an unsigned integer? The binary scan command can do that. You'll want the u modifier, which requires Tcl 8.6.
binary scan $theBytes Iu theValue

For example, if you have the bytes that correspond to the ASCII abcd then you get:
set theBytes "abcd"
binary scan $theBytes Iu theValue
puts $theValue
# Prints 1633837924
puts [format %x $theValue]
# Prints 61626364

If you're using Tcl 8.5, just use the I specifier and post-process the value with this to convert to unsigned (because Tcl uses bignums internally):
set theValue [expr {$theValue & 0xFFFFFFFF}]


text:
Q: W3C Standards compliant A name attribute replacement I am currently working making sites W3C standards complaint. There is an FAQ page which has a list of questions which is followed by the answers for the questions.
Each question is embedded in a hyperlink that has an HREF attribute with hash symbol a unique name containing a numerical index. For example Question 1, Question 2, etc...
At the beginning of each answer there is an a tag which has a name corresponding to the HREF in the question list. For example, , ,  etc...
This allows the user to click on the question and navigate directly to the answer.
Additionally, there an A tag before the list of questions with the name top, . Following each answer there is a hyperlink Back to Top which users can click on to go back to the beginning of the list of questions.
However, when validating the page there is an error The 'name' attribute on the 'a' element is obsolete. Consider putting an 'id' attribute on the nearest container instead.
How can this functionality be accomplished in HTML5 in a manner that is standards compliant?
Here is sample markup of the FAQ page:
<!DOCTYPE html>

        <title>FAQs</title>

Question 1

Question 2

Question 3

Question 4

Question 5

1.  Question 1

Answer:

Answer 1.

Back to top

2.  Question 2

Answer:

Answer 2.

Back to top

2.  Question 3

Answer:

Answer 3.

Back to top

2.  Question 4

Answer:

Answer 4.

Back to top

2.  Question 5

Answer:

Answer 5.

Back to top

A: Like it is stated in the log:
Use
...Answer 1...
.
You can keep  to navigate.
Most HTML functions which aren't included in HTML5 are kept in most browsers, but it isn't recommended.

A: You already have id attributes with the appropriate value on those elements (effectively duplicating the anchor name, which is not DRY). Just remove the name attribute and the page will continue working:

1.  Question 1

    …

2.  Question 2

    …

Alternatively you might consider wrapping each question in another element, and putting the id attribute on that. Given your structure, a list might be appropriate, but you can also just use
s:

Question 1

Answer:

Answer 1.

Back to top

Question 2

Answer:

Answer 2.

Back to top

    …


text:
Q: Content Security Policy nonce: backend vs reverse proxy I'm trying to understand how Content Security Policy nonce mechanism works in a scenario where the CSP header tag is set by Apache HTTPD acting as reverse proxy and not by the application server itself.
Since the nonce is random and the application inserts it into the script tag, I can only see the way where the response provided by the application (the backend part) contains the CSP header with the random nonce.
If the CSP header is set by Apache HTTPD (which is btw another server, not the backend server), i cannot se how Apache con now the random nonce, synchronizing it with the nonce generated by the backend.
https://content-security-policy.com/nonce/

A: You need to generate the nonce on the server, and then have Apache pass that nonce to your script where it can be used.
We've created an open source module for Apache that simplifies this process: mod_cspnonce.
Here's a simple example of the server-side config:
LoadModule headers_module modules/mod_headers.so
LoadModule cspnonce_module modules/mod_cspnonce.so

# add the CSP_NONCE to the "default-src"
Header add Content-Security-Policy "default-src 'self' 'nonce-%{CSP_NONCE}e';"

Here's a simple example of using the nonce in your script:
<script nonce="<?= $_SERVER['CSP_NONCE'] ?>">
  var inline = 1;
</script>


text:
Q: python tkinter: destroy() not working after using threading.Timer() Code Part 1
from tkinter import *
from PIL import Image, ImageTk
import threading

c1 = "#262626"

root = Tk()
root.overrideredirect(True)
root.configure(bg=c1)

def destroy():
    global root
    root.destroy()

def pr():
    print("asd")
    destroy()

def animation():
    threading.Timer(0.01, pr).start()

animation()
root.mainloop()

after the destroy () command has worked, the window is closed, but the program continues to work, you can disable it only with the help of the task manager or CMD, but there's no any errors.
Code Part 2

login = Tk()

img = Image.open(selfDir + "\\ok.png").resize((50, 50), Image.ANTIALIAS)
test = ImageTk.PhotoImage(img)
label1 = Label(login, image=test, bg=c1)
label1.image = test
label1.place(x=330, y=145, width=50, height=50)

login.mainloop()

if I run this part after the first one, I see an error:
tkinter.TclError: can't invoke "image" command: application has been destroyed
but if I run only this part, without the first one, then it works and I can see the photo in the window
So the problem is.
I need to close window after threading.Timer()
Then i need to open window, with an image

A: i just need to write
root.after(10, pr)
instead of
threading.Timer(0.01, pr).start()
special thanks to Matiiss


text:
Q: Compiling the mysql_fdw for postgresql? I'm attempting to compile the MySQL Foreign Data Wrapper for Postgresql 9.1+, on Ubuntu 12.04 LTS and having a fair bit of trouble getting it to work.
So far I've managed to use git to download the source from github, and based on the instructions add the following to my /etc/profile path in the hopes that this thing will compile:
# ^ The rest of the file ^
# POSTGRESQL Environment Vars
export PGDATA="/usr/local/pgsql/data"
export PGHOST="localhost"
export PGPORT="5432"
export PGLOG="/var/log/pgsql"
export PATH=$PATH:/usr/lib/postgresql/9.1/bin:/opt/lampp/bin

I then per the documentation I ran
$ make USE_PGXS=1
gcc -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -fPIC -DLINUX_OOM_ADJ=0 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -fpic -I/usr/include/mysql -I. -I. -I/usr/include/postgresql/9.1/server -I/usr/include/postgresql/internal -D_FORTIFY_SOURCE=2 -D_GNU_SOURCE -I/usr/include/libxml2  -I/usr/include/tcl8.5  -c -o mysql_fdw.o mysql_fdw.c
mysql_fdw.c: In function 'mysqlPlanForeignScan':
mysql_fdw.c:467:8: warning: 'rows' may be used uninitialized in this function [-Wuninitialized]
gcc -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -fPIC -DLINUX_OOM_ADJ=0 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -fpic -shared -o mysql_fdw.so mysql_fdw.o -L/usr/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,--as-needed -Wl,-z,now -L/usr/lib/i386-linux-gnu  -Wl,--as-needed  -L/usr/lib/i386-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -ldl

And aside from the warning I suppose it compiled ok...
Next I tried to install it, and I get a couple of errors about some missing files...
$ sudo make USE_PGPX=1 install
Makefile:35: ../../src/Makefile.global: No such file or directory
Makefile:36: /contrib/contrib-global.mk: No such file or directory
make: *** No rule to make target `/contrib/contrib-global.mk'.  Stop.

Do I need to compile all of Postgres and include this extension in the source?  Because the sources seem to be referring to a directory above the one that I'm in.

A: It's a typo.
sudo make USE_PGPX=1 install
              ^^^^
              PGXS


text:
Q: Fork Management of Git Multi-level Hierarchies We have the following Git hierarchy structure in place, where each child is forked from the parent. If we build something in Client1 that will be useful in the entire hierarchy, what is the best way to push the changes up to the parents (whether just one level up or all the way to the root), given that we don't wish to push all the Client-specific customizations up the chain.
Now, while the ideal solution might be to do the development at the highest required level, the modules can only really be tested down the chain where all the customizations are instantiated.
E.g. If we develop a Module-New in Client1 repo, and need to push it to Core, what would the best way for that to be done given that we don't want Client1's customizations in the core? On the other hand, if we had originally developed ModuleA directly in CORE, we would have had to push the changes downstream all the way to Client1 to test Module-New (and iterate for every change).
Are there any Git Workflows or any other tools that can help establish these rules. We currently use GitFlows to manage our master, develop and feature branches for all repos. Also, is there a way to disable direct pushes into a remote repository?
                            CORE
                              |
                ------------------------
            Product 1               Product 2
                |                       |
            ----------              ----------
        Client1     Client2     Client3     Client4
           |-v1.0
           |-v1.1
           ...

A: You can disable direct push in repositories depending on which technologies you're using. Preventing push can be done somewhat using git hooks, but if you're using gitlab/github/bitbucket... there should be a way to protect branches.
If all branches are protected and that the dev can't create new branch, then there is no way to push to the repo. This way, you'll have to handle the dev using "merge requests/push requests" or how it's called.
It's unclear what you're actually managing so the following might not help. In my case, we have a core product that is installed on every client, the core product might be installed with different versions. And additional modules can be installed on the side. Either way, usually client customization are usually done by installing specific modules for clients that extend existing modules (including core modules). In my case, customizations for clients never or rarely bubble up to the core product. If we needed to, we could simply move the module into the core product.
If a custom module is shared across multiple clients, we might use special branches that are merged on the master of each module repository.
In the end, it can get quite complicated if code doesn't bubble up to the master branch of each module's repo. In our case, most of the work is achieved using buildout to manage repos and merges and dependencies.
My opinion
Handling dependencies using git repositories should be limited to development even if it looks simpler to just fetch the repos. Git repository can get quite big and sometimes fetching might fail if the repository is big and the internet connection is unstable...Git doesn't allow partial fetch so if it fails at 99%, you'll have to restart from 0% anyway.
For deployment, I think it makes more sense to have package managers do it. They exists and they usually do their jobs well. The advantage of using a package manager is that you don't have to download the whole history of changes that might come with the module. Usually package managers allow partial download using http so you can pause an update later if internet fails. With a good package manager, you could also host your own private package servers for each client. Any module that is similar for each client can be pushed on a central server and every customized package could be pushed to a package server per client.
All of this is fine if you have a way to automate the building process of package and deployment of package on their respective servers.
This way if a client does something like "package update", it could check on the client server for a package and then on the central server and take the right version from this. Old package don't have to be deleted and the client could downgrade its setup as he wish.
My guess, is that it's the nicest thing someone could implement, yet there is no standard way to do that as far as I know. I heard people doing that with python eggs, other with debian packages an so on. But each implementation has their own problems... Like debian packages won't work on windows and non debian distros... pythong eggs are quite limited to python.. npm packages to javascript and so on. If we had a universal package manager that would be simply a piece of cake to implement.

A: Managing per client code customisation with source control is not a good idea. It's not what source control is designed to do.
In your case for example, there is no way to determine whether the 'new module' is dependant on the customisation in the branch. so you cant just merge it up and expect it to work.
The correct approach is to split the project into components and create a new customised component for clients. When deploying a client instance, you use DI and configuration to specify that the custom component is used rather than the standard one.
All the components are separate repos and published via a package manager so they can be pulled into other projects
If common functionality is used across customised components, these are again split so that the common code is in its own module and the customised components reference it. So in your scenario of wanting to move code 'up a level' you would edit the common component to add the feature to it, and edit the custom component to remove the feature from its code, but reference the new version of the common component which includes the feature


text:
Q: How to insert string variable to html I want to add a string variable from ionic/storage to html.
home.ts
export class HomePage {
  @ViewChild('username') uname;

  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public strg: Storage) {

  }
  signIn() {
    this.strg.set('uname', this.uname.value);
    this.navCtrl.push(Page1Page);
  }
}

page1.html
<ion-content padding>

Welcome to this app, /**I want to add the uname here**/

</ion-content>

How would I go about assigning the string from ionic/storage using the page1.ts?

A: You can simply fetch your username from @ionic/storage again like this:
page1.ts
username: string;

constructor(public strg: Storage) {
    this.username = this.strg.get('uname');
}

page1.html
<ion-content padding>

Welcome to this app, {{username}}

</ion-content>

This {{username}} expression is called One-Way-Data-Binding. So every time you change
the username variable in your Page1Page class, the template page1.html will automatically update.


text:
Q: How do I retrieve a key from a firestore document (using swift 4/ios) In the firebase docs for firebase database there is info on flattening a database and a message app is used as an example.
https://firebase.google.com/docs/database/web/structure-data
 // Conversation members are easily accessible
  // and stored by chat conversation ID
  "members": {
    // we'll talk about indices like this below
    "one": {
      "ghopper": true,
      "alovelace": true,
      "eclarke": true
    },
    "two": { ... },
    "three": { ... }
  },

Under "members"/"one" each key is the name of a participating member in the chat. I'm pretty sure in firebase database there is a getKey method to get each key.
I have set up my database (using firestore instead of firebase) in a similar way but where each chat is a unique identifier and the document contains the members of the chat where the key is their firebase auth id eg.
var docsref: DocumentReference?
                    docsref = self.defaultStore?.colleection("chats").document(chatID)
                    docsref?.getDocument { (document, error) in

                        if let _ = document {

                            print("document!.data()")

                        } else {
                            print("Document does not exist")
                        }
                    }

And when I output:
print(document!.data())

I get ["2mHuccccxxxxxxxxxxk4wkIAt33": 1] which is the firebase auth code of one of the participating chat members and a boolean.
I would like to get that key but wasn't sure how.
Thanks.

A: I'm not sure if it's the exact Syntax but self.defaultStore?.colleection might be a typo with the double E. It could also possibly be that you're missing a step. You're getting inside the chatID and you're expecting to output the keys inside members without actually accessing it. I'd access members after .document(chatID)

A: You can get it as follows.
to get value document.data()
to get key document.documentID


text:
Q: Multi-Column IN and INDEX in MySQL I have a table like this in MySQL. (version is 5.5)
+------------------+---------------+------+-----+---------------------+-----------------------------+
| Field            | Type          | Null | Key | Default             | Extra                       |
+------------------+---------------+------+-----+---------------------+-----------------------------+
| A                | varchar(50)   | NO   | PRI | NULL                |                             |
| B                | varchar(50)   | NO   | PRI | NULL                |                             |
                                               :

But index for WHERE (multi-column) IN does not work.
If number of the set after 'IN' is only one, index works.
explain SELECT * FROM table  WHERE (A, B) IN(('1', '2')) ;
+----+-------------+-------------------+-------+---------------+---------+---------+-------------+------+-------+
| id | select_type | table             | type  | possible_keys | key     | key_len | ref         | rows | Extra |
+----+-------------+-------------------+-------+---------------+---------+---------+-------------+------+-------+
|  1 | SIMPLE      | table             | const | PRIMARY       | PRIMARY | 304     | const,const |    1 |       |
+----+-------------+-------------------+-------+---------------+---------+---------+-------------+------+-------+

But number of the set after 'IN' is more than two, index does not work.
explain SELECT * FROM table WHERE (A, B) IN(('1', '2'), ('3', '4'));
+----+-------------+-------------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table             | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+-------------------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | table             | ALL  | NULL          | NULL | NULL    | NULL | 857897 | Using where |
+----+-------------+-------------------+------+---------------+------+---------+------+--------+-------------+

Why index does not work?

[UPDATE]
If I changed query like below, Index works.
explain SELECT * FROM tabe  WHERE (A='1' AND B='2') or (A='3' AND B='4');
+----+-------------+-------------------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table             | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------------------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | table             | range | PRIMARY       | PRIMARY | 304     | NULL |    2 | Using where |
+----+-------------+-------------------+-------+---------------+---------+---------+------+------+-------------+

But I'd rather like to use IN clause because AND/OR query is very long.


text:
Q: Why is it problematic to regard the Lorentz group as ${\rm SO}(4, \mathbb{C})$? If the four-vector $x^\mu$ is defined as $x^\mu\equiv(ict,{\bf x})$, instead of $x^\mu\equiv (ct,{\bf x})$, the Lorentz group will be the compact(?) ${\rm SO}(4, \mathbb{C})$ group. But the Lorentz group is regarded as the noncompact group ${\rm SO}(3,1)$. But I could never figure out what is the real problem of using $ict$ instead of $ct$? In short, what will go wrong if I choose to work with $ict$? Does it pose a problem from the point of view of representation theory? I am only interested in flat spacetime.

A: ${\rm SO}(4, \mathbb{C})$ allows all four coordinates of spacetime to be complex. It doesn't just allow time to be imaginary.

A: Misner, Thorne, & Wheeler (MTW) offer arguments in
"Farewell to ict" on Gravitation, p.51.
Reasons for using ict:

*

*It makes spacetime geometry look like Euclidean geometry.

*It make a Lorentz transformation look like a rotation.

*It allows one to avoid distinguishing components of a vector from its metric-dual one-form.

Reasons NOT to use ict:

*

*A vector is a very different geometric object from a one-form.

*The Euclidean angle is periodic, whereas the Minkowski-angle, better known as the rapidity ("velocity parameter"), increases monotonically without bound.

*Hiding the Lorentzian signature (- + + +) hides the light-cones that encode the causal structure.

*No one has discovered a way to use this in general relativity for a general curved spacetime manifold.
and thus conclude:
"If '$x^4 = ict$' cannot be used there, it will not be used here" [in this book Gravitation].

See page 19 of this 20-page excerpt at http://laplace.physics.ubc.ca/000-People-matt/200/gravitation.pdf.
In my opinion, disadvantage #3
concerning the causal structure
is the most important reason not to use it.


text:
Q: $(<\kappa)$-closure for Prikry forcing A p.o. $\mathcal{P}$ is $(<\kappa)$-closure, if for every decreasing sequence of  $<\kappa$ conditions in the forcing $p_0 \geq p_1 \geq \cdots$,
there is a condition that is below all of them. Prikry forcing $\mathcal{P}$ is the set of pairs $(s,A)$ where s is a finite subset of a
fixed measurable cardinal $\kappa$, and $A$ is an element of a fixed filter $D$ on $\kappa$. A condition $(s,A)$ is stronger than
$(t, B)$ if $t$ is an initial segment of $s$ and $A \cup (s-t) \subseteq B$. Why doesn't Prikry forcing have this property? Could someone help me
 out with this?

A: Consider the conditions $(s_i, \kappa)$ where $s_i=\{0, . . . , i\}$ for $i\in\omega$. This is a sequence of $\omega$-many conditions, and clearly $(s_{i+1}, \kappa)\le (s_i, \kappa)$, but there is obviously no single condition below all the $(s_i, \kappa)$: were $(p, A)$ such a condition, then $p$ would have to be infinite, which contradicts the definition of condition.
Note that we could alter the forcing to consider conditions of the form $(p, A)$, with $A$ as above, and $p$ a subset of $\kappa$ of size $<\kappa$. This forcing would then be $<\kappa$-closed (depending, I guess, on the filter $D$), but this is a very different forcing.


text:
Q: Prove explanation for exponential growth I'm currently learning about Algorithms and Data Structures, and I have a proof in my lecture notes that I don't understand.

The Theorem:
  $n^d \in o((1+\epsilon)^n)$ with $\epsilon >0$ and $n,d \in \mathbb{N}$.
"The Proof": $\lim_{n \rightarrow \infty}\frac{n^d}{(1+\epsilon)^n} = 0$

I don't really know why this "statement" is enough to prove our theorem. I know about limits etc. from calculus but I don't know why we can use this knowledge here.

A: From the definition of little-O notation,

$$f \in o(\phi) \text{ provided that } f/\phi \to 0 \tag{*}\label1$$

In your "theorem", take $f: n \mapsto n^d$ and $\phi: n \mapsto (1+\epsilon)^n$ and apply \eqref{1}.$\tag*{$\square$}$


text:
Q: Delete Multiple records with checkbox in codeIgniter Create an item table
CREATE TABLE IF NOT EXISTS `items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

then step 2:
Add routers in application/config/routes.php
add these line
$route['item'] = "item";
$route['itemDelete']['post'] = "item/deleteAll";

Then step 3:
Create Item Controller. We will create this controller with deleteAll() and index(). For this, we will create an item.php file and then add the code, which is described as follows:
<?php
defined('BASEPATH')OR exit('No direct dcript not allowed');
class Item extends CI_Controller{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    public function index(){
        $data['data']=$this->db->get("items")->result();
        $this->load->view('item',$data);
    }
    public function deleteAll(){
        $ids=$this->input->post('ids');

        $this->db->where_in('id', explode(",", $ids));
        $this->db->delete('items');

        echo json_encode(['success'=>"Item Deleted Successfully."]);
    }
}
?>

Then step 4:Create a View file with the name item.php view file will be created in application/views/item.php
<!DOCTYPE html>

    <title>Delete Multiple Records with checkbox</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

CodeIgniter 3 - Delete Multiple records with checkbox

        <button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="/itemDelete">Deleted All Selected</button>

                    <input type="checkbox" id="master">
                    Title
                    Description

                <?php foreach($data as $item){?>

                        <input type="checkbox" class="sub_chk" data-id="<?php echo $item->id; ?>">
                        <?php echo $item->title; ?>
                        <?php echo $item->description; ?>

                    <?php } ?>

Then Error shows this:: Failed to load resource: the server responded with a status of 404 (Not Found)

A: You can't define routes like that in CodeIgniter 3.
You need to remove ['post'] from the itemDelete route.
$route['itemDelete'] = "item/deleteAll";

However, if you did want to limit that route to only POST requests, I suppose you could do something like :
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $route['itemDelete'] = "item/deleteAll";
}


text:
Q: Fixing a php retrieval using an Arduino sketch. Was working, now broken As the title suggests, I have an Arduino sketch set up to reach out to my web server using SSL, intending to retrieve an output value from a php script.  It was working up until around 2am MST on Thursday, September 19th 2019, but sometime over the next eight hours, it stopped.  My hosting provider made significant updates that morning and I think there's now an incompatibility somewhere.  Below, I'm not including all of the code, just the pieces that should be relevant.  I've excluded the pieces about establishing a connection to wifi, my NTP configuration and the pieces about using the returned value in NeoPixel.  I set client.setInsecure because my cert changes pretty frequently, and so does the fingerprint.  This also worked prior to server maintenance.  The fingerprint displayed is an older one.  It's possible that some of this code is unnecessary, but I found that if I took out the lines dealing with fingerprint, the connection failed.
If I reach the URL from a browser, I get the correct number returned, but with the Arduino, I'm getting the DOCTYPE line instead.  I originally had HTTP/1.0 in my code, and it was working.  After the issue started, neither works, 1.0 or 2.0.
My hosting provider says the following:
Apache Version  2.4.39
PHP Version     7.3.8
Instead of getting a simple number back, I'm getting this:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

Sketch:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

const char* host = "battletech-live.net";
const int httpsPort = 443;
String url = "/assets/scripts/php/checkTasks.php?action=getRows&uid=esp8266";
// SHA1 fingerprint of the certificate
char fingerprint[] PROGMEM = "44 DD B9 73 04 F8 EE 6B 0A 01 76 F2 98 34 F7 DE 43 60 11 54";

void setup() {
    Serial.begin(115200);
    WiFiClientSecure client;
    client.setInsecure();

    if (client.connect(host, httpsPort)) {
        Serial.println("connected");

        String request = String("GET ") + url + " HTTP/1.0 \r\n" +
                "Host: " + host + "\r\n" +
                "Connection: close\r\n\r\n";
        client.print(request);
        String line = client.readStringUntil('\n');
        Serial.println(line);
    } else {
        Serial.println("connected failed");
    }
}

void loop() {
    getPendingTasks();
}

void getPendingTasks() {
    WiFiClientSecure client;
    client.setInsecure();
    client.setFingerprint(fingerprint);
    if (client.connect(host, httpsPort)) {
        String request = String("GET ") + url + " HTTP/1.0 \r\n" +
                "Host: " + host + "\r\n" +
                "Connection: close\r\n\r\n";
        client.print(request);
        String line = client.readStringUntil('\n');
        Serial.println(line);
    }
}


text:
Q: Are the names of the textboxes inside a stack panel global variables? I would like to dynamically create a series of StackPanels which include several TextBoxes and TextBlocks. I need to be able to get their values, so do I have to make their names globally unique or just unique within the StackPanel?

A: You cannot access to the TextBoxes which is added to the StackPanel children collection like a normal TextBox. But you can get their values by their name like this:
private static string GetChildValue(Panel panel, string name)
{
    var children = panel.Children;

    foreach (var child in children)
    {
        if (!(child is TextBox))
            continue;

        var textBox = (TextBox)child;
        if (textBox.Name.Equals(name))
            return textBox.Text;
    }

    return string.Empty;
}

private static void DoSomething()
{
    var stackPanel = new StackPanel();
    stackPanel.Children.Add(new TextBox { Name = "TextBox1", Text = "TextBox1 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox2", Text = "TextBox2 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox3", Text = "TextBox3 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox4", Text = "TextBox4 Value" });

    var textBox1Value = GetChildValue(stackPanel, "TextBox1");
}