text:
Q: coding style: lightweight/simplest way to create instances supporting attribute assignment? I often have to create a result object instance to return complex values from functions and wonder what's a nice Pythonic approach.
I am aware of the closely related attribute-assignment-to-built-in-object, but it is asking why he needs to hack a subclass workaround to use 'object'.  I understand why already. I am asking instead if there is existing support in the standard library to avoid using 'object' and the subclass hack, either through an existing class or function.
What's the lightest, most Pythonic way to instantiate an instance that supports attribute assignment?
I am OK to be pointed right back to subclassing 'object' answer.  It's really no big deal - just want to know if I had missed a cleaner approach supported by the standard library or builtins.
Sample of what I am trying to do:
try:
    returnval = object()
    returnval.foo = 1
    returnval.bar = 2

    print "\n\nSuccess with %s" % (returnval), vars(returnval), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")

except Exception, e:
    print "\n\nFailure with %s:%s" % (returnval, e), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")

This fails, as expected, with
Failure with <object object at 0x102c520a0>:'object' object has no attribute 'foo' has __slots__: False has __dict__: False

I am not surprised.  'object' is a bare stub, and does not allow attribute assignment because it has no __dict__.
Instead I have to declare a placeholder class.  Is there a cleaner way?
try:
    class Dummy(object): pass

    returnval = Dummy()
    returnval.foo = 1
    returnval.bar = 2
    print "\n\nSuccess with %s" % (returnval), vars(returnval), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")

except Exception, e:
    print "\n\nFailure with %s:%s" % (returnval, e), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")

This gives:
Success with <__main__.Dummy object at 0x102d5f810> {'foo': 1, 'bar': 2} has __slots__: False has __dict__: True

Using the Dummy/MyClass approach avoids these problems, but it gives off a mild code smell to litter my modules with Dummy classes.
Things that would not work/are not satisfactory:
Dictionaries. I would avoid this if I used a dict instead, but I would lose the simple returnval.foo access.
AttrDict implementations perhaps?  But those come in 3rd party packages, not in standard lib.
Mocks.  Not what I want to be using here, because this is not testing code and I want an exception thrown if returnval.foo does not exist.
Module/class attribute assignment.  Yes, I could assign attribute to an existing object in the namespace, like a class or a module declaration.  But then that would essentially be assigning attributes to a singleton and successive function calls would clobber each other.

A: Either use namedtuple or stick with a dictionary - if you really want an attribute access - create your own class for it:
>>> Dummy = namedtuple('Dummy', ['foo', 'bar'])
>>> d = Dummy(1, 2)
>>> d
Dummy(foo=1, bar=2)
>>> d.baz
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Dummy' object has no attribute 'baz'

A: A lightweight way is to use a function as the container
>>> foo = lambda: 0
>>> foo.bar = 'bar'
>>> foo.baz = 'baz'

If you are making a bunch of immutable objects with the same attributes collections.namedtuple is probably more appropriate
>>> foo = namedtuple("foo", "bar, baz")
>>> Foo = foo('bar', 'baz')
>>> foo.bar
'bar'
>>> foo.baz
'baz'

A: this is one of the uses of types.SimpleNamespace:

SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead.

from types import SimpleNamespace

res = SimpleNamespace(foo=1,bar=2)
print(f"{res=} {res.foo=} {(res.foo == 1)=}")
res.zoom = 3
print(f"{res=}")

output:
res=namespace(foo=1, bar=2) res.foo=1 (res.foo == 1)=True
res=namespace(foo=1, bar=2, zoom=3)


text:
Q: Question about the differential Today at class, my teacher stated the following proposition saying it is obvious:
Let $x_0 \in U \subset \mathbb{R}^d$, $U$ open, and $f: U \to \mathbb{R}^m$ differentiable at $x_0$, then for any $v \in \mathbb{R}^d$ we have
$$ D_v f(x_0) = D_f (x_0)(v) $$
It is not obvious to me. Can someone explain to me why this is true? Thanks a lot.

