text:
Q: How to make 3d bar plot in Python I have a data file like the following:
         Time   THR-1   ALA-2   PRO-3   VAL-4   PRO-5   MET-6   PRO-7   ASP-8   LEU-9   LYS-10  ASN-11  VAL-12  LYS-13  SER-14  LYS-15  ILE-16  GLY-17  SER-18  THR-19  GLU-20  ASN-21  LEU-22  LYS-23  HIS-24  GLN-25  PRO-26  GLY-27  GLY-28  GLY-29  LYS-30  VAL-31  GLN-32  ILE-33  ILE-34  ASN-35  LYS-36  LYS-37  LEU-38  ASP-39  LEU-40  SER-41  ASN-42  VAL-43  GLN-44  SER-45  LYS-46  CYS-47  GLY-48  SER-49  LYS-50  ASP-51  ASN-52  ILE-53  LYS-54  HIS-55  VAL-56  PRO-57  GLY-58  GLY-59  GLY-60  SER-61  VAL-62  GLN-63  ILE-64  VAL-65  TYR-66  LYS-67  PRO-68  VAL-69  ASP-70  LEU-71  SER-72  LYS-73  VAL-74  THR-75  SER-76  LYS-77  CYS-78  GLY-79  SER-80  LEU-81  GLY-82  ASN-83  ILE-84  HIS-85  HIS-86  LYS-87  PRO-88  GLY-89  GLY-90  GLY-91  GLN-92  VAL-93  GLU-94  VAL-95  LYS-96  SER-97  GLU-98  LYS-99  LEU-100 ASP-101 PHE-102 LYS-103 ASP-104 ARG-105 VAL-106 GLN-107 SER-108 LYS-109 ILE-110 GLY-111 SER-112 LEU-113 ASP-114 ASN-115 ILE-116 THR-117 HIS-118 VAL-119 PRO-120 GLY-121 GLY-122 GLY-123 ASN-124 DA-1    DA-2    DA-3    DC-4    DA-5    DT-6    DG-7    DT-8    DT-9    DA-10   DA-11   DA-12   DC-13   DA-14   DT-15   DG-16   DT-17   DT-18   DT-19   DA-1    DA-2    DA-3    DC-4    DA-5    DT-6    DG-7    DT-8    DT-9    DT-10   DA-11   DA-12   DC-13   DA-14   DT-15   DG-16   DT-17   DT-18   DT-19
          0.000         84.841          0.274          8.595         -4.939          1.713         -1.704          0.768       -127.825          5.554        108.207          5.297          8.390        212.124          2.830         39.479          8.168          0.458          8.848          6.897        -83.882         29.016          9.647        308.856          6.400         32.481         11.327         10.372          0.247         -3.669         45.391          7.648         -6.990         16.870         11.946         18.778         29.161        127.841         -1.885        -49.943          4.716          6.552         16.029          4.803          7.307          5.423         35.449         -1.362          0.703          0.817          5.544        -14.168         -2.450          0.138         10.984          2.680         -0.238         -0.204         -1.814         -0.273          0.971         -0.256          2.553         -1.172          0.337          0.659         -3.890          8.570          1.180          2.319        -10.711          0.433          0.320          7.904         -0.021          1.672         -0.895         -1.804         -0.317          0.233          0.013          1.462         -1.310         -3.139         -1.453         -4.536          0.559         59.050        -10.891          3.089          5.579          9.818          6.599         -1.635        -34.622          2.576         14.145          9.062        -82.518         51.319         -5.944        -42.734         -0.065          5.200        -18.819         -1.670          0.354         -0.142         -0.938         -4.108         -0.582         -0.511         -0.452          0.763        -21.291          2.587         -5.088         -0.458          5.958         -0.746         -0.587          0.600          6.134          9.432        -47.476          0.517         -0.958         -1.246          0.005         -1.422         -5.105         -2.815         -6.459         -1.618         56.055        117.408         92.845         60.554         -6.065         -9.293         -3.752         -5.407         -1.491         -4.924         -0.944         13.894         32.688         15.937          2.866         -0.934         25.169          1.291         -5.292         -8.727          5.852         -8.092        -40.334        -18.542          0.468         -6.011         -2.043         -1.305         -0.959
         10.000        127.315          0.993         15.230         12.627          0.804          0.642         -2.810       -101.634          5.500        114.097          3.368          9.100        162.819        -10.033         39.935          6.920          9.887          9.732          4.997        -79.368         25.134         -5.714        307.359          5.781         34.996          8.885          7.234         -5.875         -0.094         31.674          3.963         -8.064         14.720         12.726         25.431         25.011        108.108         -0.293        -63.815          4.442          1.071         12.768          2.871          1.451          2.179         30.666         -2.066          0.995          1.496          3.384         -1.398         -0.776         -0.101          5.159          1.092         -0.829         -0.205         -0.125          1.054          0.574         -0.291          1.106          0.875         -1.106         -1.955          1.153          4.273          0.628          1.305         -5.547          0.755          0.126          3.704          0.925          0.074         -0.516          3.643         -0.133         -0.064          0.717          0.547          0.197         -0.408         -0.912         -1.296          0.508         35.027         -3.056         10.216          5.885          8.755         -0.792         -1.442        -28.498          2.122          6.803          1.344        -58.583         47.395         -2.332        -32.863         -2.826          5.311        -23.087          6.478         -0.205          0.288         -0.373          4.358          0.362         -1.010         -0.352          2.271        -13.406         -2.747         -4.616         -2.275          3.943         -4.391         -7.063         -0.599          3.081         12.778        -40.043          0.327         -1.940         -2.012          2.592          2.909          1.041          0.658         -0.868         -3.206         16.355        109.843        107.372         63.801          8.499          0.931          2.639         -0.884          0.214          1.880         -2.379          8.408         12.583         10.883         23.083          7.955         31.277          0.539          3.992         -0.887         12.925         -4.248        -31.420         -4.812          1.125          3.287         -0.532         -0.438          0.291
         20.000         84.636          5.538         15.954         10.437          0.439          1.773         -1.913        -96.625          5.704        132.598         -0.572          6.877        174.628         -9.400         32.417         -0.264          3.812          6.175          5.056        -62.617         25.479         -1.171        288.031          8.114         37.636         10.461          4.612         -3.521         -0.335         37.957          6.596        -11.250         12.510         11.557         21.128         37.344        135.293         -2.163        -80.896          0.912          1.963          1.101          2.815          6.051          5.374         28.443          0.905          1.734          0.813          5.060         -1.365          1.653         -0.415          4.862          1.758         -0.572         -0.339          0.423          0.759          1.036         -0.543          0.783          0.102         -0.971         -1.529         -1.595          5.519          0.587          1.306         -2.813          0.605          0.761          4.542          0.698          0.767         -0.050          2.201         -0.084          0.563          0.357          0.422          0.642          0.588         -1.426         -1.375          1.455         31.332         -3.390         16.696         15.616         13.449          0.096         -2.711        -24.804          1.969          4.095          2.078        -58.303         47.776         -1.047        -22.013         -2.270          4.204        -11.059          3.952          0.382         -0.863          0.010          3.473          0.375         -1.301         -0.037          1.396        -14.392         -2.887         -5.915         -2.315          5.888         -3.365         -5.950         -2.439          4.814          7.125        -46.399          4.393          5.939         -0.508          2.461          2.562         -0.717          4.225          3.642          4.664         27.859        104.835        114.077         74.730          8.410          1.862          0.061         -1.288         -1.181          2.106          4.346          9.017         29.050         -5.088         14.618          4.149          5.062          1.369         15.083          9.537         18.306         -1.165         -8.966          3.864          3.523          7.232          4.275          1.888          4.708
         30.000         91.953         11.008         15.794         12.043          0.596          4.611          1.048        -70.764          7.475         72.100          1.360          6.891        150.455         -7.180         11.932          4.845          9.519          6.184          4.684        -57.283         24.797          0.393        275.626         14.021         22.233         10.877          0.934         -7.551         -2.439         27.929          5.098         -6.797         12.784         12.140         19.698         25.762        108.882          0.267        -54.801          1.470          2.139          1.302          1.996          2.021          3.090         22.690          0.669          1.347          0.113          5.378         -1.570          0.585         -0.143          1.156         -0.050         -1.086          0.148         -0.017         -0.417         -0.201         -1.304          0.808         -0.950         -0.958         -1.741          0.200          2.846          0.633          1.279         -3.693          0.338         -1.058          3.651          0.009          0.202         -1.009          0.037         -0.245         -0.183         -0.615          0.192         -0.386          0.426         -1.800         -2.009          0.496         33.517         -4.213         15.421         16.942         14.559          0.109         -2.553        -25.113          1.199          2.074         -0.265        -56.399         40.657         -0.746        -24.020         -1.986          3.400         -9.631          1.384          0.502         -1.001          0.547          2.622         -0.201         -1.062         -0.916          0.493        -14.621         -2.660         -4.459         -1.066          3.788         -4.289         -7.086          2.460          5.341          8.759        -39.474         -0.051          2.116          0.498          1.267          0.728          1.071          1.155          0.824          3.214         32.413        124.028        144.011         80.795         11.199          5.365          1.969          0.659          2.780          2.311          1.671         14.244         33.170         -6.859         -6.106         13.690          4.742          0.645         17.301         12.245         15.829        -11.976        -22.289          3.100          1.725          5.538          5.041          3.517         -0.205

The first column needs to go in the x axis, whereas the titles from the second column to the end would be the y axis, and the values from the second column to the last column would be the height of the bars (i.e. the z axis).
I need to do this in Python and I am a newcomer. Can you please help?
I have tried the following code and it's of no use:
#!/usr/bin/python

import numpy as nm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

data=nm.loadtxt('contrib_pol.dat')
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')

ax.bar(data[:,0],data[0,:],data[:,1:124])
plt.show()

del data

It's flashing this error message:
Traceback (most recent call last):
  File "./barplot.py", line 14, in <module>
    ax.add_collection3d(data[:,0],data[0,:],data[:,1:124])
  File "/usr/lib/python2.7/dist-packages/mpl_toolkits/mplot3d/axes3d.py", line 2210, in add_collection3d
    Axes.add_collection(self, col)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1669, in add_collection
    label = collection.get_label()
AttributeError: 'numpy.ndarray' object has no attribute 'get_label'

Also, I think I'm not properly selecting the columns as per the requirement. Please help.

A: The following should help to get you started:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Extract the header from the data
#import csv
#with open('contrib_pol.dat', 'rb') as f_data:
#    header = next(csv.reader(f_data, delimiter='\t'))[1:]

data = np.loadtxt('contrib_pol.dat', skiprows=1)

x = []
y = []
dz = []

cols = ['red', 'blue', 'yellow', 'green']
colours = []

for r, row in enumerate(data):
    for c, col in enumerate(row[1:], start=1):
        x.append(row[0])
        y.append(c)
        dz.append(col)
        colours.append(cols[r])

z = np.zeros(len(y))
dx = np.ones(len(y))
dy = np.ones(len(y))

ax3d = plt.figure().gca(projection='3d')
ax3d.bar3d(x, y, z, dx, dy, dz, color=colours)

ax3d.set_xlabel('Time')
ax3d.set_ylabel('Col')
ax3d.set_zlabel('Value')

plt.show()

This would give you an output graph as follows:

I am sure numpy could be better used to extract the required data.