A: Let $\lambda(t) = x_0+t v$. Then $D_v f(x_0) = (f \circ \lambda)'(0)$.
Since $f$ is differentiable, we can apply the chain rule to get
$(f \circ \lambda)'(0) = D(f \circ \lambda)(0) = Df(\lambda(0)) D \lambda(0) = Df(x_0) v$.
(You can find this many texts, for example in look at the commentary after Definition 3 in Section 6.4 of Marsden's "Elementary Classical Analysis".)

A: Let us first remember what is the meaning of each symbol:

*

*$D_\nu f(x_0)$ is the derivative of $f$ at $x=x_0$ in the $\nu-$direction, i.e.,
$$
D_\nu f(x_0)=\lim_{h\to 0}\frac{f(x_0+hv)-f(x_0)}{h}. \tag*{(*)}
$$

*On the other hand, we have the following the definition:
The function $f:U\to\mathbb R^m$, where $U\subset\mathbb R^d$ open and $x_0\in U$, is said to be differentiable at $x=x_0$ if there exists a linear function $A: \mathbb R^d\to\mathbb R^m$, such that
$$
\lim_{\|w\|\to 0}\frac{\|f(x_0+w)-f(x_0)-Aw\|}{\|w\|}=0. \tag{1}
$$
This unique linear functional $A$ in $(1)$ is called the differential of $f$ at $x_0$, and is denoted by $Df(x_0)$.
If $\nu\in \mathbb R^d\smallsetminus\{0\}$ and $w=h\nu$, and $f$ is differentiable at $x=x_0$, then $(1)$ implies that
$$
\lim_{\|h\|\to 0}\frac{\|f(x_0+h\nu)-f(x_0)-hDf(x_0)\nu\|}{\lvert h\rvert}=0,
$$
or, dividing numerator and denominator by $h$
$$
\lim_{\|h\|\to 0}\,\Big\|\,\frac{f(x_0+h\nu)-f(x_0)}{h}-Df(x_0)\nu\,\Big\|. \tag{**}
$$
Now $(*)$ and $(**)$ implies that
$$
D_\nu f(x_0)=Df(x_0)\nu.
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: multi select drop downs in php ajax My HTML form is submits to a URL via ajax.
data is inserting twice in one column and never inserting data from the second drop down ... I dont know why
Literally fed up with debugging.
Please anyone do trace out the glitch

$thispage = 'sbt_teacher';
include ('top-page.php'); ?>

Register as Tech

   <form method="post" id="framework_form">

      Name:
      <input class="form-control" type="text" name="s_name" id="s_name"/>

       Gender:

    Male
      <input type="radio" name="s_gender" class="radio_gender" id="s_gender" value="t_male"/>

    Female
      <input type="radio" name="s_gender" class="radio_gender" id="s_gender" value="t_female" />

     Select the class(es) you can teach

     <select multiple class="form-control" name="s_class[]" id="s_class"/>

      <?php

      while ($all_ad_class_f = mysqli_fetch_array($all_ad_class) ) {
        ?>
      <option value="<?php echo $all_ad_class_f['class']; ?>"> <?php echo $all_ad_class_f['class']; ?> </option>
      <?php

        }

       ?>

    </select>

     Select the subjects you can teach

     <select multiple class="form-control" name="s_subjects[]" id="s_subjects"/>

      <?php

      while ($all_ad_sbject_f = mysqli_fetch_array($all_ad_sbj) ) {
        ?>
      <option value="<?php echo $all_ad_sbject_f['sbj']; ?>"> <?php echo $all_ad_sbject_f['sbj']; ?> </option>
      <?php

        }

       ?>

    </select>

    <input type="submit" class="btn btn-info" name="submit_tech" value="Submit" onClick="submit_data()"/>

   </form>

<?php include('footer.php'); ?>

<?php include('bottom-page.php'); ?>

Here is my submit-as-tech.php code

<?php
include('gerf/fg.php');

$stmt = $conn -> prepare("INSERT INTO `teachersnew` (`t_name`, `t_gender`, `t_subjects`) VALUES (?, ?, ?)");

$stmt -> bind_param("sss", $s_name, $s_gender, $data_sbj);

        $s_name = ucfirst( $_POST['s_name'] );
        $s_gender = $_POST['s_gender'];
    //  $s_class = $_POST['s_class'];
        $s_subjects = $_POST['s_subjects'];

 // $data_class = '';
 // foreach($s_class as $row_class)
 // {
 //  $data_class .= $row_class . ', ';
 // }
 // $data_class = substr($data_class, 0, -2);

 $data_sbj = '';
 foreach($s_subjects as $row_sbj)
 {
  $data_sbj .= $row_sbj . ', ';
 }
 $data_sbj = substr($data_sbj, 0, -2);

//die( 'Name: ' . $s_name . ' Gender: ' . $s_gender . ' Classes: ' . $data_class );

$stmt -> execute();

 die( 'thk' );
$stmt -> close();
$conn -> close();

?>

here is the result


text:
Q: Google is indexing future dates on my codeigniter datepicker If I do a google search for "harbour holidays 2 strand" then it returns my clients site www.padstow-self-catering.co.uk
The problem is that google has decided to index and future date which can be seen from the datapicker on the right sidebar.  Nearly all searches for specific holiday properties has this issue and the future date is different for each.
I have no idea why this is happening?

A: The "2016" comes from the URL that's been indexed:
http://www.padstow-self-catering.co.uk/properties/map/46/2016/12

Presumably somewhere there's a page with that URL on, and Google indexed that.
Personally I'd probably make the date picker parameters URL parameters instead:
http://www.padstow-self-catering.co.uk/properties/map/46?year=2016&month=12

... or remove it entirely from your links. Either way, it's not that Google has "decided to index" pages for a future date - they're just pages.
(Note: I work for Google, but have nothing to do with web search. This answer should not be seen as being an "insider" post in any way, nor as representing the view of Google.)


text:
Q: Is it possible to make a POST request directly to a DynamoDB table using a gateway URL? I have an app that takes in a gateway url and makes POST request directly to the URL with some data. I would like to know if there is a specific url that is used to make POST request to DynamoDB.
I contacted AWS support and they linked me to this article but I am still confused about how to do it.
More details on the app and making POST request through it.

A: You will most likely not be able to have the Ruuvi gateway post data directly to your DynamoDB table.
While it is absolutely possible to have any client that can make HTTP requests, interface with DynamoDB, one requirement to making successful requests is for the requests to contain a valid AWS SigV4 signature. This signature is specific to each request and must be generated based on the contents of the request, including headers, and must also be time correlated with the request.
To read more about how to generate SigV4 signatures yourself, here is some information from the AWS docs: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
There is also a walk through that you can follow to understand exactly what is entailed: https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
So, unless the Ruuvi gateway has the ability to generate SigV4 signatures on your behalf, you will need some intermediate tech to receive the data and post to Dynamo.
For example, you could set up an AWS API Gateway backed by a Lambda function to receive the data, do any transformation you want, and then post to DynamoDB. Alternatively, you could spin up a tiny EC2 instance, deploy an Nginx reverse proxy and feed the requests to some stock of your choice (Node,Python,PHP,Java,.NET) and process..
Something you will have to consider is how you authenticate these requests from the Ruuvi gateway so you don't get junk into your system. Api gateway has some nice features, like throttling rules and even support for an authorization process but again, not sure how the Ruuvi gateway would integrate with anything that requires auth keys etc. Maybe they have a way to at least pass some sort of secret in a header and as long as you expose your ingestion endpoint as an SSL endpoint, you'll get some protection. YMMV

A: The article you posted has the information you need I believe
Request Format
The DynamoDB low-level API accepts HTTP(S) POST requests as input. The AWS SDKs construct these requests for you.
Suppose that you have a table named Pets, with a key schema consisting of AnimalType (partition key) and Name (sort key). Both of these attributes are of type string. To retrieve an item from Pets, the AWS SDK constructs the following request.
POST / HTTP/1.1
Host: dynamodb.<region>.<domain>;
Accept-Encoding: identity
Content-Length: <PayloadSizeBytes>
User-Agent: <UserAgentString>
Content-Type: application/x-amz-json-1.0
Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<Signature>
X-Amz-Date: <Date>
X-Amz-Target: DynamoDB_20120810.GetItem

{
    "TableName": "Pets",
    "Key": {
        "AnimalType": {"S": "Dog"},
        "Name": {"S": "Fido"}
    }
}


text:
Q: Thread-launched running processes won't destroy (Java) Starting multiple threads and having each exec() then destroy() a running java process result in some of the process not being destroyed and still running after program exit. Here is some code that reproduce the issue. I noticed the more threads you start, the more processes stay alive. And the more sleep before destroy(), the less processes stay alive. (I used InfiniteLoop as an example. Any running process will do the trick.)
EDIT : Bug has been reported to Oracle, waiting for an answer. Feel free to share any knowledge/experiments on the subject.
for(int i = 0; i < 100; i++)
{
  new Thread(new Runnable()
  {
    public void run()
    {
      try
      {
        Process p = Runtime.getRuntime().exec(new String[]{"java", "InfiniteLoop"});
        Thread.sleep(1);
        p.destroy();
      }catch(IOException | InterruptedException e){e.printStackTrace();}
    }
  }).start();
}

A: Use a p.waitFor(); before p.destroy(); ,
this will ensure the completion of the previous process. I think you p.destroy command gets invoked sooner than the exec() command performs the action. Therefore it becomes useless.

A: If subprocesses write anything to stdout or stderr (intentionally or not), that could cause trouble:

"Because some native platforms only provide limited buffer size for
  standard input and output streams, failure to promptly write the input
  stream or read the output stream of the subprocess may cause the
  subprocess to block, and even deadlock."

Source: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
The whole article is IMO worth reading if you need to use Runtime.exec().

A: You should close the input/output/error streams to the process. We saw some issues in the past where the forked process was not completing properly due to those streams not being closed (even if they weren't being used).
An exemplary solution:
p.destroy();
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();

A: This is simply because before the threads execute the destroy call, your main program terminates and all the associated threads leaving the started processes running. To verify this, simply add a System.out call after the destroy and you will find it is not executed. To overcome this add a Thread.sleep at the end of your main method and you will not have the orphaned processes. The below does not leave any process running.
public class ProcessTest {

public static final void main (String[] args) throws Exception {

    for(int i = 0; i < 100; i++) {
        new Thread(new Runnable()
            {
                public void run() {
                    try {
                        Process p = Runtime.getRuntime().exec(new String[]{"java", "InfiniteLoop"});
                        Thread.sleep(1);
                        p.destroy();
                        System.out.println("Destroyed");
                    }catch(IOException e) {
                        System.err.println("exception: " + e.getMessage());
                    } catch(InterruptedException e){
                        System.err.println("exception: " + e.getMessage());
                    }
                }
            }).start();
    }

    Thread.sleep(1000);

}

}

A: I believe that according to link, a distinct process is spawned by the operating system in response to this call. This process has a lifetime independent of your Java program and threads within it so you would expect it to continue running after your program has exited. I just tried it on my machine and it appeared to work as expected:
import java.io.*;

class Mp {
public static void main(String []args) {
    for(int i = 0; i < 100; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("1");
                    Process p = Runtime.getRuntime().exec
                        (new String[]{"notepad", ""});
                    System.out.println("2");
                    Thread.sleep(5);
                    System.out.println("3");
                    p.destroy();
                    System.out.println("4");
                }
                catch(IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
}

A: This is not an answer; I am posting complete source for my own attempt at recreating this problem as per discussion in question comments.
I cannot reproduce this problem on Ubuntu 12.04; OpenJDK 6b_27 (however, see below).
ProcessTest.java:
import java.io.*;

public class ProcessTest {

    public static final void main (String[] args) throws Exception {

        for(int i = 0; i < 100; i++) {
            new Thread(new Runnable()
                {
                    public void run() {
                        try {
                            Process p = Runtime.getRuntime().exec(new String[]{"java", "InfiniteLoop"});
                            Thread.sleep(1);
                            p.destroy();
                        }catch(IOException e) {
                            System.err.println("exception: " + e.getMessage());
                        } catch(InterruptedException e){
                            System.err.println("exception: " + e.getMessage());
                        }
                    }
                }).start();
        }

    }

}

InfiniteLoop.java
public class InfiniteLoop {
    public static final void main (String[] args) {
        while (true) ;
    }
}

I cannot reproduce the issue where processes remaining running after the JVM terminates. However, if I add a long delay in the main thread after starting the threads but before returning from main, I do see roughly a dozen running java processes that stick around (although they are terminated when the main program terminates).
Update:
I just had it leave about 5 processes running after it terminated. It doesn't always happen. Weird. I want to know more about this too. I have a hunch that it has something to do with destroying the process too quickly or some kind of race condition; maybe java forks something off or does something to create a new process that destroy() doesn't take care of if called too quickly / at the wrong time.
I found an old bug (but it is not mark resolved) stating that if a process spawns subprocesses they may not be killed by destroy(). bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092 What version of the JDK are you using.
Here's another reference to what looks like a similar issue: Java tool/method to force-kill a child process And I want to apologize if I've only added confusion to your life, I don't actually use Process that much and am not familiar with the quirks. Hopefully somebody else will step in with a definitive answer. It seems like it doesn't handle subprocesses well, and I'm presuming java forks something off. That's all I got.

A: There is a race condition between the time Runtime.exec kicks off a new thread to start a Process and when you tell that process to destroy itself.
I'm on a linux machine so I will use the UNIXProcess.class file to illustrate.
Runtime.exec(...) will create  a new ProcessBuilder and start it which on a unix machine creates a new UNIXProcess instance.  In the constructor of UNIXProcess there is this block of code which actually executes the process in a background (forked) thread:
java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
    public Object run() {
    Thread t = new Thread("process reaper") {
        public void run() {
                    try {
                        pid = forkAndExec(prog,
                      argBlock, argc,
                      envBlock, envc,
                      dir,
                      redirectErrorStream,
                      stdin_fd, stdout_fd, stderr_fd);
                    } catch (IOException e) {
                        gate.setException(e); /*remember to rethrow later*/
                        gate.exit();
                        return;
                    }
                    java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                        public Object run() {
                        stdin_stream = new BufferedOutputStream(new
                                                FileOutputStream(stdin_fd));
                        stdout_stream = new BufferedInputStream(new
                                                FileInputStream(stdout_fd));
                        stderr_stream = new FileInputStream(stderr_fd);
                        return null;
                    }
                    });
                    gate.exit(); /* exit from constructor */
        int res = waitForProcessExit(pid);
        synchronized (UNIXProcess.this) {
            hasExited = true;
            exitcode = res;
            UNIXProcess.this.notifyAll();
        }
        }
    };
            t.setDaemon(true);
            t.start();
    return null;
    }
});

Notice that the background thread sets the field pid which is the UNIX process id.  This will be used by destroy() to tell the OS which process to kill.
Because there is no way to make sure that this background thread has run when destroy() is called, we may try to kill the process before it has run OR we may try to kill the process before pid field has been set;  pid is uninitialized and therefore is 0.  So I think calling destroy too early will do the equivalent of a kill -9 0
There is even a comment in the UNIXProcess destroy() that alludes to this but only considers calling destroy after the process has already finished, not before it has started:
// There is a risk that pid will be recycled, causing us to
// kill the wrong process!  So we only terminate processes
// that appear to still be running.  Even with this check,
// there is an unavoidable race condition here, but the window
// is very small, and OSes try hard to not recycle pids too
// soon, so this is quite safe.

The pid field is not even marked as volatile so we may not even see the most recent value all the time.

A: I had a very similar issue and the problem with destroy() not working was manifesting even with a single thread.
Process process = processBuilder(ForeverRunningMain.class).start()
long endTime = System.currentTimeMillis() + TIMEOUT_MS;
while (System.currentTimeMillis() < endTime) {
    sleep(50);
}
process.destroy();

The process was not always destroyed if TIMEOUT_MS was too low. Adding an additional sleep() before destroy() fixed it (even though I don't have an explanation why):
Thread.sleep(300);
process.destroy();


text:
Q: Time Series clustering: Changing warping window for Dynamic time warping I'm working on the same type of data and i want to classify the times series to find clear pattern of use.
My data is collected from clients of a telecom company, and we want to detect pattern of the amount of data consumed by clients with their wifi box. So each client have a time series of how much data he consumed each 6minutes (I resampled it to hours).
I also applied DTW with KmeansTimeSeries using tslearn:
km = TimeSeriesKMeans(n_clusters = cluster_count, metric="dtw", verbose=1)
labels = km.fit_predict(mySeries)

My question is i want to change the warping window for DTW in python, and i'm pretty sure it's easy think to do, but i just coudn't find a way to do it. I also want to find the best window parameter for my case.

A: Assuming that you are talking about the tslearn package, we can have a look into the documentation of TimeSeriesKMeans.
The parameters are described in detail as:

metric : {"euclidean", "dtw", "softdtw"} (default: "euclidean") Metric
to be used for both cluster assignment and barycenter computation. If
"dtw", DBA is used for barycenter computation.
metric_params : dict or None (default: None) Parameter values for the
chosen metric. For metrics that accept parallelization of the
cross-distance matrix computations, n_jobs key passed in metric_params
is overridden by the n_jobs argument.

So we can pass parameters to the metric. Lets then investigate the parameters that the dtw metric offers, where we find

global_constraint : {"itakura", "sakoe_chiba"} or None (default: None)
Global constraint to restrict admissible paths for DTW.
sakoe_chiba_radius : int or None (default: None) Radius to be used for
Sakoe-Chiba band global constraint. If None and global_constraint is
set to "sakoe_chiba", a radius of 1 is used. If both
sakoe_chiba_radius and itakura_max_slope are set, global_constraint is
used to infer which constraint to use among the two. In this case, if
global_constraint corresponds to no global constraint, a
RuntimeWarning is raised and no global constraint is used.
itakura_max_slope : float or None (default: None) Maximum slope for
the Itakura parallelogram constraint. If None and global_constraint is
set to "itakura", a maximum slope of 2. is used. If both
sakoe_chiba_radius and itakura_max_slope are set, global_constraint is
used to infer which constraint to use among the two. In this case, if
global_constraint corresponds to no global constraint, a
RuntimeWarning is raised and no global constraint is used.

Thus, I suggest you call
km = TimeSeriesKMeans(n_clusters = cluster_count, metric="dtw", metric_params = {global_constraint:"itakura"} verbose=1)


text:
Q: How to make an HTML element ignore the position of another element? I have a
 tag used as a container for multiple other elements. As a sibling of the
 tag, I have an
 used as a timer of sorts. The thing is, the
 tag is positioned exactly how I want it to without the
, and when the
 exists, it moves the
 tag over. How can I use the
 tag without moving the
 tag over? Thanks!
(Required CSS below)

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    height: 100vh;
    display: flex;
    margin: 0 auto;
}