text:
Q: setcellValue limitations in PHPExcel Im using setcellValue to populate my excel file, but the moment it reaches A99, it throws this error
    Fatal error: Uncaught exception 'Exception' with message 'Column string index can not be longer than 3 characters.'

is it a limitation that phpexcel has, or am i making a mistake by populating my sheet in this format
    $objPHPExcel->getActiveSheet()->setcellValue($alpha[$alpha_count] . $spreadsheet_count, $row['comment']);

A: Maybe you could try with setCellValueByColumnAndRow() :
setCellValueByColumnAndRow($alpha_count, $spreadsheet_count, $row['comment']);

A: No it doesn't mean that that PHPExcel supports only 100 rows, PHPExcel supports up to 1,048,576 rows and up to 16,384 columns (same as the OfficeOpenXML format for xlsx files)... dependent on memory.
Your column string index that the error message refers to is the column reference (the A of A100).
Double check exactly what the value of $alpha[$alpha_count] is, I suspect it isn't what you think.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Router rendering the component on the same page rather than rendering in a new page Router is rendering the page on the same page than to generate a new page. What might be the problem? Whenever I click the link Polls , it renders the page only there but the URL is shown as changed in the browser.
Polls.js
import React from 'react';
import {Link} from "react-router-dom";

class Polls extends React.Component{
    render() {
        return(

Polls Page

This is Polls Page

        )
    }
}

export {Polls}

Choices.js
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import {Polls} from "./Polls";

class ShowChoice extends React.Component{
    render() {
        return(
            <Router>
                <Link to='/polls'>Polls</Link>
                <Route path='/polls' component={Polls} />
            </Router>
        )
    }
}

And the ShowChoice is rendered inside APP
flow of rendering is like
index>APP>ShowChoices

(link to the Polls inside ShowChoices)
and my APP.js is
class App extends React.Component {
    render() {
        return (
            <ShowChoice formResult={this.state.result} />
        );
    }
}
export default App;

A: Try to change path and use exact like that
<Route exact path="/polls" component={Polls}/>

More info: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md

A: You have added your Route in ShowChoice component. Your ShowChoice component is then added to App component.
So whenever yo click the Link, your URL will get changed but it will render the component in App component only. So your App component's content is also visible to you.
To make it feel like you get new page when you click the Link, you need to combine all the Route at top level, may be in a separate component,
const Routers = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/polls" component={Polls} />
      </Switch>
    </BrowserRouter>
  )
}

So this will render App component by default on first render, which will render ShowChoice component added in App component and you will see Link for your Polls component.
Now clicking on Link, you will get new page of your Polls component.
Demo


text:
Q: How to return dynamic array to Python using ctypes? Hi i want to return a dynamic array to python from c funtion.
this is my c funtion
extern "C" uint32_t* function(){
uint32_t *u_id;
  uint32_t size = common::size();
  u_id = (uint32_t*)malloc( size*sizeof(uint32_t) );
  for (uint32_t i = 0; i < size; i++) {
    u_id[i]
  }
  return u_id;

I follow the example and write these python codes. However, if i write in this way, the result is limited to size of 10. How can I adapt it to dynamic size?
import ctypes

mylib = ctypes.CDLL('./library.so')
mylib.function.restype = ctypes.uint*10
res = mylib.function()


text:
Q: Reverse Engineering Proguarded-apk I have a task from my lecturer to do some reverse engineering. After doing some tutorials, I can reverse engineer basic APK file (with no proguard/dexguard).
My task is finished, but I'm getting curious now. I tried to search this on Google but nothing good/useful was found.
Is it possible to reverse engineering an APK with proguard and how to do it?
Edit (dont know why people are voting to close this question, so this is what i've done so far) :
I can reverse engineered a proguarded apk, but the variables are changed (which made my head hurts) :
  TextView I;
  EditText J;
  EditText K;
  EditText L;
  CheckBox M;

Can someone help me so i can perfectly reverse engineered it?

A: it's possibile and obviously more difficult.
If it's your own .apk, or you have access to the project, then you can use the proguard mapping located here:
<project_root>/bin/proguard/mapping.txt

otherwise it's just more difficult and you'll need to get used to read and unserstand a lot of guarded bytecode.
Defenetly not easy but possible if you, for instance, have an old version of the apk not guarded.


text:
Q: Condition number of a block matrix Let $\mbox{cond} (M) := \frac{\sigma_1 (M)}{\sigma_n (M)}$ be the condition number of matrix $M$. Is
$$\mbox{cond} ([A,B]) \leq \mbox{cond}(A) + \mbox{cond}(B)$$
true? And is this true for $n \times m$ rectangular matrices? Let's  consider $3$ different cases:

*

*$n<m$

*$n=m$

*$n>m$

A: This could be true if $n\leq m$ at least in the case when all matrices involved have full rank equal to $n$. Because the singular values of $[A,B]$ are the square roots of the eigenvalues of $AA^T+BB^T$, then we have
$$
\begin{split}
\sigma_n^2([A,B]) &= \lambda_n(AA^T+BB^T)
=\min_{\|x\|_2=1}x^T(AA^T+BB^T)x\\&\geq\min_{\|x\|_2=1}x^TAA^Tx=\lambda_n(AA^T)=\sigma_n^2(A)
\end{split}
$$
Similarly,
$$
\begin{split}
\sigma_n^2([A,B]) &= \lambda_n(AA^T+BB^T)
=\min_{\|x\|_2=1}x^T(AA^T+BB^T)x\\&\geq\min_{\|x\|_2=1}x^TBB^Tx=\lambda_n(BB^T)=\sigma_n^2(B)
\end{split}
$$
and hence
$$
\sigma_n([A,B])\geq\max\{\sigma_n(A),\sigma_n(B)\}.
$$
Similarly, variational characterisation of singular values also implies that
$$
\sigma_1^2([A,B])\leq\sigma_1^2(A)+\sigma_1^2(B).
$$
Indeed,
$$
\begin{split}
\sigma_1^2([A,B]) &= \lambda_1(AA^T+BB^T)
=\max_{\|x\|_2=1}x^T(AA^T+BB^T)x\\&\leq\max_{\|x\|_2=1}x^TAA^Tx+\max_{\|x\|_2=1}x^TBB^Tx=\lambda_1(AA^T)+\lambda_1(BB^T)\\&=\sigma_1^2(A)+\sigma_1^2(B)
\end{split}
$$
Hence
$$
\mathrm{cond}^2([A,B])\leq\frac{\sigma_1^2(A)+\sigma_1^2(B)}{\max\{\sigma_n^2(A),\sigma_n^2(B)\}}\leq\frac{\sigma_1^2(A)}{\sigma_n^2(A)}+\frac{\sigma_1^2(B)}{\sigma_n^2(B)}\leq\mathrm{cond}^2(A)+\mathrm{cond}^2(B)
$$
and
$$
\mathrm{cond}([A,B])\leq\sqrt{\mathrm{cond}^2(A)+\mathrm{cond}^2(B)}
\leq\mathrm{cond}(A)+\mathrm{cond}(B).
$$
For $n>m$, it's generally not true (still assuming full rank of both $A$, $B$, and $[A,B]$). As an extreme example, take $m=1$. Then $\mathrm{cond}(A)=\mathrm{cond}(B)=1$ but $\mathrm{cond}([A,B])$ can be arbitrarily large. Consider, e.g., $A=[1,0]^T$ and $B=[1,0.001]^T$.
The rank-deficient case is a bit more difficult if you considered $\mathrm{cond}(A)=\sigma_1(A)/\sigma_r(A)$, where $r$ is the rank of $A$ (this is how the condition number is usually defined when $A$ does not have full rank). The trouble here is not with the upper bound on $\sigma_1([A,B])$ but with the lower bound which does not generally hold. Again, as an extreme example, consider $A$ and $B$ of the case 1) and 2) and augment them with a sufficient number of zero rows to convert it to the case 3) (which we know where the statement is false).


text:
Q: Wireguard don't work with VRRP I try to use Wireguard on a firewall with VRRP (based on Keepalived). The firewall blocks all the communications except to the VRRP address on port 51820 and the valid established connections.
Wireguard works well if I don't use VRRP.
When I try to use VRRP, the packet from client go to VRRP address as attended. But Wireguard try to reply from the physical IP address (and not the VRRP one), which is blocked on OUTPUT by the firewall as the IP change.
Do you know how Wireguard should be configured to reply by the VRRP address and not the physical one ?
I would not allow to answer by the physical IP address as clients firewall may block the connection if they do connection tracking too.
I try to see if a SNAT can help, to rewrite the physical IP to VRRP one, but it is not allowed put it in OUTPUT or PREROUTING nat rules.
Some logs :
on the client (IP 10.3.3.2) :
11:41:09.011209 IP 10.3.3.2.47755 > 10.3.3.254.51820: UDP, length 148
11:41:14.131337 IP 10.3.3.2.47755 > 10.3.3.254.51820: UDP, length 148

on the firewall (10.3.3.252 physical, 10.3.3.254 VRRP) :
Jan 12 11:41:09 FW-DEV1 kernel: [ 3950.406083] OUTPUT: IN= OUT=enp0s9 SRC=10.3.3.252 DST=10.3.3.2 LEN=120 TOS=0x08 PREC=0x80 TTL=64 ID=7125 PROTO=UDP SPT=51820 DPT=47755 LEN=100
Jan 12 11:41:14 FW-DEV1 kernel: [ 3955.526617] OUTPUT: IN= OUT=enp0s9 SRC=10.3.3.252 DST=10.3.3.2 LEN=120 TOS=0x08 PREC=0x80 TTL=64 ID=7878 PROTO=UDP SPT=51820 DPT=47755 LEN=100

Edit: Add NAT
I put a NAT on VRRP interface and it almost solve the issue.
iptables -t nat -A PREROUTING -d WGIP/32 -p udp -m udp --dport 51820 -j DNAT --to-destination PHYSICALIP

But I need to open the filter rule with the PhysicalIP address. It means that the VRRP and the PHYSICALIP are open from outside. I cannot put a DROP rule before the nat rule to forbid the connection except to  VRRPIP


text:
Q: How can I change the image url of an image based on #var=test variable? I'm trying to change an image's imageurl on an aspx asp.net c# page based on a variable from #var=1` (or 2, or 3, or 4)
I know nothing about javascript unfortunately which is what I've been told I need. Can anyone point me at a novice based script I can try to learn via implementation?

A: Your question is very vague so I'm not sure exactly what you need... I'm just going to write some code and see if it's close to the mark
Try something like

EDIT: Based on your comment, you're looking for the image to update even if the hash changes after the page has loaded. For that, you'll need code similar to the following:
var updateImageWhenHashChanges = function()
{
  theImage = document.getElementById("someUniqueIdYouMakeUp");
  if(window.location.hash == "#var=1")
  {
    theImage.src = "/some/image.jpg";
  }
  else if(window.location.hash == "#var=2")
  {
    theImage.src = "/some/other/image.jpg";
  }
  // Tell the window to call updateImageWhenHashChanges() again in 500 miliseconds:
  window.setTimeout(updateImageWhenHashChanges,500);
}
updateImageWhenHashChanges();

For more information, read about window.setTimeout.

A: Unfortunately, the answer is going to be as vague as the question.
It seems clear that you want to know how to modify the src attribute of an image.
Given this image in your HTML:

You could use this javascript code to get the image by its ID, and change the src attribute.

Just place the script at the bottom of your HTML body tag, and it should work.
Please note, that this is a pure javascript solution. If you're going to use jQuery, it may be worth taking a jQuery approach depending upon your actual scenario.


text:
Q: Cómo mostrar imágenes de una carpeta usando PHP Necesito mostrar las imágenes de una carpeta, pero no lo consigo. Este es mi codigo:
<?php
$directorio = opendir("C:wamp64/www/Andina/pics/");
while ($imagen = readdir($directorio)) {
    if (is_dir($imagen)) {
        echo $imagen."
";
    }
    else
    {
        $completo = $directorio.$imagen;
        echo $imagen." - ".''."  -  " ;
        echo '';
        echo "
" ;
    }
}
?>

A: Te recomiendo usar glob es algo mas sencillo de utilizar al momento de listar los ficheros de una carpeta
<?php
    $directorio = "C:wamp64/www/Andina/pics/";

    function printImagesDir($dir){
        $files = glob($dir.'*.{jpg,JPG,jpeg,JPEG,png,PNG}', GLOB_BRACE);
        foreach($files as $filename){
            $imgsrc = basename($filename);
            echo "";
        }
    }

    printImagesDir($directorio);
?>


text:
Q: iOS CAShapeLayer and shadows with Core Animation I would like to draw a graph with CAShapeLayer and set a pretty shadow on a background for some nice visual effect. With shadows, animation of my graph (straight line to graph modeled using some data) really slows down!. I read about shadowPath property and decided to use it, but the problem is, despite the fact wether I close the CGMutable path or not, it seems like CoreAnimation closes it, and this shadow I get, instead of a line, is rather a polygon. Looks really ugly.
Help!


text:
Q: Sum of jacobi symbols is zero
Let $m = p_1\cdots p_k$, where $p_i \ne p_j$ for all $i\ne j$.
  Prove that: $$\sum_{a\in\mathbb{Z}_m^\star} (a/m)= 0$$

I've noticed that $$(m-a/m) =(-a/m) = (-1/m)(a/m)$$
Now, $(-1/m) = (-1)^{\frac{m-1}{2}}$. If I knew that $(-1/m) = -1$ then the proposition holds.
$m-1$ is even so it can be of the form $4k$ or $4k+2$. Now, if it has the form $4k+2$ then $\frac{m-1}{2}$ must be odd and we're done.
I couldn't prove the last assumption though. Is my idea correct? Is there another approach?

A: If $\mathbb{Z}/(m\mathbb{Z})^*$ is a cyclic group we have as many quadratic residues as quadratic non-residues, since the set of quadratic residues is a subgroup of index $2$, given by the even powers of some generator.
If you prove the statement in the case $m=2^k$ and invoke the Kronecker decomposition theorem, the statement in its general case follows from the multiplicativity of the Jacobi symbol.
A simpler approach is to notice that once we have some $b\in\mathbb{Z}/(m\mathbb{Z})^*$ such that $\left(\frac{b}{m}\right)=-1$, by reindexing through $a=ba'$ we get that the original sum equals it opposite, hence it equals zero.


text:
Q: Large scale deletions from STL vector crashing my binary My binary is crashing. On running the core dump, I found the following :
#0  0x00a6a363 in memmove () from /lib/tls/libc.so.6
(gdb) frame 1
#1  0x083a108c in std::__copy_trivial<piola::piolaOrderBook*> (__first=0xb277f2c4, __last=0xb277f2bc, __result=0xb277f2c0)
    at /usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h:258
258           std::memmove(__result, __first, sizeof(_Tp) * (__last - __first));
(gdb) frame 2
#2  0x083a0ad6 in std::__copy_aux2<piola::piolaOrderBook*> (__first=0xb277f2c4, __last=0xb277f2bc, __result=0xb277f2c0)
    at /usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h:279
279         { return std::__copy_trivial(__first, __last, __result); }
(gdb) frame 3
#3  0x083a02d1 in std::__copy_ni2<piola::piolaOrderBook**, __gnu_cxx::__normal_iterator<piola::piolaOrderBook**, std::vector<piola::piolaOrderBook*, std::allocator<emapi::EmapiOrderBook*> > > > (__first=0xb277f2c4, __last=0xb277f2bc, __result=
      {_M_current = 0xb277f2c0})
    at /usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h:296
296           return _OutputIterator(std::__copy_aux2(__first, __last, __result.base(),
(gdb) frame 4
#4  0x0839f1b0 in std::__copy_ni1<__gnu_cxx::__normal_iterator<piola::piolaOrderBook**, std::vector<piola::piolaOrderBook*, std::allocator<piola::piolaOrderBook*> > >, __gnu_cxx::__normal_iterator<piola::piolaOrderBook**, std::vector<piola::piolaOrderBook*, std::allocator<piola::piolaOrderBook*> > > > (__first={_M_current = 0xb277f2c4}, __last=
      {_M_current = 0xb277f2bc}, __result={_M_current = 0xb277f2c0})
    at /usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h:317
317           return std::__copy_ni2(__first.base(), __last.base(),
(gdb) frame 5
#5  0x0839d676 in std::copy<__gnu_cxx::__normal_iterator<piola::piolaOrderBook**, std::vector<piola::piolaOrderBook*, std::allocator<piola::piolaOrderBook*> > >, __gnu_cxx::__normal_iterator<piola::piolaOrderBook**, std::vector<piola::piolaOrderBook*, std::allocator<piola::piolaOrderBook*> > > > (__first={_M_current = 0xb277f2c4}, __last={_M_current = 0xb277f2bc},
    __result={_M_current = 0xb277f2c0})
    at /usr/lib/gcc/i386-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_algobase.h:358
358            return std::__copy_ni1(__first, __last, __result, __Normal());
(gdb)

Most of this is cryptic to me, however on looking up memmove it seems like the code crashed because it could not handle the deletions from the vector (since deleting from a vector is a very heavy operation for large vectors) ?
Am I correct ? If yes, how can I fix this issue (apart from fixing the design of course) ?
The code is here :
for (orderbkIterator = vOrderBook.begin(); orderbkIterator != vOrderBook.end(); orderbkIterator++)
    {

        if (  (*(*orderbkIterator)->getOrderBookId()) == *(TradableInst->getOrderBookId()) )
        {
            long long a = (*(*orderbkIterator)->getOrderBookId());
            ADDVLOG(LOG_INFO, "Removing record (%lld) from vOrderBook", a );
            vOrderBook.erase(orderbkIterator);
        }

A: From std::vector::erase():

Iterators and references to the erased elements and to the elements between them and the end of the container are invalidated. Past-the-end iterator is also invalidated.

so orderbkIterator will be invalid when next incremented if the erase() was called. Change the structure of the loop as erase() returns the next iterator after the iterator that was removed, meaning only increment if an erase() did not happen:
for (orderbkIterator = vOrderBook.begin(); orderbkIterator != vOrderBook.end();)
{
    if (...)
    {
        orderbkIterator = vOrderBook.erase(orderbkIterator);
    }
    else
    {
        ++orderbkIterator;
    }
}

A: I'm pretty sure that
vOrderBook.erase(orderbkIterator);

will invalidate the iterator. Continuing the increment it will lead to undefined results.

A: The remove erase idiom will prevent many of the pitfalls with invalidated iterators.
Rewritting the loop using this idiom would look something like the following:
vOrderBook.erase(
  std::remove_if(vOrderBook.begin(), vOrderBook.end(), <unary-predicate>),
  vOrderBook.end());

The unary-predicate could be a lambda or a functor.


text:
Q: How can i control bin intervals in ggplot2? I cant correctly control if a bin is going from e.g. -10 to +10 or from 0 to 20 when I say binwidth = 20 i get the former but I have data that begins at 1 and I dont want the interval to go into the negatives.
Here is an example of my problem:
testData = data.frame(x=c(1,4,6,9,9))

ggplot(data=testData, aes(x=testData$x)) +
  geom_histogram(binwidth=3, aes(col=I("white"))) +
  scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10))

strange enough, if I use binwidth = 2 I end up with intervals like I want:
ggplot(data=testData, aes(x=testData$x)) +
  geom_histogram(binwidth=2, aes(col=I("white"))) +
  scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10))

How can I get my bins to go from 1..20, 21..40, etc. for a larger dataset?

A: You can do this by using the argument center of geom_histogram as follows:
# Make some random test data
testData = data.frame(x=runif(1000,min=1,max=110))
# Construct the plot
ggplot(data=testData, aes(x=testData$x)) +
  geom_histogram(binwidth=20,
                 center = 11,
                 aes(col=I("white"))) +
  scale_x_continuous(breaks=seq(1,max(testData$x) + 20, by = 20))

By specifying the binwidth and the center for one bin, you define that the bin should be 20 wide and be centered around 11. So the first bin will be 1 to 21.
I also added a seq() call to construct the x axis ticks without having to type all of them manually. The resulting plot is the following:


text:
Q: sort command in linux first sort special characters, than lower case and uppercase. I am using sort command for sorting in file.My data contains as follows.
abc.com
*.abc.com
abcd.com
ABC.com

I am using following sort command for sorting
sort -f -V filename

And It is giving me following result.
abc.com
ABC.com
abcd.com
*.abc.com

But I want following result
*.abc.com
abc.com
ABC.com
abcd.com

So I want that * should come first like mentioned above in my expected result.
I have tried various options in sort command but not successful.So Is there any option in sort command where I can get the expected result.

A: You need to use
sort -f -k1 filename


text:
Q: Cannot run an "initialise" function in Puppet after installing package OK I have been working on puppet for 12 months, I am deploying a manifest to install the "aide" package, but I cannot see any option to trigger the 'initialise' of aide after install of the package. There is no "notify" function on the "package" directive. How do I get this to work?

A: The notify parameter is a metaparameter and can be applied to any resource. Source:
https://puppet.com/docs/puppet/5.5/lang_relationships.html#refreshing-and-notification
https://puppet.com/docs/puppet/5.5/metaparameter.html
Typically, the ordering is as follows:
class myclass {

  package { 'myapp':
    ensure => present,
  }

  file { '/etc/myapp.conf':
    ensure  => file,
    ...
    notify  => Service['myapp'],
    require => Package['myapp'],
  }

  service { 'myapp':
    ensure => running,
    enable => true,
  }
}