/* The
 mentioned above*/
.timer {
    margin: 10px;
    font-family: roboto;
    color: #F6E71D;
    font-weight: 100;
    font-size: 25px;
}

/*The container mentioned above*/
#card-container {
    width: 640px;
    height: 640px;
    margin: auto;
    display: flex;
    flex-wrap: wrap;
    perspective: 1000px;
}

Time left:

X

X

A: If your goal is to have the timer in the top left and not affect other elements, give it the css property position: absolute; and do the rest of your styling to put things where you want them. This way it doesn't affect the positioning of other elements. I would highly recommend the use of flexbox or css grid if you haven't looked into them yet. It makes layout styling easier.


text:
Q: pyodbc memory leak when committing after select statement I've met a memory leak problem with pyodbc. It took me a lot of time to track down. Finally I got the piece of code where memory leak happens.
import pyodbc
conn = pyodbc.connect(myconnstr)
cur = conn.cursor()
for i in range(1000000):
    print i
    cur.execute('select * from test.aa;')
    cur.fetchall()
    cur.commit()

If I run this code, it slowly eat up memory at about 5mb/sec. However, if I remove the last line like in below, it won't leak memory. Closing the cursor and the connection in iteration does not help. If the memory leak happened, closing the cursor and the connection won't get the memory back.
import pyodbc
conn = pyodbc.connect(myconnstr)
cur = conn.cursor()
for i in range(1000000):
    print i
    cur.execute('select * from test.aa;')
    cur.fetchall()

However, if I replace the select with a insert statement, it doesn't leak memory:
import pyodbc
conn = pyodbc.connect(myconnstr)
cur = conn.cursor()
for i in range(1000000):
    print i
    cur.execute('insert into test.aa values(1);')
    cur.commit()

I tried using guppy to track down the leak, but it doesn't help. Using hpy().heap() gives these results:
Partition of a set of 286322 objects. Total size = 22433376 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0 115601  40  8825424  39   8825424  39 str
     1  69891  24  3030424  14  11855848  53 tuple
     2   1921   1  1352588   6  13208436  59 dict (no owner)
     3   1074   0  1349016   6  14557452  65 dict of PyQt4.QtCore.pyqtWrapperType
     4    477   0  1189980   5  15747432  70 dict of module
     5  12326   4   887472   4  16634904  74 types.CodeType
     6  12178   4   730680   3  17365584  77 function
     7   1162   0   565496   3  17931080  80 dict of type
     8   1162   0   523384   2  18454464  82 type
     9   1074   0   502632   2  18957096  85 PyQt4.QtCore.pyqtWrapperType
<1140 more rows. Type e.g. '_.more' to view.>

It said only 22mb memory is taken up but actually the python process used about 500mb at the moment.
I'm using 32bit python 2.7.2 (coming with Python(x,y) 2.7.2.3), and manually installed pyodbc 32bit 3.0.6 using the .exe installer. Oh and I'm using MySQL 5.5.17 32bit.
Have anyone met this problem before? Any comments are most appreciated. Many thanks!
Oh I forgot to tell that the reason I commit after a select statement is that I'm writing a wrapper for sql operations. I can't tell from statement if it's a select or a insert, so I fetch and commit for every statement, just to be sure everything is done. If there is a good way to tell among select/insert/update/show, I think I can avoid this memory leak problem.

A: I haven't found a fix but did find a workaround. I was experiencing the problem on only some of our machines. With the help of your code snippet, I was able to narrow down which ones these were and then noticed that all the ones it did occur on where using version 5.2 of the MySQL ODBC connector, while the ones it didn't leak on where using 5.1. This happened on both Windows and Linux.
Downgrading to 5.1 on the machines with the leak appears to have solved (or at least avoided) the problem.


text:
Q: Hide assembly and does not occupy the position
click  'hide label3'
code:label3.hidden = true

I want label2 and label4 connected together
Could only be modified  label4's  frame?
code:label4.frame.origin.y = label4.frame.origin.y - label3.frame.size.height
I don't want this way to solve this problem
If there are many labels below label3
I will crazy

A: use Horizontal Stack View  ,   hiden one label  others  connected together


text:
Q: In GWT, how to known from a SelectionEvent in a Tree if the Shift button is pressed I try in GWT to create a Tree with multiple selection for the nodes and ran into a problem similar to this question Shift Key in GWT?.
When a selectionEvent is raised from the Tree, I would like to know if the Shift key is pressed or not.
SelectionHandler<TreeItem> getSelectionHandler() {
    return new SelectionHandler<TreeItem>(){
        @Override
        public void onSelection(SelectionEvent<TreeItem> event) {
            // is shift key pressed ?
        }
    };
}