text:
Q: symfony 1.4 - save dynamic values (choice form) How can I get the values of a dynamic choice field and save them ?
This is my function :
public function configure()
  {

    $query = FillableTable::getInstance()->createQuery('fal')->addWhere('0 = 1 ');

    $piecesChoices= RepaoTable::getInstance()->createQuery('rpo')->select('rpo.code_text')->execute();
    $choices = array();
    foreach ($piecesChoices as $choice)
        {
    $value = $choice->getCodeText();
    $choices[$value] = $value;
        }

    $this->widgetSchema['simple1'] = new sfWidgetFormDoctrineChoice(array('model'=> 'Simple1'));
    $this->widgetSchema['simple2'] = new sfWidgetFormDoctrineChoice(array('model'=> 'Simple2', 'query' => $query));
    $this->widgetSchema['code_text']= new sfWidgetFormChoice(array(
            'expanded' => true,
            'multiple' => true,
            'choices'=> $choices
       ));

//validation

    $this->validatorSchema....

//

A: I presume you are referring to saving the user-selected values from the code_text widget?
In your action, after the user POST/GETs your form you would have an array instead of a single value.
You can var_dump($request->getPostParameter('code_text')) to see what happens.
You can do whatever you want with those values then.


text:
Q: POST api/customers/ to register user Prestashop Email Invalid Im trying to register user to my Prestashop store through postman,
I use post mydomain/api/customers,
In body I use raw data like this:
    <?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <customer>
        <passwd>
            testpassword
        </passwd>
        <lastname>
            testlastname
        </lastname>
        <firstname>
            testfirstname
        </firstname>
        <email>
            testemail@mail.com
        </email>
    </customer>
</prestashop>

And I have error code that Customer -> Email is not valid,
When I use this xml as a body:
<customer>
    <passwd>
        testpassword
    </passwd>
    <lastname>
        testlastname
    </lastname>
    <firstname>
        testfirstname
    </firstname>
    <email>
        testemail@mail.com
    </email>
</customer>

I got response that passwd is required, anyone have any idea how do I work with this webservice api?

A: You are using wrong input xml; I am able to create customer with following request body. Make sure to add Prestashop tag as parent tag.
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
  <customer>
    <passwd>admin@123</passwd>
    <lastname>Doe</lastname>
    <firstname>John</firstname>
    <email>john.doe@yopmail.com</email>
  </customer>
</prestashop>


text:
Q: Inserting a string in a sliced string (Python) So I am pretty new in the programming world, I'm apologising in advance if that question has been answered a million time but I couldn't find an answer to my specific problem.
I'm making a simple password generator that take a list of words as input, for example:
test = ['carpe', 'diem']>
the desired output would be like
*7carZpe-hd_iemA:
So that's 2 randomly generated characters around and between each words and one in a random place in the word This second part is where i'm struggling.
In a terminal, when running python I can do :
test[0] = test[0][0:2] + '7' + test[0][2:]
So that carpe would now be ca7rpe and it works fine.
Here are the two function I wrote to make it :(I'm importing random and ascii_letters, digits, punctuation from string)
def random_generation(length):
    string = f'{ascii_letters}{punctuation}{digits}'
    string = list(string)
    random.shuffle(string)
    randomised = random.choices(string, k=length)
    randomised = ''.join(randomised)
    return randomised

def custom_generation(listOfWords):
    for words in range(0, len(listOfWords)):
        word = listOfWords[words]
        randomInsert = random.randint(0, len(word))
        word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

    for insertion in range(0, (len(listOfWords) * 2) + 1, 2):
        listOfWords.insert(insertion, random_generation(2))
    password = ''.join(listOfWords)
    return password

My guess is that I'm doing something wrong on the first for-loop but even after a couple modifications and try I couldn't find the way.
Thank you kindly !

A: If I am not mistaken your code is missing assignment of altered word back to list, try replacing
for words in range(0, len(listOfWords)):
    word = listOfWords[words]
    randomInsert = random.randint(0, len(word))
    word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

using
for words in range(0, len(listOfWords)):
    word = listOfWords[words]
    randomInsert = random.randint(0, len(word))
    listOfWords[words] = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

A: You are right. The mistake is in the first for loop.
When you do
word = listOfWords[words]

you are copying the list element into a new variable.
Anything that you do to this variable will not affect the list elements.
So all you have to do is, change
word = word[0:randomInsert] + random_generation(1) + word[randomInsert:]

to
listOfWords[words] = word[0:randomInsert] + random_generation(1) + word[randomInsert:]


text:
Q: Setting a property to a proxy-object of its type using reflection I am trying to use PropertyInfo.SetValue() on a Property.
I got the Value from that same Property using PropertyInfo.GetValue()
The property is of type MyObject.
When I try to use SetValue I get an exception: "Object does not match target type.". The reason beeing that the Value I got through GetValue() has a runtime type of MyObjectProxy, which inherits from MyObject.
I cannot assign an object of type MyObjectProxy to a MyObject Property and havent found a way to do so.
But  EF Core did it somehow, so shouldnt I be able to do it as well?
//Each object that implements IProfileKey is an entity with a foreign key of myObject
List<PropertyInfo> myProperties = GetPropertiesOfType(typeof(IProfileKey));

//Get values from all properties as IProfileKey
List<IProfileKey> myValues = myProperties.Select(x => (IProfileKey)x.GetValue(myObject)).ToList();
myProperty.GetValue(myObject);

MyContext.Remove(ofObject);
MyContext.SaveChanges();

UpdatePrimaryKeys(myValues);

foreach(int i = 0; i < myProperties.Count; i++)
{
    //Heres the problem
    //myProperties[i] is of type MyObject, while myValues[i] is of type MyObjectProxy
    myProperties[i].SetValue(myObject, myValues[i]);

}

MyContext.Add(myObject);
MyContext.SaveChanges();

The background is that I am trying to change the primary key of one of my objects in EF Core. For that I need to Delete the Object im trying to change, then change the key and add it again.
Now that object also has other objects referencing it, so I need to change their Keys as well. All these other objects are properties of type IProfileKey in my main object.
So my idea was to use generics to automatically find and update these properties.

A: So I didn't figure out how to assign a MyObjectProxy Object to a MyObject property.
But when changing the Primary key I thought I had to reassign the navigation properties that changed as well, but thats not the case, so I dont have to assign a MyObjectProxy Object to a MyObject property after all.


text:
Q: How to use VB.net with an Excel sheet to count and sort data Just like the title says, I've been using VB.NET to do various things on Excel and am kinda new. If i have an Excel sheet with various data including staff and things sold, how can i select 2 Columns and sort them so it counts how many of each items were sold by each person into a Messagebox or Listbox?
for eg, the output i'm looking for is something like
Staff   Sold       how many
NAME1 - PRODUCT1 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT2 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT3 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT4 - AMOUNTSOLDBYNAME1
NAME2 - PRODUCT1 - AMOUNTSOLDBYNAME2
NAME2 - PRODUCT2 - AMOUNTSOLDBYNAME2

and so on...

the furthest i've gotten is counting how many of each staff member there are in  1 column but i would like to go a step further on this and get 2 columns and count each product sold by each person but am unclear how to go about it.
Private Sub getexcelfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim excelfile As New OpenFileDialog()
    excelfile.ShowDialog()
    If (excelfile.ShowDialog() = DialogResult.Cancel) Then
        Return
    Else
        Dim file As String = excelfile.FileName
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet

        xlApp = New Excel.Application
        xlWorkBook = xlApp.Workbooks.Open(file)
        xlWorkSheet = xlWorkBook.Worksheets("PSSalesFullConnectionReport")

        Dim col As String = "N"
        For row As Integer = 1 To xlWorkSheet.UsedRange.Rows.Count - 1
            Dim elemValue As String = xlWorkSheet.Range(col & row).Text
            ListBox1.Items.Add(elemValue)
        Next

        MessageBox.Show(ReturnDuplicateListBoxItems(ListBox1))

        ListBox1.Items.Clear()

    End If

End Sub

Public Shared Function ReturnDuplicateListBoxItems(ByVal lBox As System.Windows.Forms.ListBox) As String
    Dim strReturn As New System.Text.StringBuilder
    Dim lItems As New Dictionary(Of String, Integer)
    Dim intCount As Integer = 0
    Dim strCurrentItem As String = String.Empty

    Try
        For Each nItem As String In lBox.Items
            If Not (lItems.ContainsKey(nItem)) Then
                strCurrentItem = nItem
                For Each sItem As String In lBox.Items
                    If sItem.Equals(strCurrentItem) Then
                        intCount += 1
                    End If
                Next
                lItems.Add(nItem, intCount)
                intCount = 0
                strCurrentItem = String.Empty
            End If
        Next

        For i As Integer = 0 To lItems.Count - 1
            strReturn.AppendLine(lItems.Keys(i).ToString & " - " & lItems.Values(i).ToString)
        Next

    Catch ex As Exception
        Return strReturn.ToString
    End Try

    Return strReturn.ToString
End Function

any guidance on this would help me alot

A: Slight delay on the answer, but here is relevant code for creating a Pivot Table from Interop (sorry, it's C#) and then using that Pivot Table to summarize the results.  This is nice because once the Pivot Table is done, you know that you have all the unique entries sorted.  You can then iterate the Pivot Table to get the results that you want.  For some cases, this may be easier than building out all the logic on the .NET side of things since Excel is so good at aggregating data.  The downside is you have to create the Pivot Table.
This is full code to create dummy data and summarize it to be as general as possible.
//up above is a namespace usage that defines:
//using Excel = Microsoft.Office.Interop.Excel;
private void button1_Click(object sender, EventArgs e)
{
    Excel.Application xl_app = new Excel.Application();

    Excel.Workbook wkbk = xl_app.Workbooks.Add();
    Excel.Worksheet sht = wkbk.Worksheets[1];

    xl_app.Visible = true;

    //create some dummy data... not using an array.. I know
    Random rnd = new Random();

    int rows = 100;
    for (int i = 0; i < rows; i++)
    {
        sht.Cells[2 + i, 1].Value = "NAME" + rnd.Next(5);
        sht.Cells[2 + i, 2].Value = "PROD" + rnd.Next(5);
        sht.Cells[2 + i, 3].Value =  rnd.Next(10);
    }

    sht.Cells[1, 1].Value = "STAFF";
    sht.Cells[1, 2].Value = "SOLD";
    sht.Cells[1, 3].Value = "HOW MANY";

    //create the pivot table
    Excel.PivotCache pc = wkbk.PivotCaches().Add(
        Excel.XlPivotTableSourceType.xlDatabase,
        sht.get_Range("A1").CurrentRegion);

    Excel.PivotTable pt = sht.PivotTables().Add(pc, sht.get_Range("F1"));

    pt.PivotFields("STAFF").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
    pt.PivotFields("SOLD").Orientation = Excel.XlPivotFieldOrientation.xlRowField;

    pt.AddDataField(pt.PivotFields("HOW MANY"), Type.Missing, Excel.XlConsolidationFunction.xlSum);
    //formatting here ensures it is a table with no extra values

    foreach (Excel.PivotField pf in pt.PivotFields())
    {
        pf.Subtotals[1] = false;
    }

    pt.ColumnGrand = false;
    pt.RowGrand = false;

    pt.RowAxisLayout(Excel.XlLayoutRowType.xlTabularRow);
    pt.RepeatAllLabels(Excel.XlPivotFieldRepeatLabels.xlRepeatLabels);

    //now we need to go through the Pivot Table to get data

    Excel.Range rng_start = sht.get_Range("F3");

    foreach (Excel.Range rng_cell in
        sht.get_Range(
            rng_start,
            rng_start.get_End(Excel.XlDirection.xlDown)))
    {
        Console.WriteLine("{0} - {1} - {2}",
            rng_cell.Value,
            rng_cell.get_Offset(0, 1).Value,
            rng_cell.get_Offset(0, 2).Value);
    }

}

Picture of the resulting Workbook has the Pivot Table over the on the side:

Console output includes rows that have the results.  Shown are the last couple lines:
...
NAME4 - PROD0 - 7
NAME4 - PROD1 - 11
NAME4 - PROD2 - 10
NAME4 - PROD3 - 17
NAME4 - PROD4 - 23


text:
Q: Running into a problem when trying to upload a video to S3 through React Native I was hoping to get some advice in regards to an error I'm getting with my approach. The error is THE ERROR IS  [SyntaxError: JSON Parse error: Unrecognized token '<']
Whenever the component mounts, I make sure to make a request for a presignedURL to my S3 server. Within a useEffect what I do currently is:
const getAwsUrl = async () => {
    getUrl().then((response) => {
        if (response.data) {
            const url = response.data.getSignedUrl.url;
            uploadFileToS3(url);
        }
    });
};

getAwsUrl();

The way I'm sending the file to the server is through a fetch. I am getting the error when returning a response but I'm also noticing that no video file is being uploaded to my S3.
const uploadFileToS3 = async (url) => {
    const formData = new FormData();
    formData.append('file', video.uri);

    await fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
        .then((res) => console.log(res))
        .catch((e) => console.log('THE ERROR IS ', e));
};

Is there something wrong in the way I'm sending my information to S3?
Thank you for pointing out any mistakes that can be seen on my end.
UPDATE
The video.uri is just a path to where the video is located (within the phone)


text:
Q: How to get the next free item in DynamoDB in concurrent environment I have a table in DynamoDB with my users (Partial key = key, Sort key = no):
key isActive
user1       true
user2       false
...         ...
In my code I need to return a next user with status not active (isActive=false). What is the best way to do this, if I need solution is based on that I have

*

*A huge table

*Concurrent environment

I wrote code that works, BUT I amn't sure it is a good solution due to Scan and Filter expression:
public String getFreeUser() throws IOException {
        Table table = dynamoDB.getTable("usersTableName");

        ScanSpec spec = new ScanSpec()
                .withFilterExpression("isActive = :is_active")
                .withValueMap(new ValueMap().withBoolean(":is_active", false));

        ItemCollection<ScanOutcome> items = table.scan(spec);

        Iterator<Item> iterator = items.iterator();
        Item item = null;

        while (iterator.hasNext()) {
            item = iterator.next();
            try {
                UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                        .withPrimaryKey(new PrimaryKey("key", item.getString("key")))
                        .withUpdateExpression("set #ian=:is_active_new")
                        .withConditionExpression("isActive = :is_active_old")
                        .withNameMap(new NameMap()
                                .with("#ian", "isActive"))
                        .withValueMap(new ValueMap()
                                .withBoolean(":is_active_old", false)
                                .withBoolean(":is_active_new", true))
                        .withReturnValues(ReturnValue.ALL_OLD);

                UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

                return outcome.getItem().getString("key");

            } catch (Exception e) {

            }
        }

        throw new IOException("No active users were found");
    }

A: GSI + Query == GOOD
userID (PK) | isActive | otherAttribute | ...
user1       | true     | foo            | ...
user2       | false    | bar            | ...
user3       | true     | baz            | ...
user4       | false    | 42             | ...
...

GSI:
userID | isActive (GSI-PK)
user1  | true
user2  | false
user3  | true
user4  | false

Add a GSI with a hash key of isActive. This will allow you to query directly the items where isActive == false.
The benefit vs scan and filter is that reads will be much more efficient. The cost is that your GSI requires it's own storage, so if your table is huge (as per your assumption) then you might want to consider a sparse index.
Sparse Index GSI + Query == BETTER
userID (PK) | isNotActive | otherAttribute | ...
user1       |             | foo            | ...
user2       | false       | bar            | ...
user3       |             | baz            | ...
user4       | false       | 42             | ...
...

GSI:
userId | isNotActive (GSI-PK)
user2  | false
user4  | false

Consider replacing the attribute isActive with isNotActive and don't give this attribute to the active users. That is, the inactive users will have true but the active users will not have this attribute at all. You can then create your GSI with this isNotActive attribute. Since it only contains the inactive users, it will be smaller and more efficient to store and query.
Note that when a user becomes active you will need to delete this attribute, and vice versa for active users that become inactive.
Attribute Projections
Regardless of which GSI you decide is best for you, if you know which attribute(s) you will need when querying these inactive users - even if it's just "all of them" - you can project these to your GSI so that you don't need to do the second lookup by key. This will increase the size of your GSI, but may be a tradeoff worth making depending on your table size, the ratio of active to inactive users, and your expected access patterns.
UPDATE
In response to the first comment, to be clear the GSI key (now labelled "GSI-PK") is not the userID. I could put the isActive or active column on the far left in the GSI tables, but that's not how it appears in the AWS console so I've left it in the original order for consistency with the way AWS display it.
Re the second comment on concurrency, you're right I didn't address this. My solution will work in a concurrent environment except for one thing - you can only do eventually consistent reads, not strongly consistent reads. What this means is that a very recent newly inactive user (and by recent I mean a fraction of a second in most circumstances) might not have replicated to the GSI yet. Similarly, a user that has recently changed from inactive to active might not have updated the GSI yet. You'll need to consider whether eventually consistent reads are acceptable for your use case.
Another consideration is that if this is going to be a very large table, if the query results are going to total >1MB you're going to get a paginated result anyway because DynamoDB enforce that limit. Without a global table lock, you're going to get some inconsistency due to updates from other clients between page queries, in which case eventually consistent reads will need to work for you.


text:
Q: MySQL: Storing unique URLs I am creating a table wich will contain user-provided URLs. I want those to be unique, so when the user gives me a URL I will first check if the URL exists and if so return the ID for the entry. If not create a new row with this URL.
Obviously I want this to be fast. What is the best option?

*

*Make the actual URL a varchar that is UNIQUE and look by this url?

*Make a hash of the URL and use it as a primary key of sort?

*Other ideas?

A: I would definitely go with a hash of the url and make the hash a unique index. A hash has a fixed length, so you can use CHAR to specify the length of the column, which grants a slight performance boost over VARCHAR or TEXT.
But might I suggest using INSERT IGNORE instead of making two calls to the database? Something like:
INSERT IGNORE INTO urlTable VALUES ('urlHash');

This has the benefit of ignoring any duplicate errors that might arise from attempting to insert a duplicate hash, without first having to do a SELECT COUNT(*) query.

A: Unless I'm missing something, you should just create a UNIQUE index of the type HASH. I don't see what adding your own hash and triggers would add? And have the field itself NOT NULL.
CREATE  TABLE `test`.`bla` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `text` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `text_UNIQUE` USING HASH (`text`)
);


text:
Q: Changing output stream back to system.out My main calls several classes, each of which redirects System.out so they can intercept what was printed by another class (even if this is bad practice - I have to do this).
Then, after they all finish, I would like to simply print on the screen with my main, but nothing happens.
Code in class1, class2:
doStuff() {
   ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   System.setOut(new PrintStream(outContent));
   ...

Main:
class1.doStuff();
class2.doStuff();
...
System.setOut(System.out); //set output back
System.out.println("Success!"); //print something. doesn't work!

A: You have to save the original System.out somewhere.
System.setOut() modifies System.out, so you're essentially doing System.out = System.out; which of course does nothing.


text:
Q: PHP Error when uploading more then 4 files at a strech When I try to upload four or less than four files, it's working fine. But when I try to upload more than four files, I am getting the following error:
Warning: Invalid argument supplied for foreach() in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16
Notice: Undefined index: files in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16

I'm using the following HTML:
    <!-- Multiple file upload html form-->
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple="multiple" accept="image/*">
        <input type="submit" value="Upload">
    </form>

and PHP:
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){

$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
    if ($_FILES['files']['error'][$f] == 4) {
        continue; // Skip file if any error found
    }
    if ($_FILES['files']['error'][$f] == 0) {
        if ($_FILES['files']['size'][$f] > $max_file_size) {
            $message[] = "$name is too large!.";
            continue; // Skip large files
        }
        elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
            $message[] = "$name is not a valid format";
            continue; // Skip invalid file formats
        }
        else{ // No error found! Move uploaded files
            if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)) {
                $count++; // Number of successfully uploaded files
            }
        }
    }
}
}