The solution in the question above cannot apply in this case as the SelectionHandler class does not inherit from DOMEvent and then does not have a getNativeEvent() function.
I tried a dirty solution by adding keyDownEventHandler and keyUpEventHandler to the Tree with a boolean flag but the handlers are only called when the focus is on the tree so this doesn't work.
Is there a simple solution (or just a solution even if it's not simple) ? Thanks.
Edit on aem response :
The solution can work by enclosing the components in a FocusPanel with a keyUp/DownHandler but then I can't add any component needing keyboard input such as TextArea as the "global" handler takes the priority... So it don't really solve my problem.

A: My suggestion is to create a custom Tree class that temporary store the event and store this event by overriding the onBrowseEvent method. Then you can, in your onSelection method, check if the shift key was pressed by checking this stored event. Since JavaScript is not concurrent it should be no problem using the private variable. The code would be something like this:
public class MyTree extends Tree {
   private Event currentEvent;

   ... constructors...

   // Call this method from within the onSelection method to determine if the shift key
   // was pressed.
   public boolean isShiftPressed() {
      return currentEvent != null ? currentEvent.getShiftKey() : false;
   }

   @Override
   public void onBrowserEvent(Event event) {
     currentEvent = event;
     super.onBrowserEvent(event);
     currentEvent = null;
   }
}

A: I'm not sure whether this will work, but it's worth a try:
What about adding key handlers to the root panel containing the Tree, and have them set a boolean indicating whether the Shift key is down? Then the tree's SelectionHandler can check that boolean.
The trouble with this is that the page might contain other widgets that capture the key events, which would make this behavior seem flaky to the user.


text:
Q: How to configure spellcheck functionality in Solr? I want to implement spellcheck functionality in Apache Solr-6.6.4, but am not able to do so. My program is not suggesting me the correct word that should be used (in Solr query).
My collection name is employee. I want to implement spellcheck on field name jobTitleName.
I have referred to the following link:
http://akashmusings.blogspot.com/2016/03/spell-check-with-solr.html
I am using following configurations.
schema.xml
<uniqueKey>userId</uniqueKey>

 <field name="userId" type="string" indexed="true" stored="true" required="false" />
 <field name="jobTitleName" type="string" indexed="false" stored="true" required="false"/>
 <field name="firstName" type="string" indexed="false" stored="true" required="false"/>
 <field name="lastName" type="string" indexed="false" stored="true" required="false"/>
 <field name="preferredFullName" type="string" indexed="false" stored="true" required="false"/>
 <field name="employeeCode" type="string" indexed="false" stored="true" required="false"/>
 <field name="region" type="string" indexed="false" stored="true" required="false"/>
 <field name="phoneNumber" type="string" indexed="false" stored="true" required="false"/>
 <field name="emailAddress" type="string" indexed="false" stored="true" required="false"/>
 <field name="_version_" type="tver" indexed="true" stored="true" />
 <dynamicField name="ignored_*" type="ignored" multiValued="true"/>
 <dynamicField name="*" type="ignored" multiValued="true"/>
  <fieldType name="string" class="solr.StrField" sortMissingLast="true" docValues="true" />
  <fieldType name="booleans" class="solr.BoolField" sortMissingLast="true" multiValued="true"/>
  <fieldType name="int" class="solr.IntPointField" docValues="true"/>
  <fieldType name="text" class="solr.TextField" positionIncrementGap="100" multiValued="true"/>
  <fieldType name="double" class="solr.TrieDoubleField" docValues="true" precisionStep="0" positionIncrementGap="0"/>
  <fieldType name="tdates" class="solr.TrieDateField" docValues="true" precisionStep="6" positionIncrementGap="0" multiValued="true"/>
  <fieldType name="tlongs" class="solr.TrieLongField" docValues="true" precisionStep="8" positionIncrementGap="0" multiValued="true"/>
  <fieldType name="tver" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0" />
  <fieldType name="tdoubles" class="solr.TrieDoubleField" docValues="true" precisionStep="8" positionIncrementGap="0" multiValued="true"/>
  <fieldType name="ignored" stored="false" indexed="false" docValues="false" multiValued="true" class="solr.StrField" />

solrconfig.xml (spellcheck)
  <searchComponent name="spellcheck" class="solr.SpellCheckComponent">
    <str name="queryAnalyzerFieldType">text_general</str>
    <lst name="spellchecker">
      <str name="name">default</str>
      <str name="field">jobTitleName</str>
      <str name="classname">solr.DirectSolrSpellChecker</str>
      <str name="distanceMeasure">internal</str>
      <float name="accuracy">0.5</float>
      <int name="maxEdits">2</int>
      <int name="minPrefix">1</int>
      <int name="maxInspections">5</int>
      <int name="minQueryLength">4</int>
      <float name="maxQueryFrequency">0.01</float>
      <float name="thresholdTokenFrequency">.01</float>
    </lst>
    <lst name="spellchecker">
      <str name="name">wordbreak</str>
      <str name="classname">solr.WordBreakSolrSpellChecker</str>
      <str name="field">lowerfilt</str>
      <str name="combineWords">true</str>
      <str name="breakWords">true</str>
      <int name="maxChanges">10</int>
    </lst>
  </searchComponent>
  <requestHandler name="/spell" class="solr.SearchHandler" startup="lazy">
    <lst name="defaults">
      <str name="spellcheck.dictionary">default</str>
      <str name="spellcheck">on</str>
      <str name="spellcheck.extendedResults">true</str>
      <str name="spellcheck.count">10</str>
      <str name="spellcheck.alternativeTermCount">5</str>
      <str name="spellcheck.maxResultsForSuggest">5</str>
      <str name="spellcheck.collate">true</str>
      <str name="spellcheck.collateExtendedResults">true</str>
      <str name="spellcheck.maxCollationTries">10</str>
      <str name="spellcheck.maxCollations">5</str>
    </lst>
    <arr name="last-components">
      <str>spellcheck</str>
    </arr>
  </requestHandler>

solrconfig.xml (update)
  <initParams path="/update/**,/query,/select,/tvrh,/elevate,/spell,/browse">
    <lst name="defaults">
      <str name="df">firstName</str>
    </lst>
  </initParams>

  <initParams path="/update/**">
    <lst name="defaults">
      <str name="update.chain">add-unknown-fields-to-the-schema</str>
    </lst>
  </initParams>
  <searchComponent name="spellcheck" class="solr.SpellCheckComponent">
    <str name="queryAnalyzerFieldType">text_general</str>
    <lst name="spellchecker">
        <str name="name">default</str>
        <str name="field">jobTitleName</str>
      <str name="classname">solr.DirectSolrSpellChecker</str>
      <str name="distanceMeasure">internal</str>
      <float name="accuracy">0.5</float>
      <int name="maxEdits">2</int>
      <int name="minPrefix">1</int>
      <int name="maxInspections">5</int>
      <int name="minQueryLength">4</int>
      <float name="maxQueryFrequency">0.01</float>
      <float name="thresholdTokenFrequency">.01</float>
    </lst>
    <lst name="spellchecker">
      <str name="name">wordbreak</str>
      <str name="classname">solr.WordBreakSolrSpellChecker</str>
      <str name="field">lowerfilt</str>
      <str name="combineWords">true</str>
      <str name="breakWords">true</str>
      <int name="maxChanges">10</int>
       </lst>
  </searchComponent>

  <requestHandler name="/spell" class="solr.SearchHandler" startup="lazy">
    <lst name="defaults">
      <str name="spellcheck.dictionary">default</str>
      <str name="spellcheck">on</str>
      <str name="spellcheck.extendedResults">true</str>
      <str name="spellcheck.count">10</str>
      <str name="spellcheck.alternativeTermCount">5</str>
      <str name="spellcheck.maxResultsForSuggest">5</str>
      <str name="spellcheck.collate">true</str>
      <str name="spellcheck.collateExtendedResults">true</str>
      <str name="spellcheck.maxCollationTries">10</str>
      <str name="spellcheck.maxCollations">5</str>
    </lst>
    <arr name="last-components">
      <str>spellcheck</str>
    </arr>
  </requestHandler>

Requirement
I want that when user enters the wrong jobTitleName, Solr should produce the correct recommendation using spellcheck.
e.g. If the user enters Developr as jobTitleName, Solr should produce recommendation as Developer to the user using spellcheck.


text:
Q: Modeling 4-D Data in Python (with timestamp) I have data that is a projection for certain days from now n (or associated with a certain date in the future) and has an (x,y) pair as the projection. So all in all I have (x,y,n) = (x,y,z) or 3-D data.
Now, I have historical measurements, as well. The y dimension has "depth" but x is fixed. So I have (x,y,z,t) where t is a datetime.datetime object.
My actual data is currently:
data = [(x, [(y0, t0),(y1, t1),(y2, t2),...,(yn,tn), z]

My questions: (1) Is there a natural way in python to store this format of data? Or, (2) is it over-engineering the problem and there is a natural database solution to this type of data storage?

A: Use a pd.MultiIndex to represent the various dimensions
data = [('x', [('y0', 't0'), ('y1', 't1'), ('y2', 't2'), ('yn', 'tn')], 'z')]
d = [[x, y, z, t] for x, ys_ts, z in data for y, t in ys_ts]
d

[['x', 'y0', 'z', 't0'],
 ['x', 'y1', 'z', 't1'],
 ['x', 'y2', 'z', 't2'],
 ['x', 'yn', 'z', 'tn']]

Then make into a dataframe
df = pd.DataFrame(d, columns=list('xyzt')).set_index(list('xzt')).y.unstack()
df

t    t0  t1  t2  tn
x z
x z  y0  y1  y2  yn


text:
Q: What fraction of a charge is induced on a surface via balayage? Consider a smooth, bounded domain $\Omega \subset \mathbb{R}^3$, and place a  charge $q>0$ at a point $z\in\mathbb{R}^3\setminus\overline\Omega$.  Via the concept of balayage, there is an induced surface charge density (i.e. signed Radon measure) $\nu$ supported on $\partial\Omega$ such that
$$
\int \frac{d\nu(y)}{|x-y|} = \frac{q}{|x-z|}
$$
for all $x\in\Omega$.  Moreover, the total variation of $\nu$ is bounded by $q$. I think it is known that if $z$ lies in a bounded component of $\mathbb{R}^3\setminus\overline\Omega$, then this becomes an equality i.e. the total variation of $\nu$ equals $q$.   My question is what fraction of $q$ is the total variation of $\nu$ if $\overline\Omega$ does not fully enclose $z$?  Is it proportional to the solid angle subtended by $\overline\Omega$ from the perspective of point $z$ (i.e. the fraction of the view of infinity from $z$'s perspective that is blocked by $\overline\Omega$)?

A: (Too long for a comment.)
If $\Omega = B(0, r)$ is a ball, then the fraction is given by $r/|z|$. More precisely, the harmonic reduction of $$u(x) = (4\pi)^{-1} q |x-z|^{-1}$$ in $\mathbb{R}^3 \setminus \Omega$ is given by $$v(x) = (4\pi)^{-1} q r |z|^{-1} |x-z^*|^{-1}$$ for $x \in \mathbb{R}^3 \setminus \overline{\Omega}$, where $$z^* = r^2 |z|^{-2} z$$ is the image of $z$ under inversion with respect to the sphere $\partial B(0, r)$. Of course, $v(x) = u(x)$ in $\Omega$. The expression for $v$ follows by a standard calculation related to the Kelvin transformation in classical potential theory: one needs to verify that $v(x) = u(x)$ for $x \in \partial \Omega$ (a lengthy calculation), that $v$ is harmonic in the complement of $\Omega$, and that it decays at infinity. Since in the complement of $\Omega$ the function $v$ is simply the potential of a point mass $q r |z|^{-1}$ at $z^*$, it follows that $v$ is the potential of a measure with total mass $q r |z|^{-1}$, as desired.

A: Balayage is a positive operator so the measure $\nu$ obtained by sweeping out the positive charge $q\delta_{z}$, onto $\partial\Omega$, is a positive measure as well. The mass of $\nu$ can be expressed in a nice way if we appeal to the (newtonian) capacity $\text{cap}(\overline\Omega)$, the equilibrium measure $\omega_{\overline\Omega}$ of $\overline\Omega$, and its potential $U^{\omega_{\overline\Omega}}$. Indeed,
\begin{align*}
\|\nu\| & =\int d\nu= \text{cap}(\overline\Omega)\int U^{\omega_{\overline\Omega}}d\nu =
\text{cap}(\overline\Omega)\int U^{\nu}d\omega_{\overline\Omega}
\\[10pt]
& =
\text{cap}(\overline\Omega)\int U^{q\delta_{z}}d\omega_{\overline\Omega}= q~\text{cap}(\overline\Omega)\int U^{\omega_{\overline\Omega}}d\delta_{z}
=q~\text{cap}(\overline\Omega)U^{\omega_{\overline\Omega}}(z).
\end{align*}
Such results can be found in the book by Landkof, Foundations of modern potential theory, Chapter IV.
In the case where $\Omega$ is the ball of radius $r$, considered by Mateusz Kwasnicki, one has
$\text{cap}(\overline\Omega)=r$ and $U^{\omega_{\overline\Omega}}(z)=U^{\delta_{0}}(z)=|z|^{-1}$, and thus we recover that the fraction $\|\nu\|/q$ equals $r|z|^{-1}$.


text:
Q: I would like to know if there is a way to sync the checkboxes? is there a way to sync the checkboxes?
for example my screen :
enter image description here
I'm using the mvvm structure
XAML:
<CheckBox
    Grid.Column="0"
    Grid.Row="0"
    Content="{lang:Localization Chk_Users}"
    IsEnabled="True"
    IsChecked="{Binding IsUserMigration}" Margin="20,20,20,20"
/>

 <CheckBox
    Grid.Column="0"
    Grid.Row="1"
    Content="{lang:Localization Chk_Cards}"
    IsChecked="{Binding IsCardMigration}" Margin="20,6,18,34"
>

however I would like to know if there is, for example, if cards are selected, users are also selected automatically
The ViewModel only has the functions to do the migration... nothing related

A: Let say you have a ViewModel like this:
public class MyViewModel
{
    // Fields to be migrated
    public bool IsUserMigration
    {
        get => _isUserMigration;
        set
        {
            if (_isUserMigration!= value)
            {
                _isUserMigration= value;
                OnPropertyChanged(nameof(IsUserMigration));
            }
        }
    }

    public bool IsCardMigration
    {
        get => _isCardMigration;
        set
        {
            if (_isCardMigration!= value)
            {
                _isCardMigration= value;
                OnPropertyChanged(nameof(IsCardMigration));
            }
        }
    }
}

If you want to select IsUserMigration every time IsCardMigration is selected, simply set IsUserMigration to true in the setter or IsCardMigration.
public bool IsCardMigration
{
    get => _isCardMigration;
    set
    {
        if (_isCardMigration!= value)
        {
            _isCardMigration= value;
            OnPropertyChanged(nameof(IsCardMigration));
            IsUserMigration = true;
        }
    }
}


text:
Q: Setting minimum and maximum of scale_size for geom_tex and geom_point independently Is it possible to set a maximum and minimum in scale_size for geom_text and geom_point independently?
For instance, in this plot, I would like make the size of the points or circles range larger than the text (otherwise, the text masks the circles).
ggplot(mtcars, aes(y=mpg, x=cyl,size=cyl)) +
  geom_point(shape=21) +
  geom_text(aes(label=rownames(mtcars),size=hp)) +
  scale_size(range = c(2, 10))

A: You may adjust the text size in geom_text and the general aesthetics (or in geom_point):
ggplot(mtcars, aes(y=mpg, x=cyl,size=15*cyl)) +
    geom_point(shape=21) +
    geom_text(aes(label=rownames(mtcars),size=10*hp/max(hp))) +
    scale_size(range = c(2, 10))


text:
Q: If statement only entering if print before I have a loop that is running until the user clicks a ready button, and then it starts the the loop inside the if-statement, but it only works it there is a print statement before it. Does it have to do with how the Rule Set is static? The Button works no matter what, but it only enters the loop if the print statement is there.
package gameoflife;

public class GameOfLife {

    public static final int HEIGHT = 16;
    public static final int LENGTH = 16;
    public static Grid current;

    public static void main(String[] args) {
        Ui gui = new Ui();
        int time = 0;
        while (true) {
            RuleSet.checkReady();
            //System.out.println(RuleSet.checkReady());
            if (RuleSet.checkReady() == true) {
                //System.out.println("ready!");
                if(time == 0){
                    current = gui.getUserSeed();
                }
                while (time < 100) {
                    current.print();
                    Grid next = new Grid(HEIGHT, LENGTH);
                    for (int i = 0; i < HEIGHT; i++) {
                        for (int j = 0; j < LENGTH; j++) {
                            next.changeState(i, j, RuleSet.determineState(current, i, j));
                        }
                    }
                    current = next;
                    time++;
                }
                break;
            }
        }
    }
}

Rule Class:

public class RuleSet {
public Grid grid;
public static boolean readyToStart = false;

/*checkReady()
 * input:
 * purpose: checks ready flag
 * output:  none
 */
public static boolean checkReady() {
    return readyToStart;
}

/*isReady()
 * input:   none
 * purpose: sets ready flag to ready
 * output:  none
 */
public static void isReady() {
    readyToStart = true;
}

/*determineState()
 * input:   Grid grid, int y, int x
 * purpose: determines the state of a cell for the next
 *          generationusing the four rules below
 * output:  true/false
 */
public static boolean determineState(Grid grid, int y, int x) {
    grid = grid;
    int neighbors = grid.getNeighbors(y, x);
    if (grid.getState(y, x)) {
        return (ruleOne(neighbors) && ruleTwo(neighbors)
                && ruleThree(neighbors));
    } else {
        return (ruleFour(neighbors));
    }
}

/*
 * Rule 1:
 * Any live cell with fewer than two live neighbours dies,
 * as if caused by under-population.
 */
private static boolean ruleOne(int neighbors) {
    return (neighbors >= 2);
}

/*
 * Rule 2:
 * Any live cell with two or three live neighbours
 * lives on to the next generation.
 */
private static boolean ruleTwo(int neighbors) {
    return (neighbors == 2 || neighbors == 3);
}

/*
 * Rule 3:
 * Any live cell with more than three live neighbours dies,
 * as if by overcrowding
 */
private static boolean ruleThree(int neighbors) {
    return (neighbors < 4);
}

/*
 * Rule 4:
 * Any dead cell with exactly three live neighbours becomes a live cell,
 * as if by reproduction.
 */
private static boolean ruleFour(int neighbors) {
    return (neighbors == 3);
} }

Gui

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author peter
 */
public class Ui extends JFrame {

public static JPanel panelGrid;
public static JPanel panelControl;
public static JPanel panelManager;
public static JButton[][] buttons;
public static JButton isReady;
public static JButton nextGen;
public static final int HEIGHT = 16;
public static final int LENGTH = 16;
public Grid temp;

public Ui() {
    setTitle("The Game Of Life");
    setSize(800, 600);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    temp = new Grid(HEIGHT, LENGTH);
    //Creates and sets up the contentPane Container
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(initButtonGrid(), BorderLayout.CENTER);
    contentPane.add(initContButton(), BorderLayout.PAGE_END);
    //add(contentPane);
    setVisible(true);
}

/*initButtonGrid()
 * input:   none
 * purpose: to return initialize the button array, and return the
 *          corresponding JPanel
 * output:  JPanel panelGrid
 */
private JPanel initButtonGrid() {
    buttons = new JButton[HEIGHT][LENGTH];
    panelGrid = new JPanel(new GridLayout(HEIGHT, LENGTH));

    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < LENGTH; j++) {
            buttons[i][j] = new JButton();
            buttons[i][j].setSize(80, 80);
            buttons[i][j].setBackground(Color.white);
            //Creates an action listener that allows user
            //to setup seed
            buttons[i][j].addActionListener(new ActionListener() {
                //Loops through and checks the state of the button/array
                //and then changes state if needed
                public void actionPerformed(ActionEvent e) {
                    for (int i = 0; i < HEIGHT; i++) {
                        for (int j = 0; j < LENGTH; j++) {
                            if (buttons[i][j] == e.getSource()
                                    && !RuleSet.checkReady()) {
                                temp.changeState(i, j, !temp.getState(i, j));
                                if (temp.getState(i, j)) {
                                    buttons[i][j].setBackground(Color.red);
                                } else {
                                    buttons[i][j].setBackground(Color.white);
                                }
                                temp.print();
                            }
                        }
                    }
                }
            });
            panelGrid.add(buttons[i][j]);
        }
    }
    return panelGrid;
}

/*getUserSeed()
 * input:   none
 * purpose: to return the seed the user made with the buttons. I was having
 *          trouble passing the current grid from main() to here in a static
 *          way. Will attempt to update at later point
 * output:  Grid temp
 */
public Grid getUserSeed() {
    return temp;
}

/*initContButton()
 * input:   none
 * purpose: to return initialize the buttons for commands, and return the
 *          corresponding JPanel
 * output:  JPanel panelControl
 */
private JPanel initContButton() {
    panelControl = new JPanel(new GridLayout(1, 2));
    JButton ready = new JButton("Start Simulation");
    ready.setSize(80, 190);
    ready.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            RuleSet.isReady();
            System.out.println("Ready Pressed");
        }
    });
    panelControl = new JPanel(new GridLayout(1, 2));
    JButton nextGen = new JButton("Generation");
    nextGen.setSize(80, 190);
    nextGen.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        }
    });
    panelControl.add(ready);
    panelControl.add(nextGen);
    return panelControl;
}
}

A:
I have a loop that is running until the user clicks a ready button, and then it starts the the loop inside the if-statement, but it only works it there is a print statement before it.

The reason behind your problem is, "when the user clicks the ready button the event handling code is being run in different thread than the thread in which your loop is running". So, the behavior can be unexpected: because you are assuming that readyToStart is being set before you get in to the if condition.
Adding System.out.println makes the thread running the loop to wait for the io and in the meanwhile readyToStart is being set by the other thread.
You can make readyToStart volatile by adding volatile in it's declaration, so that both the threads can have consistant view of it.
public class RuleSet {

           public Grid grid;
           public static volatile boolean readyToStart = false;

           /*Rest of code goes here*/
}

A: First: Please do not use an is...() method to change state. This should be an accessor, not an mutator by naming convention. (You may want to use userIsReady() or setReady() instead).
I assume that you experience a multi-threading issue, since you have the AWT thread and your user thread working with the same value, but have not ensured that there is some kind of synchronization.
You can check if changeing the declaration of the ready flag helps:
public static boolean readyToStart = false; // change this to
public volatile static boolean readyToStart = false;

You can read more about multithreading and concurrency issues here:
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/


text:
Q: Image array in css and retrieve in HTML I want to use one class for 3 buttons but with different background-image such that each button will have its own image. I was looking to declare a background-image array in css and then retrieve the image. However as per my research, there is no array declaration in css. Is this right? If yes what alternative do I have to retrieve each image for each button?
HTML
...
...
<button class="access_item">

         Button_1
</button>

<button class="access_item">

         Button_2
</button>

<button class="access_item">

         Button_3
</button>
...

CSS
.access_item {
  display: inline-block;
  background: none;
  border: 0;
  cursor: pointer;
  appearance: none;
}

.access_icon {
  display: block;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-image: url("https://picsum.photos/id/237/200/300"); //Image 1
  background-image: url("https://picsum.photos/seed/picsum/200/300"); //Image 2
  background-image: url("https://picsum.photos/200/300/?blur"); //Image 3
  margin-bottom: 20px;

}

A: Use the :nth-child() selector. The CSS code will become:
.access_item {
  display: inline-block;
  background: none;
  border: 0;
  cursor: pointer;
  appearance: none;
}

.access_icon {
  display: block;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 20px;

}

.access_item:nth-child(1) > .access_icon {
  background-image: url("https://picsum.photos/id/237/200/300"); //Image 1
}

.access_item:nth-child(2) > .access_icon {
  background-image: url("https://picsum.photos/seed/picsum/200/300"); //Image 2
}

.access_item:nth-child(3) > .access_icon {
  background-image: url("https://picsum.photos/200/300/?blur"); //Image 3
}

A: Maybe some people disagree here. But I would reach for a solution using CSS-IDs or additional CSS-Classes.
Thus you are not restricted to the nesting and the order of the buttons.
v1 Using CSS-IDs HTML:
...
<button class="access_item" id="button_1" >
        Button_1
</button>

<button class="access_item" id="button_2" >
        Button_2
</button>

<button class="access_item" id="button_3" >
        Button_3
</button>
...

v1 Using CSS-IDs CSS:
.access_item {
    display: inline-block;
    background: none;
    border: 0;
    cursor: pointer;
    appearance: none;
}
.access_icon {
    display: block;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-bottom: 20px;
}
#button_1 {
    background-image: url("https://picsum.photos/id/237/200/300"); //Image 1
}
#button_2 {
    background-image: url("https://picsum.photos/seed/picsum/200/300"); //Image 2
}
#button_3 {
    background-image: url("https://picsum.photos/200/300/?blur"); //Image 3
}

v2 Using additional CSS-Classes HTML:
...
<button class="access_item button_1" >
        Button_1
</button>

<button class="access_item button_2" >
        Button_2
</button>

<button class="access_item button_3" >
        Button_3
</button>
...

v2 Using additional CSS-Classes CSS:
.access_item {
    display: inline-block;
    background: none;
    border: 0;
    cursor: pointer;
    appearance: none;
}
.access_icon {
    display: block;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-bottom: 20px;
}
.button_1 {
    background-image: url("https://picsum.photos/id/237/200/300"); //Image 1
}
.button_2 {
    background-image: url("https://picsum.photos/seed/picsum/200/300"); //Image 2
}
.button_3 {
    background-image: url("https://picsum.photos/200/300/?blur"); //Image 3
}