What might be the problem?

A: Edit your php.ini file and do the changes as shown below :
max_file_uploads=20

Refer this : http://php.net/manual/en/ini.core.php
Also change these things :
upload_max_filesize = 100M
post_max_size = 100M

Cheers :-)


text:
Q: Is there a way I can write a series in WordPress? What I mean by series is like writing a book. A reader should be able to click on the book and then proceed to read the chapters. I can probably mimic it by creating a page and then linking it to a series of posts. I am looking for a more natural way to present and navigate.

A: I've used this plugin for a client site I did a while back...it might do what you need...Organize Series plugin

A: Justin Tadlock's Series plugin is great, and it uses a lot less resources than the Organize Series plugin. It's simple, and based off of WP's custom taxonomies, and is built by a reputable WP programmer.

A: Just to clarify.  Organize Series uses WP's custom taxonomies as well.  Also, I now have it hosted at organizeseries.com.  Not knocking Justin's plugin though - he's doing a lot of great stuff for WordPress :)
I hope orgseries works well for you James.


text:
Q: Flutter || How to do many UI changes in a single container How can I achieve this UI?

want to change the UI in same container
I was thinking of using a bool variable that will change when I will click a button but using this with setstate will hit the performance
is there any easy way to do this ?

A: Take you container in separate stateful class and use setState inside that class,
moreover don't worry about performance related issue with setState, SetState only updates Element tree it does not recreate it.


text:
Q: JavaScript counter that continue from where left I'm trying to create a countdown counter that should countdown for 24 hours, displaying the days, the hours, the minutes and the seconds. The question is that I want to make it somehow save the progress. For example, I put the countdown to start from now till tomorrow the same time (24 hours) and when a user comes in my site after 2 hours the counter should start from 22 hours for that user and if the user closes the site and then comes back after 2 hours the counter should start from 20 hours for that user. I hope it's clear enough. I found that if that is possible it could be done using cookies, but I'm not sure how it should be done... If anyone could help it will be great! :3
Here is my code so far:
HTML:

JavaScript
// if there's a cookie with the name myClock, use that value as the deadline
    if(document.cookie && document.cookie.match('myClock')){
// get deadline value from cookie
    var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
    }

// otherwise, set a deadline 10 minutes from now and
// save it in a cookie with that name
    else{
// create deadline 10 minutes from now
        var timeInMinutes = 1380;
        var currentTime = Date.parse(new Date());
        var deadline = new Date(currentTime + timeInMinutes*60*1000);

// store deadline in cookie for future reference
        document.cookie = 'myClock=' + deadline + '; path=/; domain=.optic2n.com';
    }

    function getTimeRemaining(endtime) {
      var t = Date.parse(endtime) - Date.parse(new Date());
      var seconds = Math.floor((t / 1000) % 60);
      var minutes = Math.floor((t / 1000 / 60) % 60);
      var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
      var days = Math.floor(t / (1000 * 60 * 60 * 24));
      return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
      };
    }

    function initializeClock(id, endtime) {
      var clock = document.getElementById(id);
      var daysSpan = clock.querySelector('.days');
      var hoursSpan = clock.querySelector('.hours');
      var minutesSpan = clock.querySelector('.minutes');
      var secondsSpan = clock.querySelector('.seconds');

        function updateClock() {
            var t = getTimeRemaining(endtime);

            daysSpan.innerHTML = t.days;
            hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
            minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
            secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

            if (t.total <= 0) {
            clearInterval(timeinterval);
            }
        }

        updateClock();
        var timeinterval = setInterval(updateClock, 1000);
    }

    initializeClock('clockdiv', deadline);

Thank you in advance for the help! :3
Best regards,
Tsvetko Krastev

A: It is possible I have missed something, but your code seems very complex for something so simple. Here is what I came up with:
HTML:

  days
  hrs
  mins
  secs