text:
Q: Automatic Mails in ASP.NET MVC When changes occur on some reservation I want everyone involved getting a mail about the changes.
Actually I am not sure how to get this done. But I geuss my first question should be.
How should I check if changes have accord and how am I suppose to know which person people are involved in the changes?
I am using Entity Framework ( Lazy Loading ) in MVC 3.

A: deltu,
this can be resolved in a number of ways. the one that I use today is based on raising an event when the repository is saving changes. not sure what your configuration looks like, but here's a snippet of what I do:
public void SaveChanges()
{
    //_auditDate = DateTime.Now; ignore this in your case
    OnSavingChanges();
    _context.SaveChanges();
    OnSavedChanges();
}

private void OnSavingChanges()
{
    if (SavingChanges != null)
    {
        var eventArgs = new RepositorySavingChangesEventArgs()
        {
            AuditDate = _auditDate
        };
        SavingChanges(this, eventArgs);
    }
}
public event EventHandler<RepositorySavingChangesEventArgs> SavingChanges;

private void OnSavedChanges()
{
    if (SavedChanges != null)
    {
        var eventArgs = new RepositorySavedChangesEventArgs()
        {
            AuditDate = _auditDate
        };
        SavedChanges(this, eventArgs);
    }
}
public event EventHandler<RepositorySavedChangesEventArgs> SavedChanges;

then simple make sure that your client code subscribes to the SavingChanges EventHandler. Job done. You literally only subscribe within the context of where you know the crucial changes are and then fire off an email service call inseide that event handler.
hope this helps.
[edit] in response to comment below, you would raise either of these events in either the service class, the base abstract class, or more simply, in your controller. here's an example of the controller raising the event:
public TimelinesController(IRepository repository)
{
_serviceTasks = new TimelineService(repository);
    repository.SavedChanges +=
        new EventHandler<RepositorySavedChangesEventArgs>(repository_SavedChanges);
}

private void repository_SavedChanges(object sender, RepositorySavedChangesEventArgs e)
{
    var newDate = e.AuditDate;
    /* do something fancy with the audit date */
}

hope this points you in a more 'pointed' direction :)


text:
Q: Uncaught Reference: App is not defined this code is supposed to help do an animation with my website and I don't know what is preventing it. In the debugger console, all i am receiving is a Uncaught reference: app is not defined.
app.skills = {
    init: function () {
        $(".skills h1").blast({
            delimiter: "character",
            tag: "span"
        });
        $(".skills p").blast({
            delimiter: "word",
            tag: "span"
        });
        a = 0;
        $(".skills h1 .blast").each(function () {
            var el = $(this);
            setTimeout(function () {
                el.addClass('animated bounceIn');
            }, a);
            a = a + 80;
        });
        setTimeout(function () {
            $(".skills .blast").removeClass('animated bounceIn');
            $(".skills .blast").css('opacity', 1);
            $(".skills .blast").mouseenter(function () {
                var el = $(this);
                $(this).addClass('animated rubberBand');
                $(this).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                    el.removeClass('animated rubberBand');
                });
            });
        }, 2000);
        a = 0;
        $('.chart').not('.small').each(function () {
            var el = $(this);
            setTimeout(function () {
                el.addClass('animated rotateIn');
                el.circliful();
            }, a)
            a = a + 200;
        });
        a = 0;
        $('.chart.small').each(function () {
            var el = $(this);
            setTimeout(function () {
                el.addClass('animated flipInX');
                el.circliful();
            }, a)
            a = a + 100;
        });
    }
}


text:
Q: Facebook authentication Issue in Rails Application I have created one new user in facebook but I am unable to login. And
  when I am using the old facebook account then its working fine.
I am using omniauth-facebook gem for Facebook authentication. So, for
  that I am using version
gem 'omniauth-facebook', '~> 4.0.0'.

Now graph api version has updated.So, I have added graph api version like this.
"https://graph.facebook.com/v3.0"

But still I am not able to figure out what is the issue.
Can anyone please help me? Thanks


text:
Q: Sharing one huge HTML text in more containers (jQuery) I have specific issue:
I have a couple of divs on HTML page, each with different fixed sizes and set as overflow:hidden, each of containers is powered by jqueryte wisiwig editor (jqueryte.com) so user can change a content of divs interactively.
The point is to ensure more comfortable work with huge texts (like books etc.).
User would insert one big content (also with HTML marks) in some div by editor, but oveflowed part of text (not visible in current div) will be send into next div (assume user will select joined divs before).
For those who are familiar with Adobe InDesign there is exactly the same functionality, but question is if it's applicable on html/css/jquery environment.
Some perfect solution would be that user could edit content in each separate div by editor and content would interactively continue into next joined div, if u understand what i mean.
I have found a couple of tips but all needs either the same width for all divs or non-html content (plain text).
Please guys, is there any posibility to prepare such concept of working with huge HTML-like content?
Thank you very much for any help, regards, Honza.

A: If i understand correctly the scenario is the following: Supporse you have two divs, #divOne and #divTwo of fixed width (not the same) both of them. Then you insert a large HTML into #divOne and you want the invisible context in #divOne to be moved into #divTwo. Is that correct?
If so, you could achive that by identifying if the #div one has a scrollbar how to check if an element has a scrollbar
Then you could write an algorithm where you will parse the HTML and at the same time check if the #divOne has scrollbars. Then you could check for any full stop or question mark and cut the HTMl text there and append it to the $("#divTwo").append().
It is just a scenario and you could see if that works for you.


text:
Q: Error when executing a mysql store procedure I have created a simple stored procedure that will drop a view. I am learning stored procedures in mysql so bear with me,
DELIMITER $$
CREATE PROCEDURE dropView (
    IN viewName varchar(4000)
)
BEGIN

    SET @sql:=CONCAT('DROP VIEW ',@viewName);
        PREPARE dynamic_statement FROM @SQL;
        EXECUTE dynamic_statement;
        DEALLOCATE PREPARE dynamic_statement;

END$$
DELIMITER ;

And i am calling the above like so,
SET @theView = '`Report`;';

CALL dropView(@theView);

I am getting the error message,
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1
I am using mysql 8.0.17
According to this i can use 'CREATE/DROP VIEW' in a prepared mysql.

A: @viewNameis a 9.4. User-Defined Variables and viewName one stored procedure parameter (13.1.17 CREATE PROCEDURE and CREATE FUNCTION Statements), are different variables.


text:
Q: Sending Emails with AWS SES I cant seem to get AWS emails working. I have set up thunderbird to handle the outgoing emails (SMTP) and have set the incoming emails up to be put in a s3 Bucket. The reciving part works well, however I seem to be only able to send to those emails that I have "verified." What could the cause of this be?
Also if anyone had any tips on how to set up my email better I would also be interested. Ideally I would like to be able to send and recieve domain emails via gmail / or another web based service. I have heard AWS has something called workmail, but really I am looking for somthing free. Had this set up, it was working nicely, but seemed to stop working, and I cant seem to fix it: (tells me the MX records are not configured correctly, but I did have it working, the MX records are the same as what they were when it was working)
http://improvmx.com/


text:
Q: xcodebuild: find where the output app file is Is there anyway to specify where to put the output file (ie .app) for xcodebuild? By default it is in:

/Users/myusername/Library/Developer/Xcode/DerivedData/Project-crkyjjbuqqnqqvfxehsjsarzlbbr/Build/Products/Release-iphoneos/Project.app

As I need to find the output Project.app file, if there is no way to specify the path, can I use a script to look for that "/Users/myusername/Library/Developer/Xcode/DerivedData/" folder and inside it find the one with latest modified date and prefix "Project-"? What does the script look like?
Thanks

A: Override the CONFIGURATION_BUILD_DIR environment variable in an xcodebuild argument. For instance, this command would put its build products under "/tmp/sportsball/":
xcodebuild -workspace Sportsball.xcworkspace -scheme "Sportsball Debug" -configuration Debug clean build CONFIGURATION_BUILD_DIR=/tmp/sportsball/


text:
Q: Regex to test if string begins with http:// or https:// I'm trying to set a regexp which will check the start of a string, and if it contains either http:// or https:// it should match it.
How can I do that? I'm trying the following which isn't working:
^[(http)(https)]://

A: Case insensitive:
var re = new RegExp("^(http|https)://", "i");
var str = "My String";
var match = re.test(str);

A: Your use of [] is incorrect -- note that [] denotes a character class and will therefore only ever match one character.  The expression [(http)(https)] translates to "match a (, an h, a t, a t, a p, a ), or an s."  (Duplicate characters are ignored.)
Try this:
^https?://

If you really want to use alternation, use this syntax instead:
^(http|https)://

A: ^https?://

You might have to escape the forward slashes though, depending on context.

A: ^https?:\/\/(.*) where (.*) is match everything else after https://

A: ^ for start of the string pattern,
? for allowing 0 or 1 time repeat. ie., s? s can exist 1 time or no need to exist at all.
/ is a special character in regex so it needs to be escaped by a backslash \/
/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false

A: This should work
^(http|https)://

A: (http|https)?:\/\/(\S+)
This works for me
Not a regex specialist, but i will try to explain the awnser.
(http|https) : Parenthesis indicates a capture group, "I" a OR statement.
\/\/ : "\" allows special characters, such as "/"
(\S+) : Anything that is not whitespace until the next whitespace

A: This will work for URL encoded strings too.
^(https?)(:\/\/|(\%3A%2F%2F))

A: Making this case insensitive wasn't working in asp.net so I just specified each of the letters.
Here's what I had to do to get it working in an asp.net RegularExpressionValidator:
[Hh][Tt][Tt][Pp][Ss]?://(.*)

Notes:

*

*(?i) and using /whatever/i didn't work probably because javascript hasn't brought in all case sensitive functionality

*Originally had ^ at beginning but it didn't matter, but the (.*) did (Expression didn't work without (.*) but did work without ^)

*Didn't need to escape the // though might be a good idea.

Here's the full RegularExpressionValidator if you need it:
<asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server"
    ControlToValidate="txtURLHeaderEdit"
    ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
    ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>


text:
Q: Elasticsearch filter by several geo_points with different weights I have a number of documents that, apart from other fields, have a number of geo_points associated with them. I want to find all documents that are associated with a particular city. To that end, I also have an index of cities, I search it first and get a list of coordinates with the _scores from that search. Now I want to pass that data to the document search and multiply the score of the found documents by the corresponding city score.
Assuming the first query returns a list of tuples like [(city_coords, city_score), (...)], I want to build the query to the document index using the function_score and the functions array with each city as a separate function with its separate score.
However, when I construct the query in its simplest form, it fetches all the documents in my index. Here's what the query I have made:
{
    'query': {
        'function_score': {
            'functions': [
                {
                    "filter": {
                        "geo_distance": {
                            "distance": "1km",
                            "distance_type": "plane",
                            "points": city_coords
                        },
                    },
                    'weight': city_score
                }
            ]
        }
    }
}