Javascript:
var deadline = localStorage.getItem('dl') ? parseInt(localStorage.getItem('dl')) : (Date.now() + 86400000);
var delay = null;
// Good spot to do checks for 24hrs has passed already here

localStorage.setItem('dl',deadline);

function render() {
    if (delay) {
        clearTimeout(delay);
        delay = null;
    }
    var diff = (deadline - Date.now()) / 1000;
    document.getElementById('d').innerHTML = Math.floor(diff / 86400);
    document.getElementById('h').innerHTML = Math.floor(diff / 3600);
    document.getElementById('m').innerHTML = Math.floor((diff / 60) % 60);
    document.getElementById('s').innerHTML = Math.floor(diff % 60);
    delay = setTimeout(render,1000);
}
render();

NOTE: There are no checks for what to do after 24 hours.


text:
Q: can't get permission to post on facebook read_stream I need permission to post facebook status via application
and can't get access to read_stream
$loginUrl = $facebook->getLoginUrl(array(
"scope" => "read_stream,publish_stream"));
 header('Location: '.$loginUrl);

Do I have to submit to review ?
sorry for my english

A: The only way to NOT send the review, it's if the selected permissions are on admin (of your Facebook app) users.
For example, if you want to create an app which post new status when you create a topic on your forum, you'll access to your own "manage_pages,publish_stream" permissions, and you are the administrator of your app, so the review is not require.
But, when you want to access to your website users permissions, you need to send a review. It takes ~2 business days.


text:
Q: PHP Upload form, PDF, Doc & Docx I'm struggling to make this upload code work for a docx file, it works okay for doc and pdf..
$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)
&& in_array($extension, $allowedExts))
 {
  if ($_FILES["file"]["error"] > 0)
 {
   echo "Return Code: " . $_FILES["file"]["error"] . "
";
 }

this is part of a project from a while ago and i honestly can't remember how to do it..
I know it's not the most secure upload method, but if someone could help it would be appreciated!
I'm thinking i need to add another line here:
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 20000000)