Am I missing something? How do I get only the documents that are associated with that particular city?

A: Since you don't specify a query in your function_score part, Elastic assume a match_all query. So it returns all documents and add a boost for the documents near the selected queries.
You should add a specific query in your function_score part that will filter out any document that is not near enough of the selected cities. Something like
{
    "query": {
        "function_score": {
            "query": {
              "bool": {
                "should": [
                  {
                    "geo_distance": {
                        "distance": "1km",
                        "distance_type": "plane",
                        "points": city_coords1
                    }
                  },
                  {
                    "geo_distance": {
                        "distance": "1km",
                        "distance_type": "plane",
                        "points": city_coords2
                    }
                  },
                  ... and so on
                ]
              }
            },
            "functions": [
                {
                    "filter": {
                        "geo_distance": {
                            "distance": "1km",
                            "distance_type": "plane",
                            "points": city_coords
                        },
                    },
                    "weight": city_score
                }
            ]
        }
    }
}


text:
Q: Is there a way to easily share Workspace settings (folder mappings) for Visual Studio Online / Team Foundation Server? I want to move from having a single Visual Studio (Online) workspace for all my Projects to having a separate Workspace for each Project (because: http://blogs.msdn.com/b/phkelley/archive/2013/05/30/using-multiple-workspaces-with-visual-studio.aspx).
This all works out fine, but now I want to roll out this new approach to my colleagues and have come across the problem that it looks like there is no easy way to share Workspace settings with them.
Here is the official advice from an MSDN article for VS 2013 titled "Create and work with workspaces":

Q: Can I reuse and share folder mappings?
A: Yes. If you want to reuse or share folder mappings with other team
  members, you can copy the folder mappings. Simply open the shortcut
  menu in the Working folders list and choose Copy. To reuse the folder
  mappings, paste them into another version control workspace or a build
  definition workspace. To share the folder mappings with your
  teammates, paste them into a text file and then share the file.
source: http://msdn.microsoft.com/en-us/library/ms181383.aspx#copy_paste

I think the answer should have been "No. There is no way exporting and importing Workspace folder mappings". The suggestion to "paste them into a text file and share the file" is simply hilarious.
My research has turned up that for the server version of Team Foundation Server there is a thing called workspace templates:

With workspace templates you can provide your developers with a
  standard way of organizing their workspace. Your whole team uses the
  same structure and enjoys all the benefits.
http://roadtoalm.com/2011/10/25/hidden-gems-in-tfspart-6-managing-workspaces-in-tfs-with-workspace-templates/

As far is I know this is not available in Visual Studio Online (the cloud version of Team Foundation Server).
So my question is:
Is there a way to easily share Workspace settings (folder mappings) for Visual Studio Online / Team Foundation Server?
If not, does anybody know of a better way than the copy / paste / share suggestion?

A: I'll answer my own question: yes, there is an easy way.
Install "Microsoft Visual Studio Team Foundation Server 2013 Power Tools": https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f
After installing you will have a new option in Team Explorer: Team Members. Click it.

Click "Team Utilities".

Click "Add Template".

Select the Workspace you want to create a template for and click "Create".

Review the settings of the template and click "Create".

Your new template will be appear under "Workspace Templates" for all other team members after they have installed the Power Tools. When they click the template a Create Workspace dialog will open, based on the settings in the template.

Thanks to @EdwardThomson for pointing me in the right direction.


text:
Q: How to make column unique and index it in Laravel Migration? I would like to alter my one of my column on my table - and make them a unique index.
I tried :
public function up()
{
    Schema::table('inventories', function($table)
    {
        $table->string('sku',255)->unique();
    });
}

I get :

What is the most efficient way to do that ?

A: You can add indexes separately from their definition. As documented here
Schema::table('inventories', function($table)
{
    $table->unique('sku');
});

A: I got it.
I did this :
public function up()
{
    DB::update('alter table `inventories` modify `sku` VARCHAR(200) UNIQUE NOT NULL');
}

and now It works  :


text:
Q: Navigation menu not showing pages under subsite in navigation menu SharePoint 2010 I have been trying to have my navigation menu show a dropdown (hierarchical) list. I followed the tutorial here. But, when i try to create a new page, it does not show under my subsite.
For example, I have SiteA-> SubSiteA1 (showing)-> Page.aspx (not shown in the navigation menu).
I have been looking on google and this forum but I cant see to find a solution! I tried re-activating the Server Publishing feature but it does not work :(

A: If you activate the SharePoint Server Publishing Infrastructure feature, you need go to Site Settings > Navigation, then select Show subsites in Global Navigation section.


text:
Q: Puppeteer performance leaks I am using a puppeteer and a puppeteer-cluster to take screenshots of the received HTML. To "bypass" the Node.js' single-thread processing, I use several Docker containers.
The problem is that it randomly prolongs a render time - once the same HTML is rendered in 200 ms and the next time (same configuration, environment etc.) it is 8.2 s. Node's logs does not contain any errors.
Does it have any solution?

A: There should be no reason to "bypass the Node.js' single-thread processing" as most puppeteer actions are executed asynchronously. This sounds to me like you are solving a problem that does not really exist.
When you are using docker in addition to your script, it also makes sense that the processes are slower (prolonging the render time) as in addition to your script, the OS also needs to run docker.
Check system resources
I'm assuming your system is not capable of running multiple docker containers in addition to multiple Chrome instances in each container. Monitor CPU and memory to see if you are hitting any limitations.


text:
Q: Can entity framework database-first successfully build models from any SQLServer db? I'm considering using entity framework database-first approach. The database in question uses various non-standard techniques, eg 'informal' foreign keys. I'd like to confirm that it's still possible to create a usable EF model from this database, even if all the relationships are not recognised?

A: Yes, you can do this.  Generate the model from the database as normal, then modify the generated entities in order to introduce the relationships.  You'll need to set a Null database initializer to tell EF it should not try and update the database to match its model:
Database.SetInitializer(new NullDatabaseInitializer<MyContext>());

There's no requirement for foreign keys to exist in the database to match your model - as long as the navigation properties have been added on the entities, EF will generate the correct SQL queries accordingly.
I would recommend the use of the [ForeignKey] attribute to clarify the names of your foreign key fields for when they don't conform to EF's expected patterns (or you could modify the Conventions accordingly).  For example...
public class Child {
    // ...

    public int Parent_ID { get; set; }     // <-- non-standard name

    // Add these to introduce the navigation property without a formal relationship
    [ForeignKey("Parent_ID")]
    public virtual Parent Parent { get; set; }
}

I have used this approach on a MySQL database with no foreign keys at all.


text:
Q: Ajax not parsing data correctly? Knowing me, I've probably done something wrong, but I was having a look at how parsing data from Javascript to PHP looked like using ajax and it looked fine but it doesn't want to send the data through and update it in my Database.
All that happens is a dialogue box shows up with nothing inside.
AJAX:
    $.ajax({
        url: 'updateCredits.php',
        type: 'GET',
        data: {
            credits: totalcash
        },
        success: function(data){
            alert(data);
        }
    });

PHP:
<?php

require 'steamauth/steamauth.php';
include ('steamauth/userInfo.php');
include('mysql/config.php');

if(isset($_SESSION['steamid'], $_GET["credits"]))  {
    $credits = $_GET['credits'];
    mysqli_query($db,"UPDATE set credits = credits + '".$credits."' WHERE steamid = '".$steamprofile['steamid']."'");
} else {
echo 'An Error has occurred, this is either due to you not being logged in or something went wrong!';

}

?>

A: You are not returning anything from PHP snippet  on success
 <?php require 'steamauth/steamauth.php';
 include ('steamauth/userInfo.php');
 include('mysql/config.php');
 if(isset($_SESSION['steamid'], $_GET["credits"]))
 {
   $credits = $_GET['credits']; mysqli_query($db,"UPDATE set credits = credits + '".$credits."' WHERE steamid = '".$steamprofile['steamid']."'");
echo 'Success fully updated';
} else { echo 'An Error has occurred, this is either due to you not being logged in or something went wrong!'; } ?>


text:
Q: Using strings saved in variables in coding I would like to know how to use stings stored in a variable/vector/matrix etc
in the middle of coding in order to edit names of variables/vectors or functions
e.g.
instead of creating the below
v_name1<- rep(5,10)
v_name2<- rep(30,10)
.
.
.

function_name1<- { ... }
function_name2<-{ ... }

.
.
.

using a for loop instead
I already know e.g. (this is just an example to illustrate)
  s<-c("name1","name2", ... )

for (i in 1:(length(s))) {
    eval(parse(text=paste("v_",s[1],"<-c(rep(i,10))", sep="")))
    }
        v_name1
         [1] 1 1 1 1 1 1 1 1 1 1

I have two problems :
1) How do you make this for functions, I get the below error?  e.g.
st<- "(x,y)<-{ 3*x + y}"
eval(parse(text=paste("function_",s[1],st, sep="")))

> eval(parse(text=paste("function_",s[1],st, sep="")))
Error in eval(expr, envir, enclos) : object 'x' not found

2) is there any faster/smarter way to do just that (substitute part of the coding with strings saved into another object) ?
I do not want to share what is my end goal or why I need to do this, I just want to know if the 2 things above are plausible.

A: The very first comment told you to use lists. You can put anything into a list, data as well as functions:
set.seed(42)
v <- list(uk = rnorm(10, mean = 5), us = rnorm(10, mean = 30), fr = rnorm(10, mean = 300))
funs <- list(uk = mean, us = median, fr = min)

You can then do this:
country <- "us"
funs[[country]](v[[country]])

R is not a language with macros. Work with the language and not against its design. And forget eval(parse()).


text:
Q: React functional component state variable's setFunction is not working when it is called through another function reference I have found this error while trying to build another React app. So I am only asking the main issue here in a demo app, I might not be able to change any rendering methods here since it is not the actual project.
Issue in simplified form -> I was building a app where two count will be shown and a + button will be there next to that count value. When the button is clicked the count should be increased by 1. Unfortunately when I try to click on the button the value is increasing only the first time. After that the value is not even changing. But when I am implementing the same using Class component its working as expected.
Functional Component
import React, { useState } from "react";

function Page(props) {
    const [count, setCount] = useState(0);

    const [content, setContent] = useState({
        button: (value) => {
            return <button onClick={() => handlePlus(value)}>+</button>;
        },
    });

    function handlePlus(value) {
        console.log("value=", value);
        const data = count + 1;
        setCount((count) => data);
    }

    return (

            Functional Component Count = {count}
            {content.button(10)} // 10 will be replaced with another variable

    );
}