Just not sure what.. Help is appreciated!
Edit:
So i've got to this stage (with the help of comments!)
$allowedExts = array("pdf", "doc", "docx");
$extension = end(explode(".", $_FILES["file"]["name"]));
//if ((($_FILES["file"]["type"] == "application/pdf")
//|| ($_FILES["file"]["type"] == "application/msword"))
if (($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-    officedocument.wordprocessingml.document"))
&& ($_FILES["file"]["size"] < 20000000)

&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {

But now its coming up with: Parse error: syntax error, unexpected T_BOOLEAN_AND in /var/sites/s/stanation.com/public_html/forms/process/insert.php on line 30

A: For docx check this MIME type
application/vnd.openxmlformats-officedocument.wordprocessingml.document

EDIT :
Here's the code . You're missing parenthesis
<?php

    $allowedExts = array("pdf", "doc", "docx");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if (($_FILES["file"]["type"] == "application/pdf") || ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") && ($_FILES["file"]["size"] < 20000000) && in_array($extension, $allowedExts))
    {
      if ($_FILES["file"]["error"] > 0)
      {
         echo "Return Code: " . $_FILES["file"]["error"] . "
";
      }
      else
      {
        echo "Success";
      }
  }

A: This following check will help you to upload .docx files:
$_FILES["txtFile"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"

A: There is another way to do the task.
Just check the file type and then you can work further.
Here is code to check the filetype.
$target_dir = "uploads/";
$filename= $_FILES["fileupload"]["name"]; //gets filename with type
$target_file = $target_dir . basename($filename); //uploads/file.type
echo $target_file;
$extension= pathinfo($target_file,PATHINFO_EXTENSION);
$imageFileType = strtolower($extension);
if(strcmp($imageFileType,"docx")==0){
    echo "Its word file";
}


text:
Q: Running a background service android without freezing the UI I need to log "Some text" in the devices storage after every 5 minutes can some one point me to the best way to do this.
But i do not want the main thread to freeze and the logging thread should be alive all the time.
I tried this but it seems to freeze my emulator
is there a better way to do the same
public class DataWriteService extends Service {

private FileIOHelper fileHelper= new FileIOHelper("Test.txt");
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    //Gets location and writes to a file
    fileHelper.writeToFile(this, "Some text");

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

}

A: Use Handler or seperate background thread to finish your long work. once you are done,post the value on UI thread.
Btw, on Android O +, the service would only run as long as your app is alive. As soon as your app goes in background, the app will shut down the service. Consider using JobScheduler


text:
Q: Month and year from date Postgresql I need to extract from a table that has the following columns "responsable", "fecha_contratado" the following data:
ORIGIN:
fecha_contratado || responsable

"2016-08-04";"sonia"

"2016-05-09";"mercedes"

"2016-03-01";"rebeca"

"2017-02-20";"rebeca"

"2017-01-02";"julia"

"2016-01-11";"anamgarcia"

"2016-06-20";"rebeca"

"2017-01-16";"julia"

"2016-09-26";"sonia"

"2017-03-06";"victoria"

"2016-09-28";"daniel"

"2016-01-07";"emilio"

"2016-02-08";"valle"

"2016-01-14";"mercedes"

"2016-11-14";"mercedes"

"2017-03-09";"alba"

For each "responsable"(responsible person) and year a row with the following data:
Anno | Responsible | January | February | .... | total

"anno": year

"responsable" : responsible

"Enero"(January): rows that are for that year, January and responsible in question (count)

February: same as January but with February month.

March --- December .: equal

Total: total of the year, for that year and responsible (count)

anno | responsable | Enero --- Diciebre | Total

2017;"alba";0;1;0;0;0;0;0;0;0;0;0;0;1

2017;"mercedes";0;0;1;0;0;0;0;0;0;0;0;0;1

2016;"alba";0;0;2;0;0;0;0;0;0;0;0;0;2

Now I get that, but I for a year and responsible I get more than a row, and I want only a row for a year and responsible, concrete
select
anno,
tecnico_rrhh,
sum(case when mes = 1 then total else 0 end) as enero,
sum(case when mes = 2 then total else 0 end) as febrero,
sum(case when mes = 3 then total else 0 end) as marzo,
sum(case when mes = 4 then total else 0 end) as abril,
sum(case when mes = 5 then total else 0 end) as mayo,
sum(case when mes = 6 then total else 0 end) as junio,
sum(case when mes = 7 then total else 0 end) as julio,
sum(case when mes = 8 then total else 0 end) as agosto,
sum(case when mes = 9 then total else 0 end) as septiembre,
sum(case when mes = 10 then total else 0 end) as octubre,
sum(case when mes = 11 then total else 0 end) as noviembre,
sum(case when mes = 12 then total else 0 end) as diciembre,
sum(coalesce(total,0)) as total
from (
select
  empleado.fecha_contratado as alta,
  extract(month from empleado.fecha_contratado) as mes,
  extract(year from empleado.fecha_contratado) as anno,
  count(1) as total,
  usuario_responsable.username  as tecnico_rrhh
from rrhh.empleado as empleado
LEFT JOIN commons.usuario as usuario_responsable
  on empleado.responsable = usuario_responsable.id
where usuario_responsable.username is not null
group by mes,empleado.fecha_contratado, tecnico_rrhh) altas
group by alta,anno, tecnico_rrhh
order by tecnico_rrhh;

The closest thing I've got to get is the following query, but it repeats rows for the same "responsible" and "year", when I need to pull out a single row for each "responsible year".
Can somebody help me.
Thank you very much.

A: try aggregating your set:
with p as (
select
anno,
tecnico_rrhh,
sum(case when mes = 1 then total else 0 end) as enero,
sum(case when mes = 2 then total else 0 end) as febrero,
sum(case when mes = 3 then total else 0 end) as marzo,
sum(case when mes = 4 then total else 0 end) as abril,
sum(case when mes = 5 then total else 0 end) as mayo,
sum(case when mes = 6 then total else 0 end) as junio,
sum(case when mes = 7 then total else 0 end) as julio,
sum(case when mes = 8 then total else 0 end) as agosto,
sum(case when mes = 9 then total else 0 end) as septiembre,
sum(case when mes = 10 then total else 0 end) as octubre,
sum(case when mes = 11 then total else 0 end) as noviembre,
sum(case when mes = 12 then total else 0 end) as diciembre,
sum(coalesce(total,0)) as total
from (
select
  empleado.fecha_contratado as alta,
  extract(month from empleado.fecha_contratado) as mes,
  extract(year from empleado.fecha_contratado) as anno,
  count(1) as total,
  usuario_responsable.username  as tecnico_rrhh
from rrhh.empleado as empleado
LEFT JOIN commons.usuario as usuario_responsable
  on empleado.responsable = usuario_responsable.id
where usuario_responsable.username is not null
group by mes,empleado.fecha_contratado, tecnico_rrhh) altas
group by alta,anno, tecnico_rrhh
order by tecnico_rrhh
)
select anno, tecnico_rrhh, sum(enero), sum(febrero), sum(marzo), sum(abril), sum(mayo), sum(junio), sum(julio), sum(agosto), sum(septiembre), sum(octubre), sum(noviembre), sum(diciembre)
from p
group by anno, tecnico_rrhh;


text:
Q: Data fetched from table count-1 I'm having an problem that my c# project when fetching data from data table it always fetches data -1. For example if my table has 3 data when i print data in output console it prints only 2 data(First data row won't get fetched). What is the reason for this scenario.I attached the code part with this.
String connectionString = "server = localhost; user id = xxx; password = xxx; database = xxxr";
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        String caseId = textBox1.Text;
        String searchString = "SELECT * FROM xxx" ;
        if (textBox1.Text != "")
        {
            using (MySqlCommand mySqlCommand = new MySqlCommand(searchString, connection))
            {

                using (MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader())
                {
                    if (mySqlDataReader.Read() && mySqlDataReader[0] != DBNull.Value)
                    {
                        while(mySqlDataReader.Read()){
                            Debug.WriteLine(mySqlDataReader.GetString(0));
                            Debug.WriteLine(mySqlDataReader.GetString(1));
                            Debug.WriteLine(mySqlDataReader.FieldCount.ToString());
                        }

                    }

                }
            }

                connection.Close();

Thanks.

A: When you call
if (mySqlDataReader.Read() && mySqlDataReader[0] != DBNull.Value)

you fetch first row of the result. You do not use this result anywhere when outputting the data and this result is effectively lost.


text:
Q: How can i read characters from a file and split it into two 16bits? I want to read d characters of a file and split that into two 16bits say for example:
text[1]=0x7469206564616d20;
text[2]=0x7469206564616d20;

How to do that?
INSTEAD OF TEXT[0] AND TEXT[1] PREDEFINED VALUES I WANT IT 2 READ D CHARACTERS FROM A FILE AND SPLIT IT IN2 THAT FORM

A: You probably want this:
u64 text[2] ;

FILE *input = fopen("myfile.data", "r") ;

if (input == NULL)
{
  printf ("Unable to open file\n") ;
  return 1 ;
}

while (!feof(input))
{
  int charsread ;
  charsread = fread(text, 16, 1, input) ;  // read at most 16 bytes into the text array

  // process your text array here
  // charsread contains the number of characters actually read
  //     this can be less than 16 if the total file length is not a
  //     multiple of 16. You mus deal with that.

}

fclose(input) ;


text:
Q: parsing xml file won't work I have an object constructor which uses an xmlfile to set the properties of the method. The constructor accesses it by
$this->xml_file = simplexml_load_file('xml/settings.xml');

This is how the xml file looks like:
<?xml version="1.0"?>
<settings>
   <contents>
      <content>
         <item>a</item>
         <title>A</title>
         <keywords></keywords>
      </content>
      <content>
         <item>b</item>
         <title>B</title>
         <keywords></keywords>
      </content>
      <content>
         <item>c</item>
         <title>C</title>
         <keywords></keywords>
      </content>
   <errors_escape>
      <error_escape>one</error_escape>
      <error_escape>two</error_escape>
      <error_escape>three</error_escape>
   </errors_escape>
</settings>

I'd like to create two arrays with this information. The should look like:
protected $all_settings = array(
         array('item' => 'a', 'title' => 'A', 'keywords' => ''),
         array('item' => 'b', 'title' => 'B', 'keywords' => ''),
         array('item' => 'c', 'title' => 'C', 'keywords' => ''),
      );
protected $errors_escape = array('one', 'two', 'three');

I've tried and read different questions on this topic, but I can't do anything but create arrays where it says
[title] => SimpleXMLElement Object
                (
                    [0] => A
                )

or
[title] => SimpleXMLElement Object
                (
                )

A: Assuming your missing </contents> is placed as below:
<?xml version="1.0"?>
<settings>
   <contents>
      <content>
         <item>a</item>
         <title>A</title>
         <keywords></keywords>
      </content>
      <content>
         <item>b</item>
         <title>B</title>
         <keywords></keywords>
      </content>
      <content>
         <item>c</item>
         <title>C</title>
         <keywords></keywords>
      </content>
   </contents> <!-- missing -->
   <errors_escape>
      <error_escape>one</error_escape>
      <error_escape>two</error_escape>
      <error_escape>three</error_escape>
   </errors_escape>
</settings>

You can do something like this:
$this->all_settings=array();
$this->error_escape=array();
foreach($this->xml_file->contents->content as $node)
{
    $this->all_settings[]=array("item"=>strval($node->item),"title"=>strval($node->title),"keywords"=>strval($node->keywords));
}
foreach($this->xml_file->errors_escape->error_escape as $node)
{
    $this->error_escape[]=strval($node);
}
//print_r($this->all_settings);
//print_r($this->error_escape);

Online demo
The two debug print_r outputs:
Array
(
    [0] => Array
        (
            [item] => a
            [title] => A
            [keywords] =>
        )

    [1] => Array
        (
            [item] => b
            [title] => B
            [keywords] =>
        )

    [2] => Array
        (
            [item] => c
            [title] => C
            [keywords] =>
        )

)
Array
(
    [0] => one
    [1] => two
    [2] => three
)


text:
Q: Why am I receiving HY093 error [PDO] here is my function:
function create($printing_id,$Machine,$Started,$Grams,$color) {
        //*
        $this->sql = "insert into `".$this->tableName."` (`3dprinting_id`,`Machine`,`Started`,`Grams`,`color`) values  ( :3dprinting_id , :Machine, :Started , :Grams , :color )";
        $this->stmt = $this->dbh->prepare($this->sql);
        $this->stmt->bindParam(":3dPrinting_id",$printing_id,PDO::PARAM_INT);
        $this->stmt->bindParam(":Machine",$Machine,PDO::PARAM_STR);
        $this->stmt->bindParam(":Started",$Started,PDO::PARAM_STR);
        $this->stmt->bindParam(":Grams",$Grams,PDO::PARAM_INT);
        $this->stmt->bindParam(":color",$color,PDO::PARAM_STR);
        $this->params = array();
        $this->params[":3dPrinting_id"] = $printing_id;
        $this->params[":Machine"] = $Machine;
        $this->params[":Started"] = $Started;
        $this->params[":Grams"] = $Grams;
        $this->params[":color"] = $color;
        return $this->stmt->execute();
        //*/
        /*
        $this->sql = "insert into `".$this->tableName."` (`3dprinting_id`,`Machine`,`Started`,`Grams`,`color`) values ($printing_id,'$Machine','$Started',$Grams,'$color')";
        return $this->dbh->exec($this->sql);
        //*/
    }

When I do it the top way (not commented out) I get an HY093 error. When I do it the bottom way it works perfectly.
In my database:

*

*3dprinting_id is an int, cannot be null

*Machine is varchar(30), can be null

*Started is datetime, cannot be null

*Grams is an int, can be null

*color is varchar(30), can be null

A: Just like variables, binds are case-sensitive.
You have this in your values ( :3dprinting_id
and then you're doing
bindParam(":3dPrinting_id"

They need to match in letter-case.
bindParam(":3dprinting_id"


text:
Q: If a DBSCAN algorithm is working correctly, is it possible to result in a cluster with less than minPoints members? I am new to using the DBSCAN algorithm.
Quick summary; it has two parameters:

*

*epsilon  - to specify the acceptable "distance" between two points, under which they can be considered close enough to cluster.

*minPoints - to specify the minimum number of points that must fall with the distance epsilon to constitute a cluster. If there aren't enough points together, it's just labelled as noise.

I'm using somebody else's DBSCAN algorithm and I have the source code, which I only kind of understand. I was hoping I could use it as-is but then I found some behaviour I wasn't expecting.
I specified a value of 6 for minPoints and yet in my results I got a cluster with only 2 points.
From debugging, I think I can see what's happening. It looks like when the point is examined it has 16 neighbours at a distance below epsilon, so it should qualify as a cluster. Later on, the algorithm sees that 14 of those neighbours had already been assigned to a different cluster, so this cluster ends up with only 2 points in it.
Is minPoints supposed to be strictly enforced?
Is this how a healthy DBSCAN algorithm is supposed to work or is it a bug I need to fix before proceeding?

A: For anybody who finds this question through Google, the correct answer is Yes. It is possible for a correctly functioning DBSCAN implementation to create a cluster with less than minPoints members. It is explained more fully on this other Stack Overflow question:
Can the DBSCAN algorithm create a cluster with less than minPts?


text:
Q: How to change the following Makefile of LINUX ,so that it works on MACOS as well I have a Makefile on my Linux Pc.I want to build and run the same program on MacOS too . How to edit the following Makefile ?
I want to compile a C program that has a header file of a graphics library EGGXProCALL JAXA "eggx.h".
I already installed  Xcode ,XQuartz.
I have installed EGGX file on the following directory .
[Home@/opt/eggx]$
I have a C file in the following directory.
[Home@~/Desktop/development]$
I have checked the followings .
① gcc works fine here   [Home@~/Desktop/development]$
② even the sample program to display a digital clock works ,
when the current directory is [Home@/opt/eggx]$
③   PROBLEM
when I tried to build [make] the program from  [Home@~/Desktop/development]$ by using the makefile that I had in Linux.
I always get the following error message.
[Home~/Desktop/development]$ sudo make
gcc -c main.c
main.c:7:10: fatal error: 'eggx.h' file not found
#include <eggx.h>
         ^~~~~~~~
1 error generated.
make: *** [main.o] Error 1

[Home@~/Desktop/development]$

Here is the Makefile
# Makefile

OBJS = main

$(OBJS): $(OBJS).o
#   gcc -O2 -Wall $(OBJS).c -o $(OBJS)  -I/usr/local/include  -L/usr/local/lib64   -leggx -lX11 -lm
    gcc $(OBJS).c -o $(OBJS)  -I/usr/local/include  -L/usr/local/lib64   -leggx -lX11 -lm

$(OBJS).o: $(OBJS).c
    gcc -c $(OBJS).c

.PHONY: clean
clean:
     rm -f $(OBJS) $(OBJS).o

A: You must do things in the correct order and not proceed to the next step until you have correctly completed the previous step.
1. Download, and extract the library.
The download is normally done with git clone or scp to copy the source files from somewhere.
The extract (unpack from archive) is normally done with:
tar -xvf eggx-0.93r5.tar

That will normally create a new directory (with the same name as the tar-file but without the .tar extension) like:
eggx-0.93r5

2. Build the library.
Normally you need to change directory into the newly created one and run make. I gave you the Makefile last time so you need to do:
cd eggx-0.93r5
cp MAKEFILEFROMMARK Makefile
make

There should be no errors. If there are errors, you must solve them and then run:
make clean        # delete any rubbish from previous failed build
make

3. Install the library.
You normally do this with:
make install

What that actually does depends on the package you are installing, but as a general rule, it will copy the header files and the libraries you just made into a "known" location, like /usr/local or /opt/package. The idea is to make all the files your own code will need available to all users of the computer by "publishing" or installing them to known locations.
4. Work out how to compile a simple C program that uses the library.
You should do the following steps in a completely different directory from where you downloaded the library to - do not mix your code with the library's code.
If your program uses eggx.h like this:
#include "eggx.h"

then you need to find where eggx.h is like this:
find /usr /opt /Users -name eggx.h

If that results in:
/path/to/somewhere/include/eggx.h

that means you must add this to your gcc command to tell the compiler how to find it:
gcc -I/path/to/somewhere/include ...

If your library is called libeggx.a, you need to find that too:
find /usr /opt /Users -name "libegg*a"

If that results in:
/path/to/somewhere/lib/libeggx.a

that means you need to add this to your gcc command to tell the linker where it is and what it is called:
gcc ... -L/path/to/somewhere/lib -leggx

If your program uses X11, you must install XQuartz on a Mac, and add the flags/switches for X11 into your compilation:
gcc ... -I /opt/X11/include -L /opt/X11/lib -lx11 ...

So, putting all that together, if your program is called program.c, you will compile and link with:
gcc program.c -o program -I/path/to/somewhere/include -I /opt/X11/include -L /opt/X11/lib -lx11 -L/path/to/somewhere/lib -leggx

and then run with:
./program

5. Make a Makefile that enshrines what you learned at (4).
That might look something like this:
EGGINC = -I /path/to/somewhere/include
EGGLIB = -L /path/to/somewhere/lib -leggx

X11INC = -I /opt/X11/include
X11LIB = -L /opt/X11/lib -lx11

$(OBJS): $(OBJS).o
    gcc $(OBJS).c -o $(OBJS) $(EGGLIB) $(X11LIB)

$(OBJS).o: $(OBJS).c
    gcc -I/usr/local/include $(EGGINC) $(X11INC) -c $(OBJS).c

A: You build your program in two steps:

*

*Build the source file into an object file

*Link the object file with libraries to create the final executable program

The preprocessor (which handles #include directives) is part of the building of the object file. So all flags that are needed for creation of the object files (like the -I option) should be present there and only there.
So the two rules could be changed as follows:
$(OBJS): $(OBJS).o
    gcc $(OBJS).c -o $(OBJS) -L/usr/local/lib64 -leggx -lX11 -lm

$(OBJS).o: $(OBJS).c
    gcc -I/usr/local/include -c $(OBJS).c

Of course that assumes that the EGGX library was installed in /usr/local.


text:
Q: Stop Reloading data when move into another navigation drawer i have 5 Navigation , and every navigation have fragment tablayout with 3-5fragment , i can stop reloading data in tablayout fragment, but how to stop reloading data if im moving into another navigation ?
example : now im in Navigation A when Tablayout has 3 fragments(1,2,3) when im click another fragment its okay and if data already load, so they didnt load again. and when im move into Navigation B when TabLayout has 2 fragments(4,5) its okay data load because its firsttime click, but when im moving again into Navigation A data will reload again. how to stop reloading if data already reload?


text:
Q: Want to know sha512 is safe if i mix it with md5 I need a little check on my code if it is safe or not
$pass = "jitubond";
$hashed_password =  md5($pass);
echo $hashed_password; // this is unsafe 100%
echo "
";
$hashed = hash("sha512", $pass); // style 1
echo $hashed;
echo "
";
$hashed = hash("sha512", $hashed_password); // style 2
echo $hashed;

Can you guide its is ok to use as password or not?
Thanks everyone =)

A: It is also much safer to use crypt()where you can also define the number of rounds and the salt (you should really use salts) which is also part of the PHP core
http://php.net/manual/en/function.crypt.php
https://stackoverflow.com/a/10281510/753676
you can also not rely on hash() as it is not part of the PHP core
http://php.net/manual/en/faq.passwords.php
Also PHPass is a very good option:
https://security.stackexchange.com/questions/17111/php-crypt-or-phpass-for-storing-passwords
Some examples:
http://net.tutsplus.com/tutorials/php/understanding-hash-functions-and-keeping-passwords-safe/
http://www.openwall.com/phpass/
Blowfish/bcrypt is also mentioned as the most secure algorithm (but may be too cpu-expensive) and you can set some parameters like the cost factor ...
Some servers have also php installed with the mcrypt library, which supports also more like TwoFish, TreeFish and so on http://www.php.net/manual/en/intro.mcrypt.php but this may be too much

A: sha512 is a very good algorithm to use, it is overkill to first use an md5, just use sha512.


text:
Q: Rails money-rails gem getting undefined method on monetize I'm trying to get the money-rails gem working, and I'm having problems... >.<
Here's the product I have the appropriate columns on:
class ItemAttrVal < ActiveRecord::Base
  belongs_to :attr_name
  belongs_to :registry_item

  monetize :price_val_cents, :allow_nil => true
  #snip
end

I've run the migration, and the appropriate columns are there (price_val_cents, and price_val_currency).
I've got the gem in my Gemfile, and have run bundle install successfully.
When I do ItemAttrVal.new, I get this as the first line of the error message:
NoMethodError: undefined method `monetize' for #<Class:0x007fb489c759d0>

Could somebody help point out to me what simple thing I've missed?
I haven't included it anywhere as a require (apart from my Gemfile), but I didn't think that was needed...
Thanks!

A: Based on Peter Brown's comment, you should restart the console whenever a new gem is added, or when environment variable is added or modified. Just exit and start it again, rebooting the server is also recommended.
Sometimes the problem persists, even after restart. In that case try to kill the spring server so you are starting completely fresh.


text:
Q: Simple array operation in parallel using julia I am working on a project which include some simple array operations in a huge array.
i.e. A example here
function singleoperation!(A::Array,B::Array,C::Array)
@simd for k in eachindex(A)
   @inbounds C[k] = A[k] * B[k] / (A[k] +B[k]);
end

I try to parallelize it to get a faster speed. To parallelize it, I am using distirbuded and share array function, which just modified a bit on the function I just show:
@everywhere function paralleloperation(A::SharedArray,B::SharedArray,C::SharedArray)
   @sync @distributed for k in eachindex(A)
       @inbounds C[k] = A[k] * B[k] / (A[k] +B[k]);
    end
end

However, there has no time difference between two functions even I am using 4 threads (with the try on R7-5800x and I7-9750H CPU). Can I know anythings I can improve in this code? Thanks a lot! I will post the full testing code in below:
using Distributed
addprocs(4)
@everywhere begin
    using SharedArrays
    using BenchmarkTools
end

@everywhere function paralleloperation!(A::SharedArray,B::SharedArray,C::SharedArray)
   @sync @distributed for k in eachindex(A)
      @inbounds C[k] = A[k] * B[k] / (A[k] +B[k]);
    end
end
function singleoperation!(A::Array,B::Array,C::Array)
    @simd for k in eachindex(A)
       @inbounds C[k] = A[k] * B[k] / (A[k] +B[k]);
    end
end

N = 128;
A,B,C = fill(0,N,N,N),fill(.2,N,N,N),fill(.3,N,N,N);
AN,BN,CN = SharedArray(fill(0,N,N,N)),SharedArray(fill(.2,N,N,N)),SharedArray(fill(.3,N,N,N));

@benchmark singleoperation!(A,B,C);
BenchmarkTools.Trial: 1612 samples with 1 evaluation.
 Range (min … max):  2.582 ms …   9.358 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     2.796 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   3.086 ms ± 790.997 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

@benchmark paralleloperation!(AN,BN,CN);

BenchmarkTools.Trial: 1404 samples with 1 evaluation.
 Range (min … max):  2.538 ms … 17.651 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     3.154 ms              ┊ GC (median):    0.00%
 Time  (mean ± σ):   3.548 ms ±  1.238 ms  ┊ GC (mean ± σ):  0.08% ± 1.65%

A: As the comments note, this looks like perhaps more of a job for multithreading than multiprocessing. The best approach in detail will generally depend on whether you are CPU-bound or memory-bandwith-bound. With so simple a calculation as in the example, it may well be the latter, in which case you will reach a point of diminishing returns from adding additional threads, and and may want to turn to something featuring explicit memory modelling, and/or to GPUs.
However, one very easy general-purpose approach would be to use the multithreading built-in to LoopVectorization.jl
A = rand(10000,10000)
B = rand(10000,10000)
C = zeros(10000,10000)

# Base
function singleoperation!(A,B,C)
    @inbounds @simd for k in eachindex(A)
       C[k] = A[k] * B[k] / (A[k] + B[k])
    end
end

using LoopVectorization
function singleoperation_lv!(A,B,C)
    @turbo for k in eachindex(A)
      C[k] = A[k] * B[k] / (A[k] + B[k])
    end
end

# Multithreaded (make sure you've started Julia with multiple threads)
function threadedoperation_lv!(A,B,C)
    @tturbo for k in eachindex(A)
      C[k] = A[k] * B[k] / (A[k] + B[k])
    end
end

which gives us
julia> @benchmark singleoperation!(A,B,C)
BenchmarkTools.Trial: 31 samples with 1 evaluation.
 Range (min … max):  163.484 ms … 164.022 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     163.664 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   163.701 ms ± 118.397 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

                █  ▄ ▄▄ ▁   ▁                 ▁
  ▆▁▁▁▁▁▁▁▁▁▁▁▁▆█▆▆█▆██▁█▆▁▆█▁▁▁▆▁▁▁▁▆▁▁▁▁▁▁▁▁█▁▁▁▆▁▁▁▁▁▁▆▁▁▁▁▆ ▁
  163 ms           Histogram: frequency by time          164 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

julia> @benchmark singleoperation_lv!(A,B,C)
BenchmarkTools.Trial: 31 samples with 1 evaluation.
 Range (min … max):  163.252 ms … 163.754 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     163.408 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   163.453 ms ± 130.212 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

             ▃▃   ▃█▃   █ ▃        ▃
  ▇▁▁▁▁▁▇▁▁▁▇██▇▁▇███▇▁▁█▇█▁▁▁▁▁▁▁▁█▁▇▁▁▁▁▁▁▁▁▇▁▁▁▁▁▁▁▁▁▁▇▇▁▇▁▇ ▁
  163 ms           Histogram: frequency by time          164 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

julia> @benchmark threadedoperation_lv!(A,B,C)
BenchmarkTools.Trial: 57 samples with 1 evaluation.
 Range (min … max):  86.976 ms …  88.595 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     87.642 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   87.727 ms ± 439.427 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

                    ▅      █  ▂                              ▂
  ▅▁▁▁▁██▁▅█▁█▁▁▅▅█▅█▁█▅██▅█▁██▁▅▁▁▅▅▁▅▁▅▁▅▁▅▁▅▁▁▁▅▁█▁▁█▅▁▅▁▅█ ▁
  87 ms           Histogram: frequency by time         88.5 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

Now, the fact that the singlethreaded LoopVectorization @turbo version is almost perfectly tied with the singlethreaded @inbounds @simd version is to me a hint that we are probably memory-bandwidth bound here (usually @turbo is notably faster than @inbounds @simd, so the tie suggests that the actual calculation is not the bottleneck) -- in which case the multithreaded version is only helping us by getting us access to a bit more memory bandwidth (though with diminishing returns, assuming there is some main memory bus that can only go so fast regardless of how many cores it can talk to).
To get a bit more insight, let's try making the arithmetic a bit harder:
function singlemoremath!(A,B,C)
    @inbounds @simd for k in eachindex(A)
       C[k] = cos(log(sqrt(A[k] * B[k] / (A[k] + B[k]))))
    end
end

using LoopVectorization
function singlemoremath_lv!(A,B,C)
    @turbo for k in eachindex(A)
      C[k] = cos(log(sqrt(A[k] * B[k] / (A[k] + B[k]))))
    end
end

function threadedmoremath_lv!(A,B,C)
    @tturbo for k in eachindex(A)
      C[k] = cos(log(sqrt(A[k] * B[k] / (A[k] + B[k]))))
    end
end

then sure enough
julia> @benchmark singlemoremath!(A,B,C)
BenchmarkTools.Trial: 2 samples with 1 evaluation.
 Range (min … max):  2.651 s …    2.652 s  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     2.651 s               ┊ GC (median):    0.00%
 Time  (mean ± σ):   2.651 s ± 792.423 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

  █                                                        █
  █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█ ▁
  2.65 s         Histogram: frequency by time         2.65 s <

 Memory estimate: 0 bytes, allocs estimate: 0.

julia> @benchmark singlemoremath_lv!(A,B,C)
BenchmarkTools.Trial: 19 samples with 1 evaluation.
 Range (min … max):  268.101 ms … 270.072 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     269.016 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   269.058 ms ± 467.744 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

  ▁           █     ▁  ▁  ▁▁█ ▁  ██   ▁    ▁     ▁     ▁      ▁
  █▁▁▁▁▁▁▁▁▁▁▁█▁▁▁▁▁█▁▁█▁▁███▁█▁▁██▁▁▁█▁▁▁▁█▁▁▁▁▁█▁▁▁▁▁█▁▁▁▁▁▁█ ▁
  268 ms           Histogram: frequency by time          270 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

julia> @benchmark threadedmoremath_lv!(A,B,C)
BenchmarkTools.Trial: 56 samples with 1 evaluation.
 Range (min … max):  88.247 ms … 93.590 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     89.325 ms              ┊ GC (median):    0.00%
 Time  (mean ± σ):   89.707 ms ±  1.200 ms  ┊ GC (mean ± σ):  0.00% ± 0.00%

  ▄ ▁ ▄█   ▄▄▄  ▁ ▄   ▁  ▁     ▁      ▁ ▁▄
  █▁█▆██▆▆▆███▆▁█▁█▁▆▁█▆▁█▆▆▁▁▆█▁▁▁▁▁▁█▆██▁▁▆▆▁▁▆▁▁▁▁▁▁▁▁▁▁▆▆ ▁
  88.2 ms         Histogram: frequency by time        92.4 ms <

 Memory estimate: 0 bytes, allocs estimate: 0.

now we're closer to CPU-bound, and now threading and SIMD-vectorization is the difference between 2.6 seconds and 90 ms!
If your real problem is going to be as memory-bound as the example problem, you may consider working on GPU, on a server optimized for memory bandwidth, and/or using a package that puts a lot of effort into memory modelling.
Some other packages you might check out could include Octavian.jl (CPU), Tullio.jl (CPU or GPU), and GemmKernels.jl (GPU).