export default Page;

Class Component
import React, { Component } from "react";

class PageClass extends Component {
    state = {
        count: 0,
        content: {
            button: (value) => {
                return (
                    <button onClick={() => this.handlePlus(value)}>+</button>
                );
            },
        },
    };

    handlePlus = (value) => {
        console.log("value=", value);
        this.setState({ count: this.state.count + 1 });
    };

    render() {
        return (

                Class Component Count = {this.state.count}
                {this.state.content.button(10)} // 10 will be replaced with another variable

        );
    }
}

export default PageClass;

App.js
import "./App.css";
import Page from "./components/Page";
import PageClass from "./components/PageClass";

function App() {
    return (

            <Page />
            <PageClass />

    );
}

export default App;

However, If I replace that content state variable with normal const variable type and it is working as expected.
Below is working when I am not using any hooks to render the button.
But this is not helpful for my case.
    const content = {
        content: () => {
            console.log(count);
            return <button onClick={() => handlePlus(value)}>+</button>;
        },
    };

I was trying to create some re-usable components and hence I wanted to have that function in state variable which return button tag, so that I can implements some other logic there.

A: The value will be missing since you're passing a hard-coded 10.
I'd recommend simplifying the handlePlus to just:
setCount(c => c + 1);

Then set the onclick like so:
<button onClick={handlePlus}>+</button>

And your code will work as expected as you can see in this snippet:

const { useState } = React;

const Example = () => {

    const [count, setCount] = useState(0);

    const [content, setContent] = useState({
        content: (value) => {
            return <button onClick={handlePlus}>+</button>;
        },
    });

    function handlePlus(value) {
        setCount(c => c + 1);
    }

    return (

            {count}
            {content.content(10)}

    );
}
ReactDOM.render(<Example />, document.getElementById("react"));

That said, I'd recommend removing the button from the hook, and just render it yourself:

const { useState } = React;

const Example = () => {

    const [count, setCount] = useState(0);

    function handlePlus(value) {
        setCount(c => c + 1);
    }

    return (

            {count}
            <button onClick={handlePlus}>+</button>

    );
}
ReactDOM.render(<Example />, document.getElementById("react"));

See React documentation about the c => c + 1 syntax


text:
Q: Email Blast to multiple emails - W/h Rails . I am trying to create a feature where a user is able to dynamically email a group of people at once. In my demo app a user is able to create a event and anybody is able to book a pass to that event by entering in a email.
Currently I have a Event Model That belongs to one user.
And a booking model that belongs to the event.
In short I want the user to be able to email everyone who has a completed a booking for the Event.
I have no idea where to start so I was hoping to be guided in some sort of direction.
I know this is pretty broad but any help would be appreciated.


text:
Q: how to use abp repository in global.aspx? In the mvc5 project, I want to take database data fill in Redis at Application_Start. but at that time IocManager registration not completed. What should I do to solve this problem (don't use ADO.Net)

A: You can feed your Redis application in PostInitialize method of WebMvcModule.cs class.
In the sample code, I am retrieving users from the database.
public override void PostInitialize()
{
    var userRepository = IocManager.Resolve<IRepository<User, long>>();
    var users = userRepository.GetAllList();
    /* Feed the Redis here... */
}


text:
Q: Kleene normal form : elementary? The Kleene normal form explains there are primitive recursive functions $T$ (a predicate indeed) and $U$ such that for any computable function $\phi_n$, and for any $x\in\mathbb N$ :
$$\phi_n(x)=U(\mu_yT(n,x,y)) $$
This is a very basic theorem of computability. I was wondering recently if $T$ and $U$ could be considered to be in the elementary function class.
As $U$ is very simple, and if the "program trace" $y$ is encoded with a simple method, I have no doubt that $U$ can be made elementary. Is there any reference to this fact ?
Even $T$ (a predicate that can be seen as a function into $\{0,1\}$) juste compute the program $\phi_n$ from $n$ and verify that $y$ seen as a list of actions is indeed coherent with $\phi_n$ and $x$. Even that seems to be very simple enough for elementary, if you consider that the encoding of $\phi_n$ into $n$ is simple. But I found nowhere the fact that $T$ can be elementary.
So, am I wrong into thinking that $T$ and $U$ can be considered elementary or did I miss well known references about that fact ?
Can it be considered even simpler (like lower elementary or even lower) ?

A: In this book, it proved there exists a Elementary function $C(a,b,c,d)$ such that for every $n$ and $k$:
$$\phi_n^k(a_1,...,a_k)=r\Leftrightarrow\exists q\:C(n,<a_1,...,a_k>,r,q)=1$$
and $<a_1,...,a_k>=\prod_{i=0}^{k}P_i^{a_i+1}$
So we can define $U(n)=\pi_1(n)$, and $$T(n,x,y)\simeq C(n,x,\pi_1(y),y)$$ $<n,m>$, $\pi_1(n)$ and $\pi_2(n)$ are Cantor Pairing function and its decoding functions. So $T$ and $U$ can defined Elementary. But $T$ can defined in smaller class of function. Let $E$ be the smallest class of functions such that:

*

*$\left \{S(n),Z(n),+(n,m),*(n,m),=(n,m),P^i_k(n_1,...,n_k) \right \}\subseteq E$

*$\left \{ g(n_1,...,n_k),f_1(\vec{x}),...,f_k(\vec{x}) \right \}\subseteq E\Rightarrow g(f_1(\vec{x}),...,f_k(\vec{x}))\in E$

*$f(\vec{x},n)\in E\Rightarrow g(\vec{x},n)=\min y\leq n [f(\vec{x},y)=1]\in E$

Ii is easy to see that $<n,m>$, $\pi_1(n)$ and $\pi_2(n)$ are elements of $E$. Define $D^1_1(n)=\pi_2(n)$, then for every $k>1$ define $D^1_k(n)=\pi_2(D^1_{k-1}(n))$. Also Define $D^2_1(n)=\pi_1(n)$, then for every $k>1$ define $D^2_k(n)=\pi_1(D^1_{k-1}(n))$.
We know $C(n,x,\pi_1(y),y)$ is a recursive function, so by MRDP Theorem there exists two  polynomial $t_1(n,x,y,r,q_1,...,q_u)$ and $t_2(n,x,y,r,q_1,...,q_u)$ with natural coefficients such that:
$$C(n,x,r,y)=1\Leftrightarrow \exists q_1,...,q_u(t_1(n,x,r,y,q_1,...,q_u)=t_2(n,x,r,y,q_1,...,q_u))$$
Now define
$$L(n,x,y)=t_1(n,x,D^2_1(y),D^2_2(y),D^2_3(y),...,D^2_{u+2}(y))$$
$$R(n,x,y)=t_2(n,x,D^2_1(y),D^2_2(y),D^2_3(y),...,D^2_{u+2}(y))$$
Therefore
$$T(n,x,y)\simeq\:=(L(n,x,y),R(n,x,y))$$
and $U(n)=\pi_1(n)$. It is easy to check that $\phi_n(x)\simeq U(\mu_y T(n,x,y))$ Also $U$ and $T$ are in $E$ which is a smaller class then elementary functions.


text:
Q: drawContours around detected document using opencv for android gives strange bug I am new to OpenCv4Android. I am trying to auto detect document using OpenCv4Android sdk. Initially i have gone through issue of landscape opencv camera . Somehow i managed to change the orientation of opencv JavaCameraview to portrait. I made following changes in default classes of opencv sdk to orient opencv camera in portrait :
1) In CameraBridgeViewBase class
 Matrix matrix = new Matrix();
 matrix.setRotate(90f);
 Bitmap bitmap = Bitmap.createBitmap(mCacheBitmap, 0, 0, mCacheBitmap.getWidth(), mCacheBitmap.getHeight(), matrix, true);

2) now in drawbitmap method replace above bitmap with mCacheBitmap
3) now , In JavaCameraView class
if ((getLayoutParams().width == ActionBar.LayoutParams.MATCH_PARENT) && (getLayoutParams().height == ActionBar.LayoutParams.MATCH_PARENT))
       mScale = Math.min(((float)height)/mFrameWidth, ((float)width)/mFrameHeight);
else
       mScale = 0;

After above changes , i am able to orient camera in portrait mode . But , having strange issue in detecting document . See below images

As you can see in first image , before customization i can detect paper in full green color . And in 2nd image you can see the bug of drawing line  (drawContours) around paper
what i follow to detect paper is : GaussianBlur -> Canny edge detection -> findContours  -> drawContour
In OnCameraFrame method :
     mRgba = inputFrame.rgba();
   Mat mGray = new Mat();
   Mat edged = new Mat();
  Imgproc.cvtColor(mRgba,mGray,Imgproc.COLOR_BGR2GRAY);
  Imgproc.GaussianBlur(mRgba,mGray,new Size(5,5),0);

-> and then finding contours
Imgproc.findContours(edged, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

-> Then i found the largest contour and finally the drawContours on that
Imgproc.drawContours(mRgba, contours, maxI, new Scalar(0, 255, 0), 5);

I don't know where i m wrong..! Please help me to solve this strange issue.
@Rick M.  following is the original image :

@ilke444 , following is the image after edge detection which is perfectly what i want :


text:
Q: Reading the content of file section wise in java I want to read the content of any files like doc, pdf, ppt etc section or paragraph wise in java, because i want to retrieve a particular section of a file (if have) instead of retrieving the content of whole file.. Please can anyone tell me, How can i read the content of any file either section or paragraph wise………..
Thanks

A: This depends entirely on the format of the file in question. For example, when you have a .docx file, you can employ some XML parser and then iterate through the result or use XPath to find all paragraphs, sections or whatever you wish to extract.
For other file formats you will have to find a different approach. There is no single way to extract a specific part of any file, as different file types have different ways of storing data. Most likely, you will have to collect a bunch of libraries, one for each file type.


text:
Q: how to efficiently convert large dictionary to matrix in python I wonder what's the most efficient way to convert a very large dictionary to matrix, for example:
{'0': [1, 2, 3....99999999, 100000000], '1': [1, 2, 3....99999999, 100000000], '2': [1, 2, 3....99999999, 100000000], '3': [1, 2, 3....99999999, 100000000]......'999': [1, 2, 3....99999999, 100000000], '1000': [1, 2, 3....99999999, 100000000]}
to this
list([[1, 1, 1, 1.....1, 1, 1, 1, 1],
[2, 2, 2, 2....2, 2, 2, 2, 2],
.....
[99999999, 99999999, 99999999, 99999999....99999999, 99999999, 99999999, 99999999],
[100000000, 100000000, 100000000, 100000000...100000000, 100000000, 100000000, 100000000]])