text:
Q: Blas SGEMM launch failed I just installed  TensorFlow-GPU 1.0.1 on Win10 GTX GEFORCE 850M with CUDA 8.0 and Cudnn v5.1.
when I try to figure out if the installation was successful, I run the

mnist_with_summaries.py

in

C:\Users...\Anaconda3\Lib\site-packages\tensorflow\examples\tutorials\mnist

When I run the code in Jupyter Notebook, it prints

Accuracy at step 0: 0.068
Accuracy at step 10: 0.6795
Accuracy at step 10: 0.6795
Accuracy at step 20: 0.8062
Accuracy at step 30: 0.8455
Accuracy at step 40: 0.8737
Accuracy at step 50: 0.8735
Accuracy at step 60: 0.8851
Accuracy at step 70: 0.8815
Accuracy at step 80: 0.8863
Accuracy at step 90: 0.8918

And the kernel just died after print above message.
When I try to run the code in command prompt, it returns error:

failed to create cublas handle
attempting to perform BLAS operation using StreamExecutor without BLAS support
Internal error: Blass SGEMM launch failed: a.shape=(10000,784),b.shape=(784,500)

And this Internal error message appears three times.( too many error message, I just write down something I think useful. If anyone need more information, tell me).
I then try to run:
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))

And the output is:
[[ 22. 28.]
[ 49. 64.]]
This time the code runs without error.
But it should output:
Device mapping:

/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GTX 850M
id: 0000:05:00.0
b: /job:localhost/replica:0/task:0/gpu:0
a: /job:localhost/replica:0/task:0/gpu:0
MatMul: /job:localhost/replica:0/task:0/gpu:0

[[ 22.  28.]
[ 49.  64.]]
I am totally lost. Could someone tell me why?

A: How much memory do you have on your graphics card? You may be running out of memory. There are ways to force TensorFlow to limit memory usage-- see: How to prevent tensorflow from allocating the totality of a GPU memory?
But I wonder if TF doesnt handle low memory situations gracefully.


text:
Q: How to stop Yarn Package Manager script from CLI https://yarnpkg.com/en/docs/cli/
Is there a way to stop what is started from the command "yarn run"? Is my only option to lookup the process number and call kill on it?

A: The usual way ctrl-c should work. If it doesn't work, than you have bug in the script. The script's author missed handler for shutdown (SIGINT/SIGTERM/etc).

A: I had a similar issue having it running after ctl+c and then I thought, maybe it is just running on the cache
so went to http://localhost:3000/

ctrl+F5

which forces refresh without cache showed me that the actual project wasn't really running anymore!
;)
*hadn't it worked I would have had to sudo kill the 3000 port

A: I know this is a well-answered question. However, it behaved once very strange when I was running a sample React code which was auto-created by the create-react-app CLI, on my Windows 10.
After hitting Ctrl+C, which is the most suggested standard way to stop the yarn run, though I got back the command prompt, there was a ghost process lingering around there, which was still actively listening to 3000(default) port, and localhost:3000 was working as normal.
So finally this is how I fixed it:

*

*netstat -ano | grep ":3000" (yeah, I ran this from my git-bash instead of command prompt!)

*Noted down the PID of the line where it says LISTENING on 3000

*Pressed Ctrl+Shift+Esc to open the Task Manager

*Went to the Process tab

*Right clicked on one of the headings, say Name

*Selected PID --> This added the PID column to the display

*Located the PID in question

*Right clicked on it and clicked "End task"

Luckily Windows knew how to kill that misbehaving, ghost process and the port became free for me.
NOTE: Prior to the above-mentioned steps, I tried to kill that PID from git-bash using the famous (or notorious as per its meaning?? >8)) kill -9 command. It was responding back with no such PID msg, however netstat -ano was clearly displaying the PID and browser was proving that the ghost process is up and alive!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: A  may have only one child element using react-router-dome. i i have used every peace of solution that were available in this forum,
installed new dependency... but still getting the error.
this on is my index file.
'''
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter} from 'react-router-dom';
import "./index.css";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import "bootstrap/dist/css/bootstrap.css";
import "font-awesome/css/font-awesome.css";
import { O_RDWR } from "constants";

ReactDOM.render(<BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root"));
registerServiceWorker(); '''

and this one is the app file
'''
    import React, { Component } from "react";
    import { BrowserRouter ,Router,Route,Redirect,Switch } from 'react-router-dom';
    import Movies from "./components/movies";
    import Customer from  './components/customer';
    import Rental from  './components/rental';
    import NotFound from  './components/notFound';
    import "./App.css";

    class App extends Component {
      render() {
        return (

         <Router>
         <main className="container">
     <Route path="/movies" component={Movies} ></Route>
<Route path="/customer" component={Customer}></Route>
        <Route path="/rental" component={Rental}></Route>
        <Route path="/notFount" component={NotFound}></Route>
         </main>></Router>

        );
      }
    }

    export default App;

A: You don't need to surround your routes with Router if you already have your App surrounded in your index.js file.

A: i found the answer of my question...
i have just closed my <App /> in index.jsx in curly braces like this
 ReactDOM.render(<BrowserRouter>{ <App />} </BrowserRouter>, document.getElementById("root"));

and it workef for me.i don't know what is logic behind this.


text:
Q: error while using locallydb in ari-client node.js _http_outgoing.js:299
    value = value.replace(/[\r\n]+[ \t]*/g, '');
                  ^
TypeError: undefined is not a function
    at storeHeader (_http_outgoing.js:299:19)
    at ClientRequest.OutgoingMessage._storeHeader (_http_outgoing.js:225:9)
    at ClientRequest._implicitHeader (_http_client.js:184:8)
    at ClientRequest.OutgoingMessage.end (_http_outgoing.js:513:10)
    at createRequest (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/node_modules/shred/lib/shred/request.js:532:16)
    at new Request (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/node_modules/shred/lib/shred/request.js:79:3)
    at Object.Shred.request (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/node_modules/shred/lib/shred.js:47:12)
    at ShredHttpClient.execute (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/lib/swagger.js:1314:21)
    at SwaggerHttp.execute (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/lib/swagger.js:1134:34)
    at new SwaggerRequest (/root/.nvm/v0.11.13/lib/node_modules/ari-client/node_modules/swagger-client/lib/swagger.js:1099:27)


text:
Q: When does a FileSystemWatcher.Created event fire within a directory? I am currently designing a Windows Service that will watch a folder for a file which is copied from another folder automatically. Will an event fire as soon as it sees this copy happening or after when the copy has completed?
Or is best to poll the folder every minute lets say?

A:
Will an event fire as soon as it sees this copy happening

Yes.

Or is best to poll the folder every minute lets say?

That too, as a FileSystemWatcher can miss certain events, especially under stress (for example when a lot of files are being created in rapid succession).


text:
Q: Feeding command line from the bash script Is there a way to create a bash script that when run would feed the command line with some text (command to execute) and place the cursor at the end?
So it should not execute the command, it would only happen if I press [Enter] key. I just want to be able to sometimes change some of the parameters that are in the command.
Example:
    # ./do_command.sh
    # some__very_long_command_with_plenty_of_params param1 param2 param3 | <- and the cursor
is here waiting for me to just approve hitting the [Enter] or possibly tweak the params before doing so

What I have so far is just the script echo'ing the command, which requires me to copy-paste it.

A: Not sure you can achieve this exactly using only Bash. Some additional features from your terminal application might be needed.
The options I can think of:

*

*write a Bash function with optional parameters for each very long command with plenty of params. The function can also print the command and ask for confirmation ;

For instance:
myfunc() {
   param1=${1:default1}
   param2=${1:default2}
   cmd="command --param $para1 --param $param2"
   echo running $cmd
   read -p "<ENTER> to run, <CTRL-C> to abort"
   $cmd
}

*

*use a text completion tool such as Dash, TextExpander that will prompt your for the arguments when you write a specific sequence of characters and write the result when you press ENTER;

*use Bash aliases with online expansion: create an alias for each of the very long command with plenty of params, and then type the alias, but do not press enter (yet), press CTRL-ALT-E ; the line will expand and you will be able to review, modify, and then press ENTER.
For instance:
$ aliase myfunc="command --param 1 --param 2"
$ myfunc <CTRL-ALT-E>
$ command --param 1 --param 2

*

*use 'permanent history with hashtags': run the command with the very long command with plenty of params once, but terminate with a comment to give that line a 'name'. Then, you can use CTRL-R to search the name ('hashtag')

For instance:
$ command --param 1 --param 2 # myfunc

Then type CTRL-R my
(reverse-i-search)`my': command --param 1 --param 2 # myfunc

to retrieve the command.

A: do_command is really just a wrapper around the read command.
cmd="some__very_long_command_with_plenty_of_params"
args=("foo bar" "param2" "param3")
read -e -i "$(printf '%q' "$cmd"; printf ' %q' "${args[@]}")" cmd
eval "$cmd"

Generally, eval should not be used, but here, you are specifically trying to execute an arbitrary command, which is what eval is designed to do. This is no more dangerous than typing your command directly at the bash prompt.
The -e command tells read to use the Readline library to edit the command line (just like the regular prompt). -e provides a default value. The printf commands ensure that the command name and the default arguments are printed in a way that can be reused with the eval command. Be aware that %q doesn't use quotes; it uses a backslash to escape only those characters that must be escaped, so the argument foo bar is displayed as foo\ bar, not "foo bar" or 'foo bar'.


text:
Q: Isomorphism involving the opposite of a ring Given a ring $R$, its opposite ring $R^{\text{op}}$ is defined as the ring formed by considering the same underlying set of $R$ with the same addition but with multiplication performed in the reversed order. Let's note the multiplication in $R^{\text{op}}$ by $*$. The ring $R^{\text{op}}$ is a left $R$-module with the multiplication in $R$.
We have that $R^{\text{op}}$ and $R$ are isomorphic as left $R$-modules (being the identity map one such isomorphism) and then $\mathrm{End}_{R}(R^{\text{op}})$ and $\mathrm{End}_{R}(R)$ are isomorphic as rings.
If $R$ is a unital ring we have a ring isomorphism $\phi:R \rightarrow \mathrm{End}_{R}(R^{\text{op}})$ given by $\phi(a)(x) = a * x$.

If all this is correct, then $R$ and $\mathrm{End}_{R}(R)$ are isomorphic as rings. Is this OK?

I'm confused because if I write down the isomorphisms and perform the composition I don't get a ring isomorphism between $R$ and $\mathrm{End}_{R}(R)$. But I don't know where is the error. I think that the fallacious step is when I claim "...then $\mathrm{End}_{R}(R^{\text{op}})$ and $\mathrm{End}_{R}(R)$ are isomorphic as rings". But I don't see why.

A: The endomorphism ring of $R$ as a left $R$-module (equivalently, of $R^{op}$ as a right $R^{op}$-module) is $R^{op}$, which need not be isomorphic to $R$.
The correct statement for $R$ is then that $R$ is naturally isomorphic to the endomorphism of $R$ as a right $R$-module. This is Cayley's theorem for rings, and is a corollary of the (enriched) Yoneda lemma (although it also admits a straightforward direct proof).


text:
Q: Bootstrap 3 form-control class issue? I am using twitter bootstrap 3. I have an issue with table colspan attribute in chrome only.As described in the bootstrap documentation that form-control class has 100% width, but when i applied it on the input box inside the colspan 2 than the width of input box is not 100%.
Please check this fiddle (Issue with chrome only)
Whats the wrokaround?

A: set the containing div width to 100% and it should fix the issue.

       <input type="text" class = "form-control", placeholder = "Email" />

also, might i ask why you're not using divs with class "rows" and "cols"?


text:
Q: Mocking in the Google AppEngine Runtime I'm trying to do something within the GAE runtime that needs to do "mocking":
  private Mongo createMongo() {
    Mongo mongo = Mockito.mock(Mongo.class);
    ...
  }

However, this obviously cause an error since "reflection" is a restricted class:
java.lang.NoClassDefFoundError: sun.reflect.ReflectionFactory is a restricted class. Please see the Google  App Engine developer's guide for more details.
    at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.<init>(SunReflectionFactoryInstantiator.java:24)
    at org.objenesis.strategy.StdInstantiatorStrategy.newInstantiatorOf(StdInstantiatorStrategy.java:65)
    at org.objenesis.ObjenesisBase.getInstantiatorOf(ObjenesisBase.java:76)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)
    at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:111)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:51)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:52)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:41)
    at org.mockito.Mockito.mock(Mockito.java:1014)
    at org.mockito.Mockito.mock(Mockito.java:909)

*

*Is there any workaround for this? Is there a way to make "reflection"
work with GAE runtime?

*Are there any "emulation" library for sun.reflect that makes it possible to do reflection?

*Perhaps, to define which classes possible to be reflected? Like @Reflectable or something

*Or there already exist a Mock framework that works in AppEngine?

Update:
I found a similar question way back 2010:
https://groups.google.com/forum/?fromgroups=#!topic/google-appengine-java/uIWRftGl-fA
However no answer until now.

A: App Engine apps run in a sandbox which places limits on what they can do.  An overview of the sandbox can be found here:
https://cloud.google.com/appengine/docs/java/#Java_The_sandbox
One of the sandbox limitations is a restriction on the jre-bundled classes that an application can access.  The full list of jre-bundled classes an application is allowed to access is listed here:
https://cloud.google.com/appengine/docs/java/jrewhitelist
Why is ReflectionFactory itself not on this list of accessible classes?  Well, if you read the javadocs for this class you will find the following statement: "The methods in this class are extremely unsafe and can cause subversion of both the language and the verifier."  And so, this class can be used to subvert the sandbox.


text:
Q: how to use java util class (or static method) in camel route to modify Exchange properties I would like to have CamelUtils class with the method setProperty
public final class CamelUtils {
    public static void setProperty(Exchange exchange, String name, Object value) {
        exchange.setProperty(name, value);
    }
}

I would like to use it in camel route like
<route>
   <from uri="direct:hello">
   <to uri="CamelUtils.setProperty(exhange, strName, strValue)"/>
   ... use property anyhow
</route>

How could I make it work?

I've found proper way of setting property in XML DSL:
<setProperty propertyName="propName"><simple>${body.someField}</simple></setProperty>

A: The exchange is passed by default if no parameters used.
You can set two headers for the other parameters and use
 <from uri="direct:hello">
    <setHeader headerName="name">
                    <constant>name</constant>
                </setHeader>
                <setHeader headerName="value">
                    <constant>value</constant>
                </setHeader>
 <to uri="bean:mypackage.CamelUtils?method=setProperty"/>

and then in the method
public static void setProperty(Exchange exchange, @Header("name") String name, @Header("value") Objectvalue) {
        exchange.setProperty(name, value);
    }


text:
Q: Should I enable TRIM support in Mac OSX 10.6.7 for SSD with SandForce SF-2281 controller (Vertex 3)? Recent articles in Mac Rumors and Life Hacker (which actually reference this question on SU) say that using TRIM will prolong the life and increase the performance of an SSD.
I just got an OCZ Vertex 3 with the SandForce SF-2281 controller.  Does this drive need TRIM support to operate at max performance? What about longevity?  Isn't the built in Sandforce garbage collection enough?

Edit for clarity:
I'm aware of the the various methods of enabling TRIM support on my MacBook Pro.  The question is whether or not the new Sandforce Controllers need TRIM?

A: Apple only supports TRIM on their own SSDs, but there are ways around this.
The AnandTech review of the OCZ 120GB Vertex 3 shows that, in the worst possible case of writing lots of incompressible data to the drive, there can be a substantial drop in performance without TRIM.

A: Yes, you will get more out of the SSD enabling TRIM. Several people have experienced performance issues without it on OS X.
You don't need any firmware update to do this, but still OS X Snow Leopard doesn't have it built in yet (10.7 will however).
You can download TRIM Enabler which does exactly that. I've been running a Macbook Pro with an SSD for several months now using it, no problems at all.


text:
Q: Proof by contradiction : about the assumption that there are finitely many primes. To prove by contradiction that there are infinitely many primes, we first assume there are finitely many primes.
It sounds to me that we can consider all primes in $\mathbb{N}$.
Is this assumption possible beacause of a ZFC axiom, that is, we take the set of all primes $\{x\in\mathbb{N}:x\text{ is a prime}\}$ and assume the set is finite?
(I did not know Euclid's proof is a proof by cases, a direct proof method.)

A: Yes, the axioms of ZFC guarantee the existence of the set of all primes in $\mathbb{N}$.
Indeed, in ZFC the axiom scheme of specification (also known as axiom scheme of separation, or axiom scheme of comprehension) says that:
$$\tag{1}
    \forall w_{1},\ldots ,w_{n}\,\forall A\,\exists B\,\forall x\,(x\in B\Leftrightarrow [x\in A\land \varphi (x,w_{1},\ldots ,w_{n},A)])
$$
where $\varphi$ is any formula in the language of set theory with free variables among $x, w_1, ..., w_n, A$ ($B$ does not occur free in $φ$).
Now, instantiate $(1)$ with $n=0$ and $A = \mathbb{N}$ (it exists in ZFC because of the axiom of infinity), and with the formula $\varphi(x)$ that says that $x$ is prime (it can easily be expressed in the language of set theory).
It yields
$$
\exists B  \, \forall x (x \in B \Leftrightarrow (x \in \mathbb{N} \land x \text{ is prime}))
$$
So, in ZFC there exists a set $B$ that is nothing but $\{x \in \mathbb{N} : x \text{ is a prime}\}$.

In ZFC, the axiom scheme of specification is not assumed as axiom because it can be derived from another axiom scheme in ZFC, the axiom scheme of replacement, as explained here.


text:
Q: Ambiguity between function and function in namespace with same argument Can anybody explain why there is an ambiguity between A::f(const B& b) and f(const A::B& b). I consider the code to be quite explicit about the intention.
#include <iostream>

namespace A
{
  class B
  {
  protected:
    double value_;
  public:
    B() : value_(15.0) {}
    double getValue() const {return value_;}
  };

  void f(const B& b)
  {
    std::cout << "f(b) = " << b.getValue() << std::endl;
  }
}

void f(const A::B& b)
{
  std::cout << "Other f(b) = " << b.getValue() << std::endl;
}

int main()
{
  A::B b;
  A::f(b);
  f(b);
  return 0;
}

However, both g++ 7.5.0 and clang 6.0.0 complain about ambiguous function call
(error: call of overloaded 'f(A::B&)' is ambiguous) regardless of compiler flags and optimizations.

A: For this function call expression
f(b);

the compiler finds the name f declared in the global namespace. On the other hand, using the argument dependent lookup the compiler also looks through the namespace A  where the class B is declared and also finds a function with the name f. Neither function is the best candidate to be called. So there is an ambiguity.
Apart from using qualified names of the functions to avoid the ambiguity you could suppress the argument dependent lookup the following way
( f )( b );

The argument dependent lookup is very useful for searching friend functions that otherwise are not visible if they are only defined in a class that grants the friendship.
Here is a demonstrative program
#include <iostream>

namespace N
{

    class A
    {
    private:
        int x;

    public:
        A( int x ) : x( x ) {}

        friend std::ostream & operator <<( std::ostream &os, const A &a )
        {
            return os << a.x;
        }
    };
}

int main()
{

    N::A a( 10 );

    std::cout << a << '\n';

    return 0;
}

The program output is
10

If the argument dependent lookup did not exist then the friend operator << could not be called because it will not be found even in the namespace N
Consider the following program.
#include <iostream>

namespace N
{
    class A
    {
    private:
        int x;

    public:
        A( int x ) : x( x ) {}

        friend void f( int x )
        {
            A a( x );

            std::cout << a.x << '\n';
        }
    };
}

int main()
{
    N::f( 10 );

    return 0;
}

The friend function f can not be called even if to specify the qualified name N::f. For this program the compiler will issue an error saying that 'f' is not a member of 'N'. To make the function visible you need to declare it also outside the class A as for example
#include <iostream>

namespace N
{
    class A
    {
    private:
        int x;

    public:
        A( int x ) : x( x ) {}

        friend void f( int x )
        {
            A a( x );

            std::cout << a.x << '\n';
        }
    };

    void f( int ); // make the function visible
}

int main()
{
    N::f( 10 );

    return 0;
}

A: This is an example of argument-dependent lookup.
Even though ::main is in global namespace, A::f is callable without using the fully-qualified name, because it is looked up in the namespace A of its argument, A::B. As a result, there is an ambiguity between ::f and A::f.
To resolve the ambiguity, you would need to call either A::f(b) (as you did), or ::f(b).


text:
Q: How to open AlertDialog from preference screen? My activity is below
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class locationserviceSettings extends PreferenceActivity implements OnPreferenceChangeListener,OnSharedPreferenceChangeListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.locationservice);

    //    PreferenceManager.setDefaultValues(notificationSettings.this, R.xml.notification, true);
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // TODO Auto-generated method stub
        System.out.println("Preference changed " + newValue);
        return false;
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        // TODO Auto-generated method stub
        System.out.println("Shared preference changed" + key);
    }

}

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="Location service settings">
        <CheckBoxPreference android:title="Location service"
            android:key="locationService" android:defaultValue="true"
            android:summary="checked for start location service in background"></CheckBoxPreference>
    </PreferenceCategory>
    <EditTextPreference android:title="Minimum time seconds"
        android:key="time" android:dependency="locationService"
        android:summary="Miminum time in seocnds for update location"></EditTextPreference>
    <EditTextPreference android:title="Minimum distance meters"
        android:key="distance" android:dependency="locationService"
        android:summary="Miminum distance in meters for update location"></EditTextPreference>
</PreferenceScreen>

both of these method are not printing anything when i chacked the checkPreference

A: use onPreferenceStartFragment(). It became a replacement for deprecated onPreferenceTreeClick().

A: Register your listener (for example in onCreate()) like this:
    timePref = getPreferenceScreen().findPreference("time");
    distancePref = getPreferenceScreen().findPreference("distance");

    timePref.setOnPreferenceChangeListener(this);
    distancePref.setOnPreferenceChangeListener(this);


text:
Q: Create annotation with babel ES6 I m actually developping an application using babeljs and ES6 (with .js files) and I was wondering if it was possible to create annotations, like we can do with typescript, using babeljs and ES6 ?

A: JavaScript doesn't have a construct identical to TypeScript annotations (all kinds of them). There is however a proposal for Decorators for ES7, and BabelJS does implement that (With the appropriate configuration). Here's a nice article describing the differences between the two.


text:
Q: How read with xQuery several similar nodes? Let's imagine I have an XML with the following structure:
<book>
 <title>My car is red</title>
 <author>Jhon Doe</author>
 <date>05-21-2021</date>
 <illustration>
    <name>front.jpg</name>
 </illustration>
 <illustration>
    <name>back.jpg</name>
 </illustration>
</book>

The  node is repeated several times.
With a xQuery I can read all nodes :
for $book in /book
 let $title := $book/title
 let $author := $book/author
return
 ....

But I want extract from XML file the name of the two illustration.
I try whit the following code:
for $illustration in $book/illustration
let $nombre := $illustration/name

But only read the name of the last node
How could I do it?
Thanks

A: You can add a nested loop for the illustration.
for $book in /book
    let $title := $book/title
    let $author := $book/author
    for $illustration in $book/illustration
        let $nombre := $illustration/name
        return ...


text:
Q: How to insert a variable number of values into a database using php I have a form where users can select the number of questions (no more than 10) they would like to enter marks into.

Enter Number of Questions : ____

Another form pops up with the requested number of questions where the user can enter marks.

If 3 was inputted :
Question1 : ____
Question 2: ____
Question 3: ____

I have a table called questions with 11 rows where ID is auto-incremented and the other questions can be null if there is no marks to be entered in that question

|  ID  |  Q1  |  Q2  | . . . |  Q10  |

This leads to my question which is, since the number of questions that the user selects can vary how can I input these values into a database using PHP.

A: You can set the "name" property of your answer fields to "answer[0]" "answer[1]" and so on. Then in PHP you can do $_GET['answer'] which will return an array that contains all your answers.

A: First, be sure to use a Many-to-many table (called "yourPrimaryTable_has_questions" in my below schema) between your questions table and the primary table which represents the page.
Then cycle through the questions, and add a row for each in your many-to-many table.  If you use a name with brackets but no value in the brackets, it will auto-increment when your PHP server receives the data.
if (isset($_POST) && $_POST  && $_POST['questions'])
{
    echo("<form name='xxx'>");
    foreach($_POST['questions'] as $question)
    {
        //Insert record with answer into your many to many table
    }
    echo("</form>");
}
else
{
    for ($i = 1; $i <= $count; $i++) {
        echo("Question {i} <input name='question[] type='text' /><br>");
    }
}

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `mydb` ;

-- -----------------------------------------------------
-- Table `mydb`.`questions`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`questions` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `otherData` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`yourPrimaryTable`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`yourPrimaryTable` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `otherData` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`yourPrimaryTable_has_questions`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`yourPrimaryTable_has_questions` (
  `yourPrimaryTable_id` INT NOT NULL ,
  `questions_id` INT NOT NULL ,
  `answer` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`yourPrimaryTable_id`, `questions_id`) ,
  INDEX `fk_yourPrimaryTable_has_questions_questions1_idx` (`questions_id` ASC) ,
  INDEX `fk_yourPrimaryTable_has_questions_yourPrimaryTable_idx` (`yourPrimaryTable_id` ASC) ,
  CONSTRAINT `fk_yourPrimaryTable_has_questions_yourPrimaryTable`
    FOREIGN KEY (`yourPrimaryTable_id` )
    REFERENCES `mydb`.`yourPrimaryTable` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_yourPrimaryTable_has_questions_questions1`
    FOREIGN KEY (`questions_id` )
    REFERENCES `mydb`.`questions` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
Q: close fancybox after confirm form in ajax success I have problem with close my fancybox after submit registration form in my web.
I using cms pro system....
With this I showing fancybox include form:
submitHandler: function(form) {
    var str = $("#subscriber_application").serialize();
      $.ajax({
          type: "POST",
          url: "ajax/user.php",
          data: str,
         success: function (msg){
                $("div#subscriber_response").html(msg);
                $("#subscriber_application").hide();
            }
          });
}

My html:

        <form action="" method="post" id="admin_form" name="admin_form">
          <input name="email" type="text" size="45" maxlength="40" class="home_input"   placeholder="Email Address" />
          <input name="token" type="text" size="45" maxlength="40" class="home_input"   placeholder="Token" />
          <input name="submit" value=" " type="submit" class="account_activate"/>
        </form>
      <?php echo $core->doForm("accActivate","ajax/user.php");?>

Subscribe For Free Application

&nbsp

  <form action=""  method="post" id="subscriber_application" name="subscriber_application" style="width:270px;">

      <input data-progression="" type="text" data-helper="Username should be at least 3 characters long" name="username" value="" class="home_input" placeholder="User name" name="username" />

      <input data-progression="" type="text" data-helper="Add your E-mail" name="email" class="home_input"   placeholder="Email address" value="<?php if(isset($_SESSION['subscriber_application']['email_address'])):echo $_SESSION['subscriber_application']['email_address'];endif; ?>" />

      <input data-progression="" type="text" data-helper="Your Restaurant Name" name="hotel_name" class="home_input"   placeholder="Restaurant name" />

      <input data-progression="" type="password" data-helper="Add Password - min 4 characters" name="password" class="home_input" placeholder="Password" />

      <input name="submit" type="submit"  id="submit" value=" " class="sign_in" />
      <input name="doapplication" type="hidden" value="1" />
    </form>

Sign in with social network!

my button :

      <button type="button" class="way-start" style="border-radius: 5px;height: 60px;width: 180px;background-color: green;border: 1px solid green;font-size: 26px;font-weight: 300;font-family: Helvetica Neue, Helvetica, Sans Serif;">Get the app!</button>

I will be grateful for every opinion !!!
Thanks!!!

A: My solution is in success function like:
setTimeout("$.fancybox.close()", 5000);

A: Try triggering a click on the fancybox close button.
$('#fancybox-close').trigger('click');


text:
Q: No alternative drivers appearing on Software Sources and manual install leads to no unity
Possible Duplicate:
How well do laptops with Nvidia Optimus work?

I just got a new laptop, installed Ubuntu 12.10 and am trying to install proprietary nvidia drivers. Once I understood the change from jockey, I did a fresh install and followed these instructions:
http://techhamlet.com/2012/11/install-nvidia-drivers-in-ubuntu-12-10/
But when I do, Unity crashes on startup.
My hardware on lspci | grep VGA is as follows

00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
01:00.0 VGA compatible controller: NVIDIA Corporation GK107 [GeForce GT 650M] (rev a1)

I've followed a couple of nvidia 12.10 tutorials on Google but none have helped. Can I get any specific advice?


text:
Q: How to match a string, for which a specific method is invoked, via regex? Regex: \"(.+?)\"\.Localize\(\)

Text: ModelState.AddModelError("Property", "Invalid property.".Localize());

Example:
http://regex101.com/r/aY5jK2
Currently the text Property", "Invalid property. gets matched. How do i match just the Invalid property string?

A: Try this:
\"([^"]+?)\"\.Localize\(\)

Demo Here

A: You can use this regex:
(")([^"]+)\1(?=\.Localize\(\))

Group 2 will contain what you want.

A: @Dante, Keep your regex that's working a simply add a space (\s) before the quote:
\s\"(.*?)\"\.Localize\(\)

DEMO
REGEX EXPLANATION:
\s\"(.*?)\"\.Localize\(\)

Match a single character that is a "whitespace character" (any Unicode separator, tab, line feed, carriage return, form feed) «\s»
Match the character """ literally «\"»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character """ literally «\"»
Match the character "." literally «\.»
Match the character string "Localize" literally (case insensitive) «Localize»
Match the character "(" literally «\(»
Match the character ")" literally «\)»


text:
Q: Variable in URL VB.net Telerik How to pass a variable in url like this:
<script language="VB" runat="server">
Dim id As String = HttpContext.Current.Request.QueryString("id")
Dim getEndpoint = "http://localhost:5000/equipments/" & id & "/moni"
</script>

<WebServiceDataSourceSettings>
<Select Url="<%=getEndpoint%>" RequestType="Get" />
</WebServiceDataSourceSettings>


text:
Q: How to handle FirebaseInstanceId.getInstance().getToken() = null I have just migrated to FCM. I have added my class that extends from FirebaseInstanceIdService to receive a refreshedToken as and when appropriate.
My question is specific to the case when user installs my app first time and due to some reason, unable to receive a registration Id from onTokenRefresh. How are we supposed to handle this? Can I set a broadcast receiver from my FirebaseInstanceIdService class which will notify the Main activity when a registration Id is received?

A: As far as I know, token will be null only when you try to run your app on emulator on which google play service is not there and when you are using dual email id on you google play store(on you actual device), but only one email id is verified for the usage. Those are the cases which will give you null token and I have already implemented FCM in my new project. So for rest of any cases , token won't be null.

A: Use this class extends with..
public class MyFirebaseInstanceIDService  extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        Toast.makeText(MyFirebaseInstanceIDService.this,refreshedToken,Toast.LENGTH_LONG).show();
    }
}

A: I was facing the same problem. I looked through a lot of SO posts and other forums and I found a solution that worked for me. FCM documentation says to use this method to get a token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();

I found a post online (I apologize, I don't remember which one. I found it a while ago) that used this method instead:
String refreshedToken = FirebaseInstanceId.getInstance().getToken() (String authorizedEntity, String scope);

FCM documentation describes the first method as:

Return the master token for the default Firebase project.

While the second one is described as:

Returns a token that authorizes an Entity to perform an action on behalf of the application identified by Instance ID.
  This is similar to an OAuth2 token except, it applies to the application instance instead of a user.
  For example, to get a token that can be used to send messages to an application via FirebaseMessaging, set to the sender ID, and set to "FCM".

I have been looking into why the first method call takes a longer time to return a token, but I haven't found an answer yet. Hope this helps.

A: *

*if your device have no connection to the internet onTokenRefresh() is never called  and you should notify to user his/her device has no internet connection

*firebase has its own network change listener and when a device connected to the internet then try to get token and return it, at this time you can tell your main activity by sending a local broadcast receiver that registration token is received.

use below codes:
    @Override
public void onTokenRefresh() {

    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    Log.d("FCN TOKEN GET", "Refreshed token: " + refreshedToken);

    final Intent intent = new Intent("tokenReceiver");
    // You can also include some extra data.
    final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
    intent.putExtra("token",refreshedToken);
    broadcastManager.sendBroadcast(intent);

}

in your main activity:
    public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
   LocalBroadcastManager.getInstance(this).registerReceiver(tokenReceiver,
            new IntentFilter("tokenReceiver"));

}

BroadcastReceiver tokenReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String token = intent.getStringExtra("token");
        if(token != null)
        {
            //send token to your server or what you want to do
        }

    }
};

}

A: Change this in manifest.xml file
tools:node="replace"
to
tools:node="merge".

A: depending on your application logic you can write the code to handle the "new" token directly in the FirebaseInstanceIdService.onTokenRefresh() method, or you can use a LocalBroadcast to send this information to your activity if you need to change the UI when this event happens.
Note that when onTokenRefresh() is called your activity could be closed.
A possible implementation could a mix of the two options:

*

*add some logic in onTokenRefresh() to send the token to your server

*use a LocalBroadcastReceiver to inform your activity, if you have a piece of UI that need to change when the token is available.

A: If you are running it on your emulator, check that you have Google play services enabled in Tools -> Android -> SDK Manager -> SDK Tools -> Google play services
Once installed, reboot both Android Studio and your emulator
It worked for me


text:
Q: The following code always fails with 400 bad request     function SendEditCommand()
    {
        jQuery.ajax({
            url: 'http://localhost:15478/Service.svc/GetTest',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert('success');
            },
            error: function(request, status, error) {
                alert(error);
            }
        });
    }

    jQuery(document).ready(function () {
        SendEditCommand();
    });

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <connectionStrings>
        <add name="Entities" connectionString="metadata=res://*/Data.TechieCMS.csdl|res://*/Data.TechieCMS.ssdl|res://*/Data.TechieCMS.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost\mssql2008;Initial Catalog=TechieCMS;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
    </connectionStrings>
    <system.serviceModel>
        <services>
            <service name="DefaultService" behaviorConfiguration="DefaultServiceBehavior">
                <endpoint address="" binding="webHttpBinding" contract="Techie.CMS.Business.ContentProvider" behaviorConfiguration="DefaultEndpointBehavior" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="DefaultEndpointBehavior">
                    <enableWebScript />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
                <behavior name="DefaultServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
</configuration>

    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ContentProvider
    {
        [OperationContract]
        [WebGet()]
        public string GetTest()
        {
            return "Test";
        }
    }

A: Im guessing that it does not like the port within the URL. Everything else is correct. Are you using IE? Does it work with other browsers? Other people with the same problem have been using IE and it works on Firefox.
Perhaps try adding a data variable and changing it to POST? Some say that solves it.

A: Thank you all for your answers, they were surely relevant and a piece to the of the puzzle. The key problem was <service name="DefaultService"... I thought this was just supposed to be a name that I choose. Found out that it has to be the fully qualified name of the class that implements the contract.


text:
Q: typescript .d.ts module for images not working I am a little new to Typescript my only weakness is the tsconfig.json.
I have a problem with importing images ( in Reactjs ) being not found:
client/app/Reports/View.tsx:11:30 - error TS2307: Cannot find module '../../assets/images/placeholders/awards.png' or its corresponding type declarations.

11 import AwardPlaceholder from "../../assets/images/placeholders/awards.png";

So I searched and found a conclusion to declare modules for the image files so TS can register them as modules properly, so I did this:
// @types/images.d.ts
declare module '*.svg' {
  const content: string;
  export default content;
}

declare module '*.png' {
  const content: string;
  export default content;
}

declare module '*.jpg' {
  const content: string;
  export default content;
}

but the error still persists, here is my tsconfig.json, I think it could use some work but this is working how I want it to because I have custom type declartions
{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es2017",
        "skipLibCheck": true,
        "noImplicitAny": true,
        "noEmit": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "jsx": "react",
        "paths": {
         "MyCustomTypesModule" : ["@types/MyCustomTypesModule/index.d.ts"],
            "*": [
                "node_modules/*"
            ]
        },
        "typeRoots" : ["@types"]
    },
    "include": [
        "server/**/*",
        "client/**/*"
    ]
}

through my research, since the images.d.ts declaration file is in my @types folder, Typescript should just see and acknowledge it.
Is something wrong with my tsconfig.json? Do I have to register it seperately in the config somewhere?
To run the typescript server, I just execute $ tsc

A: I moved my images.d.ts from the path of @types/images.d.ts to outside of my @types folder to client/images.d.ts and somehow it worked even though my typeRoots is [@types].

A: The key thing for me was that the .d.ts files need to be in subfolders within @types.
My folder structure now looks like this and works perfectly:
my_project/
├─ @types/
│  ├─ global/
│  │  ├─ index.d.ts
│  ├─ assets/
│  │  ├─ index.d.ts
├─ app.tsx


text:
Q: How do server-side events keep the connection open despite using HTTP? I am confused at how SSE, despite using HTTP, is able to maintain the connection.
When I look at Web sockets, my understanding is that the most that HTTP is used is only for establishing the TCP connection and asking to upgrade to WS protocol. After that, the client and server both use the WS protocol which is why the connection can be persisted.
With SSE, there is no special protocol, it's just HTTP. Don't browsers have an HTTP TTL? How is the connection persisted beyond the TTL then?
Other HTTP polling mechanisms still suffer from timeout. SSE isn't a polling mechanism, but it still uses HTTP.


text:
Q: Finding duplicates in one column with non-dups in another I am struggling with how to take a dataset and output a result that finds duplicate information in one column with non-duplicate items in another. If say column 0 and 2 are exact duplicates I don't care about the set of data, only if there are rows where column 0 has entries with more than one value in column 2. And, if that is the case, I want all of the rows that match column 0.
I am first using concat to narrow down the dataset to rows that have duplicates. My problem is now trying to get only the rows where column 2 is different.
My example dataset is:
Pattern or URI,Route Filter Clause,Partition,Pattern Usage,Owning Object,Owning Object Partition,Cluster ID,Catalog Name,Route String,Device Name,Device Description
"11111",,Prod_P,Device,"11111",Prod_P,,,,SEPFFFF0723AFE8,device1
"11111",,Prod_P,Device,"11111",Prod_P,,,,SEPFFFF862FAF74,device2
"11111",,Prod_P,Device,"11111",Prod_P,,,,SEPFFFFF2A8AA38,device3
"11111",,Prod_P,Device,"11111",Prod_P,,,,SEPFFFFD2C0A2C6,device4
"22334",,Prod_P,Device,"22334",Prod_P,,,,SEPFFFFCF87AB31,device5
"33333",,Prod_P,Device,"33333",Prod_P,,,,SEPFFFFCF87AAEA,device6
"33333",,Dummy_P,Device,"33333",Dummy_P,,,,SEPFFFF18FF65A0,device7
"33333",,Prod_P,Device,"33333",Prod_P,,,,SEPFFFFCFCCAABB,device8

In this set, I want to have a result of the last three rows that are "33333" as they have more than one type of value in column 2. "11111" only matches Prod_P so I don't care about it.
import pandas as pd
ignorelist = []
inputfile = "pandas-problem-data.txt"
data = pd.read_csv(inputfile)
data.columns = data.columns.str.replace(' ','_')
data = pd.concat(g for _, g in data.groupby("Pattern_or_URI") if len(g) > 1)
data = data.loc[(data["Pattern_Usage"]=="Device"), ["Pattern_or_URI","Partition","Pattern_Usage","Device_Name","Device_Description"]]
new_rows = []
tempdup = pd.DataFrame()
for i, row in data.iterrows():
    if row["Pattern_or_URI"] in ignorelist:
        continue
    ignorelist.append(row["Pattern_or_URI"])
    # testdup = pd.concat(h for _, h in (data.loc[(data["Pattern_or_URI"]==row["Pattern_or_URI"], ["Pattern_or_URI","Partition","Pattern_Usage","Device_Name","Device_Description"])]).groupby("Partition") if len(h) > 1)
    # print(data.loc[(data["Pattern_or_URI"]==row["Pattern_or_URI"], ["Pattern_or_URI","Partition","Pattern_Usage","Device_Name","Device_Description"])])
    newrow = data.loc[(data["Pattern_or_URI"]==row["Pattern_or_URI"], ["Pattern_or_URI","Partition","Pattern_Usage","Device_Name","Device_Description"])]

If I uncomment the line where I try to use the same concat to find entries with "Partition" > 1 I get an error ValueError: No objects to concatenate. I know it gets through the first iter with the print statement uncommented.
Is there an easier or better way of doing this? I'm new to pandas and keep thinking there is probably a way to find this that I haven't figured out.
Thank you.
Desired output:
Pattern or URI,Route Filter Clause,Partition,Pattern Usage,Owning Object,Owning Object Partition,Cluster ID,Catalog Name,Route String,Device Name,Device Description
"33333",,Prod_P,Device,"33333",Prod_P,,,,SEPFFFFCF87AAEA,device6
"33333",,Dummy_P,Device,"33333",Dummy_P,,,,SEPFFFF18FF65A0,device7
"33333",,Prod_P,Device,"33333",Prod_P,,,,SEPFFFFCFCCAABB,device8

A: I think it's a bit misleading to say you're looking for duplicates.  This is really a grouping problem.
You want to find groups of identical values in Pattern or URI that correspond with more than one unique value in your Partition Series.

transform + nunique

s = df.groupby('Pattern or URI')['Partition'].transform('nunique').gt(1)
df.loc[s]

   Pattern or URI  Route Filter Clause Partition Pattern Usage  Owning Object Owning Object Partition  Cluster ID  Catalog Name  Route String      Device Name Device Description
5           33333                  NaN    Prod_P        Device          33333                  Prod_P         NaN           NaN           NaN  SEPFFFFCF87AAEA            device6
6           33333                  NaN   Dummy_P        Device          33333                 Dummy_P         NaN           NaN           NaN  SEPFFFF18FF65A0            device7
7           33333                  NaN    Prod_P        Device          33333                  Prod_P         NaN           NaN           NaN  SEPFFFFCFCCAABB            device8

A: Using df.drop_duplicates() as follows:
df=pd.DataFrame({'a':[111,111,111,222,222,333,333,333],
                 'b':['a','a','a','b','b','a','b','c'],
                 'c':[12,13,14,15,61,71,81,19]})
df

    a   b   c
0   111 a   12
1   111 a   13
2   111 a   14
3   222 b   15
4   222 b   61
5   333 a   71
6   333 b   81
7   333 c   19

df1=df.drop_duplicates(['a','b'],keep=False)

df1

    a   b   c
5   333 a   71
6   333 b   81
7   333 c   19

Note, instead of assigning it to a new DF, you can add inplace=True to apply it to the original


text:
Q: Custom UIActionSheet with UIDatePicker gives error "invalid context 0x0" I'm trying to display a UIDatePicker in an iPad/iPhone application and I'm using a UIActionSheet with a UIDatePicker embedded within. When I'm testing the app with iOS 7 Simulator I'm getting the following error:
<Error>: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

I get the same error for CGContextSetStrokeColorWithColor, CGContextSaveGState, CGContextSetFlatness and a bunch of other similar CGContext___ types.
What is strange is that I'm not getting this error when testing in iOS 6.1 Simulator.
I'm still new to iOS development so I'm wondering if modifying a UIActionSheet with custom views is something that Apple strongly advises against. If yes what other options do I have to display a UIDatePicker in a modal manner?
Update
As mentioned below, I've found an explanation for the error in Apple's documentation for UIActionSheet; it's pretty clearly explained the UIActionSheet is not to be subclassed and used to display subviews.


text:
Q: Change appearance of voltage source in circuitikz I prefer my voltage sources as in the image below. How can I achieve this in circuitikz?
There is an identical question here, however for plain tikz. I tried to implement the solution given their, but it does not seem to work in combination with circtuitikz. In fact it generates an error.

A: One simple approach is to use open with o-o option:
\draw (0,0) to ++(1,0) to[open,o-o,l={$U_\sim$}] ++(1,0) to ++(1,0);

Or else, custom component customV can be defined and used:
\draw (3.5,0) to[customV,l={$U_\sim$}] ++(3,0);

MWE:
\documentclass[border=3mm]{standalone}
\usepackage{circuitikz}

\makeatletter
\pgfcircdeclarebipole{}{\ctikzvalof{bipoles/open/height}}{customV}{\ctikzvalof{bipoles/open/height}}{\ctikzvalof{bipoles/vsource/width}}{
    \pgftransformshift{\pgfpoint{\pgf@circ@res@left}{0pt}}
    \pgfnode{ocirc}{center}{}{}{\pgfusepath{draw}}
    \pgftransformshift{\pgfpoint{2\pgf@circ@res@right}{0pt}}
    \pgfnode{ocirc}{center}{}{}{\pgfusepath{draw}}
}
  \def\pgf@circ@customV@path#1{\pgf@circ@bipole@path{customV}{#1}}
  \compattikzset{customV/.style = {\circuitikzbasekey, /tikz/to path=\pgf@circ@customV@path, label=#1}}
\makeatother

\begin{document}
\begin{circuitikz}
\draw (0,0) to ++(1,0) to[open,o-o,l={$U_\sim$}] ++(1,0) to ++(1,0);
\draw (3.5,0) to[customV,l={$U_\sim$}] ++(3,0);
\end{circuitikz}
\end{document}


text:
Q: Convert from date to long are not the same in java and postgresql I have a table in postgresql which has a column created_date date type. I have created the view which returns date in miliseconds instead of date:
select date_part('epoch'::text, timezone('UTC'::text, created_date::timestamp with time zone)), created_date
from table

This returns the following result:
date_part    created_date

1497384000   2017-06-14
1497384000   2017-06-14
1498420800   2017-06-26
1498420800   2017-06-26

In Java I did the following:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(view.getStartDate(), formatter);
long longDate = date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond();

The longDate result is 1497398400 for 2017-06-14 and 1498435200 for 2017-06-26.
Why postgresql and Java convert from date to long are not the same?
PS: the database's timezone is Asia/Baku.

A: You're calling atStartOfDay(ZoneId). As the ZoneId is UTC, it sets the hour to midnight and the zone to UTC. So, your date becomes 2017-06-14T00:00:00Z, and the equivalent epoch seconds value is 1497398400.
If you check the value returned by the database (1497384000):
System.out.println(Instant.ofEpochSecond(1497384000L));

You get:

2017-06-13T20:00:00Z

If you convert this to the timezone your system is using (Asia/Baku):
System.out.println(Instant.ofEpochSecond(1497384000L).atZone(ZoneId.of("Asia/Baku")));

You get:

2017-06-14T00:00+04:00[Asia/Baku]

So, the value 1497384000 is equivalent to 2017-06-13T20:00:00Z in UTC. The database returns 2017-06-14 because it's converting this UTC date/time to the system's timezone (Asia/Baku).
If you want to get the same results, you must use the same timezone the database is using:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2017-06-14", formatter);
// using Asia/Baku timezone instead of UTC
long longDate = date.atStartOfDay(ZoneId.of("Asia/Baku")).toEpochSecond();
System.out.println(longDate);

The output will be:

1497384000


text:
Q: how to exlude a directory from an if-statement to header pages hello I get crazy through a header-function that does not work.
the idea is that when a user is calling the page foo.php he will be headered. therfor I included a script from script.php
the script reads out the information about the accepted languages from

$_SERVER["HTTP_ACCEPT_LANGUAGE"])

okay, from that I have the preferred language and a country code that I need to header foo.php into the right language direction. the code from script.php is like:
if ($pref_language == 'af'){
    header('Location:en'.$_SERVER['SCRIPT_NAME']);
    exit;
}
if ($pref_language == 'sq'){
    header('Location:en'.$_SERVER['SCRIPT_NAME']);
    exit;
}

so these examples will header foo.php to directory of

root/en/foo.php

now when calling just script.php that is located in root/scripts/script.php I will headered root/en/scripts/script.php. thats why I would like to add the if-condition that
all if-statements with header(); only take place for files outside of root/scripts/.
so I added:
$filename = $_SERVER['SCRIPT_NAME'];
$path = $_SERVER['HTTP_HOST']."/scripts".$_SERVER['SCRIPT_NAME'];

if (isset($path == false)){

    if ($pref_language == 'af'){
        header('Location:en'.$_SERVER['SCRIPT_NAME']);
        exit;
    }
    if ($pref_language == 'sq'){
        header('Location:en'.$_SERVER['SCRIPT_NAME']);
        exit;
    }
}

that does not work. so if someone could help me out I really would appreciate.
thanks alot.

A: This can be your solution, although it's kind of silly in a way, but will do the job:
<?php

$unwanted_dir = "/scripts";

// this will make sure that the script name doesnt start with "/scripts"
if (substr($_SERVER['SCRIPT_NAME'], 0, strlen($unwanted_dir)) != $unwanted_dir){

    if ($pref_language == 'af'){
        header('Location:en'.$_SERVER['SCRIPT_NAME']);
        exit;
        }
    if ($pref_language == 'sq'){
        header('Location:en'.$_SERVER['SCRIPT_NAME']);
        exit;
        }
}
?>

another way would be a regular expression, but this is simplier
I advise you to make it more dynamic on selecting the language. i.e:
<?php

$unwanted_dir = "/scripts";
$pref_language == 'af';  // dynamicaly set the language
$full_path = '/home/php/site/';

// this will make sure that the script name doesnt start with "/scripts"
if (substr($_SERVER['SCRIPT_NAME'], 0, strlen($unwanted_dir)) != $unwanted_dir){

    if (is_dir($full_path . $pref_language)){
        header('Location:'$full_path . $pref_language . $_SERVER['SCRIPT_NAME']);
    }
    else{
        echo "Sorry, we don't support your language";
        // or
        // header('Location:go/to/unsopported/languages.php');
    }

    exit;
}
?>


text:
Q: how can I create [experimental] tag in c# which throws a compiler warning In c# I can mark some functions as obsolete by doing
[Obsolete]
void Foo()
{}

this tell the compiler to throw warning if I am using this function.
I want to create my own tag [Experimental] which just as obsolete throw a warning telling the user who build the code that this function is not well tested and using it may result in troubles.
Is it possible to do this? How?

A: The Obsolete attribute is special, as the C# compiler knows about it. You won't be able to create your own. The closest you could get would be to inherit from ObsoleteAttribute yourself, but the class is sealed so this is not possible.
As it is, you could mark your method as [Obsolete("This method is not well tested.")]. That's the best you can do.

A:
I want to create my own attribute [Experimental] which just as [Obsolete] does makes the compiler produce a warning. Is it possible to do this?

No, sorry.  Obsolete is a very special attribute. The compiler has special-purpose code written for it. There is no extensible warning mechanism in C#.
If you would like to submit this suggestion to the Visual Studio team, you can do that at http://visualstudio.uservoice.com/.

A: You can add it as an Attribute.
[System.AttributeUsage(AttributeTargets.All)]
public class Experimental: System.Attribute
{

}

A: I think you can do it with PostSharp. There was a post about it on SO, but I ohly have the bookmark link now:
http://fgheysels.blogspot.com/2008/08/locking-system-with-aspect-oriented.html
Look under Compile Time Validation in that page, it shows you how the author did it.
Further note: it involves a bit of plumbing code. Definitely not a "slap-it-in-to-the-project" variety of code.


text:
Q: Different form opens when you login as admin c# mysql So i've made a login form in c# working with MySql and i want to make it so when administrator login a different form pops up i've made on the mysql in the users database a column named permissions so if a user will have permission Admin i want a different form to open for him and not the same as for normal users but i don't really know how to do that
the code:
private void btn_Prijava_Click(object sender, EventArgs e)
    {
        try
        {
            string myConnection = "datasource=localhost;port=3306;username=root;password=";
            MySqlConnection myConn = new MySqlConnection(myConnection);

            MySqlCommand SelectCommand = new MySqlCommand(" select * from login.users where upIme='" + this.tB_upIme.Text + "' AND geslo='" + this.tB_geslo.Text + "' ;", myConn);

            MySqlDataReader myReader;
            myConn.Open();
            myReader = SelectCommand.ExecuteReader();
            int count = 0;
            while (myReader.Read())
            {
                count = count + 1;
            }
            if (count == 1)
            {
                MessageBox.Show("Uspešno ste se prijavili!");
                this.Hide();
                Form3 f3 = new Form3();
                f3.ShowDialog();
            }
            else if (count > 1)
            {
                MessageBox.Show("Dvojno uporabniško ime in geslo!");
                this.Hide();
            }
            else
                MessageBox.Show("Uporabniško ime ali geslo ni pravilno!");
            myConn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

A: if you have permissions column and have value Admin for admin users you can try thebelow code.
       bool IsAdminUser=false;
       while (myReader.Read())
        {
            count = count + 1;
            IsAdminUser = myReader["permissions"].ToString().Equals("Admin");
        }
        if (count == 1 && IsAdminUser==true)
        {
            MessageBox.Show("User is Admin!");
            this.Hide();
            AdminForm adminForm = new AdminForm ();
            adminForm.ShowDialog();
        }
        else if (count == 1)
        {
            MessageBox.Show("Uspešno ste se prijavili!");
            this.Hide();
            Form3 f3 = new Form3();
            f3.ShowDialog();
        }
        else if (count > 1)
        {
            MessageBox.Show("Dvojno uporabniško ime in geslo!");
            this.Hide();
        }

A: private void cmdEnter_Click(object sender, EventArgs e)
        {
                try
                {
                    string myConnection = "datasource=localhost;port=3306;username=root;password=1234";
                    MySqlConnection myConn = new MySqlConnection(myConnection);
                MySqlCommand SelectCommand = new MySqlCommand(" select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' AND password='" + this.txtPassword.Text + "' ;", myConn);

                MySqlDataReader myReader;
                myConn.Open();
                myReader = SelectCommand.ExecuteReader();
                int count = 0;

                bool IsAdminUser = false;
                while (myReader.Read())
                {
                    count = count + 1;
                    IsAdminUser = myReader["username"].ToString().Equals("admin");
                }
                if (count == 1 && IsAdminUser == true)
                {
                    MessageBox.Show("User is Admin!");
                    this.Hide();
                    AdminForm adminForm = new AdminForm();
                    adminForm.ShowDialog();
                }
                else if (count == 1)
                {

                    this.Hide();
                    Menu f3 = new Menu();
                    f3.ShowDialog();
                }

                else if (count > 1)
                {
                    MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    myConn.Close();
                }

                myConn.Close();
             }
                 catch (Exception ex)
                {
                MessageBox.Show(ex.Message);
                }
    }


text:
Q: Is CakePhp 'standards compliant' when generating HTML, Forms, etc? So I've been reading a lot of "Designing with Web Standards" and really enjoying it.  I'm a big CakePhp user, and as I look at the source for various form elements that Cake creates with its FormHelper, I see all sorts of extraneous

In the book, he promotes semantic HTML, and writing your markup as simple / generic as possible.
So my question is, am I better writing my own HTML in these situations?  I really want to work in compliance with XHTML and CSS standards, and it seems I'd spend just as much time (if not more) cleaning up Cakes HTML, when I could just write my own
thoughts?
p.s.  Here's an example in an out of the box form that CakePhp generates using the FormHelper
<form id="CompanyAddForm" method="post" action="/omni_cake/companies/add" accept-charset="utf-8">
<input type="hidden" name="_method" value="POST" />

Name<input name="data[Company][name]" type="text" maxlength="50" id="CompanyName" />

Website<input name="data[Company][website]" type="text" maxlength="50" id="CompanyWebsite" />

Notes<textarea name="data[Company][notes]" cols="30" rows="6" id="CompanyNotes" ></textarea>

<input type="submit" value="Submit" />
</form>

EDIT: An in an indented form (indentation does not effect the standards compliance issue, but the above one-liner style is nearly impossible to read):
<form id="CompanyAddForm" method="post" action="/omni_cake/companies/add" accept-charset="utf-8">

       <input type="hidden" name="_method" value="POST" />

        Name
        <input name="data[Company][name]" type="text" maxlength="50" id="CompanyName" />

        Website
        <input name="data[Company][website]" type="text" maxlength="50" id="CompanyWebsite" />

        Notes
        <textarea name="data[Company][notes]" cols="30" rows="6" id="CompanyNotes" ></textarea>

        <input type="submit" value="Submit" />

</form>

In the above, there's those couple divs that seem unnecessary like the one that has inline CSS "display:none".  I realized I can change classes and IDs of all the fields, but if I'm doing do that for each one, I might as well write the HTML myself...

A: My answers to your two questions are as follows:

Is CakePhp 'standards compliant' when
  generating HTML, Forms, etc?

Yes.

In [Designing with Web Standards], he
  promotes semantic HTML, and writing
  your markup as simple / generic as
  possible. So my question is, am I
  better writing my own HTML in these
  situations?

Sometimes you are better off, sometimes you're not. If your goal is to use minimal, semantic markup, you could be better off writing your own HTML most of the time. However, if your goal is to generate standards compliant HTML quickly, then allowing Cake to be what it's meant to be—a rapid development framework—is a good idea.
That said, you can tell Cake not to print some of its markup when you find it unnecessary. For example, you can suppress the div elements that wrap form inputs by using a value of false with this option: http://book.cakephp.org/view/1397/options-div

A: The markup output by Cake helpers is certainly standards compliant, as you can check at any time. What it could possibly be is simpler, but not much more so. The
 container with hidden input fields may be superfluous, but it's nicely grouping these fields and getting them out of the way. If you're using the SecurityComponent you'll find many more of these necessary hidden fields, which makes the wrapping
 less superfluous.  Apart from that, I have a hard time finding any really extraneous markup.
If you're not happy with the
<input>[error]
 structure, you can use the specialized $this->Form->label() etc. methods to produce only the input elements and wrap them in your own container elements. Just remember to include the $this->Form->error() as well somewhere.
I think the best way is to start prototyping your apps using basic $this->Form->input() groups of elements. Often these are perfectly serviceable in the final app as well. If during development you realize you need different markup than what Cake offers you, you can start transitioning to more custom markup. The one thing you should not do is write your own <input> elements, you should always use the FormHelper methods to produce those, since it's taking care of a lot of details that are a pain to reproduce properly by hand.
Apart from the FormHelper, I don't think there's anything to complain about in Cake's HTML markup, since you're writing most of the rest yourself.

A: According to the CakePHP book, the generated HTML is standards compliant.
You could override the default HTML output from the FormHelper methods by extending the Helper class.
More information here

A: Question already answered but maybe worth adding that this depends on which standards, and which version of CakePHP.
HTML5 form input types are not supported by the FormHelper in 1.2.x and 1.3.x, for example
echo $this->Form->input('User.email', array('type' => 'email'));

will output something like

    Email
    <textarea id="UserEmail" name="data[User][email]"></textarea>

Apparently this will be fixed in 2.0.x.
Another edge case is if you have more than one form on the page with the same model you may end up with duplicate HTML identifiers.


text:
Q: What could stop h2o responding to our R script? What are the possible reasons that an h2o service might stop responding to an http REST API request?
We are using the R CRAN package, and after a fair period of time, the h2o server stops responding. We have captured a variety of logs, but there is no obvious error or reason for this. There is also a matter of consistency, which I will detail after the logs. The h2o.logging() log shows:
Time:     2019-01-07 11:13:19.262

GET       http://localhost:54321/3/Jobs/$03017f00000132d4ffffffff$_936500deb000be7364a7e2ce61d5451e
postBody:

curlError:         FALSE
curlErrorMessage:
httpStatusCode:    200
httpStatusMessage: OK
millis:            3513

{"__meta":{"data":"removed as it is not relevant"}}

------------------------------------------------------------

Time:     2019-01-07 11:13:25.013

GET       http://localhost:54321/3/Jobs/$03017f00000132d4ffffffff$_936500deb000be7364a7e2ce61d5451e
postBody:

curlError:         TRUE
curlErrorMessage:  Failed to connect to localhost port 54321: Connection refused
httpStatusCode:    -1
httpStatusMessage:
millis:            88616

The main log shows it was working just before:
Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         2 minutes 9 seconds
    H2O cluster timezone:       Etc/UTC
    H2O data parsing timezone:  UTC
    H2O cluster version:        3.20.0.8
    H2O cluster version age:    3 months and 17 days !!!
    H2O cluster name:           H2O_started_from_R_root_ttz747
    H2O cluster total nodes:    1
    H2O cluster total memory:   255.99 GB
    H2O cluster total cores:    2
    H2O cluster allowed cores:  2
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    H2O API Extensions:         XGBoost, Algos, AutoML, Core V3, Core V4
    R Version:                  R version 3.5.1 (2018-07-02)

  |======================================================================| 100%
  |======================================================================| 100%
Error in .h2o.__checkConnectionHealth() :
  H2O connection has been severed. Cannot connect to instance at http://localhost:54321/
Failed to connect to localhost port 54321: Connection refused
Calls: <Anonymous> -> .h2o.__remoteSend -> .h2o.__checkConnectionHealth

The interesting thing about this is that it is 100% repeatable on machines that have this problem (the majority), but we also have two machines that don't show this problem (at least don't seem to, we can't rule out they never have, but they usually run it okay).
I've seen that h2o never shuts itself down on its own, so that is unlikely. We stopped any parallelism in the R script, and that didn't change anything.
We therefore need suggestions on how to identify the problem here, and of course fix it.

A: It looks like the h2o connection 'open' too many files beyond the default limit set on the machine and that causes the crash.
The limit on open file descriptors can be checked with:
ulimit -n

And later the soft limit can be modified to a larger valuer:
ulimit -Sn 5000


text:
Q: Relations between different zeta functions for a simple algebra I'm trying to understand the classical works of Eichler, Shimura and many others (especially Shimizu and Tamagawa's annals papers) on the "classical" (I'm a newcomer and I'm not sure whether this adjective is proper; I just followed Voight's famous book: Quaternion algebras) zeta functions for simple algebras (over a number field).
Meanwhile, I learnt basic ideas and calculations of the "modern" Godement-Jacquet theory (their most famous monograph: Zeta functions for simple algebras).
So what made me puzzled is their relations. In modern Godement-Jacquet theory, the so called "standard" way is to use harmonic analysis on adelic groups (global theory) to define the zeta integral. So we denote by $G$ the group of units of the simple algebra, and define:
$$
Z(\Phi, s, \varphi)=\int_{G_{\mathbb{A}}} \Phi(g)|\operatorname{det} g|^{s} \varphi(g) \mathrm{d} g
$$
where $\Phi$ is taken to be a Schwartz function and $\phi$ a matrix coefficient of an automorphic representation. Then we need some work to obtain the $L$-factor and $\gamma$-factor, etc, which established its automorphic $L$-function.
On the other hand, for example (for simplicity), let $B$ be a quaternion algebra over a number field, $O\subset B$ a maximal order. Then there's also a definition of the "classical" zeta function:
$$
\zeta_{O}(s):=\sum_{I \subseteq O} \frac{1}{\mathrm{~N}(I)^{s}}=\sum_{\mathfrak{n}} \frac{a_{\mathfrak{n}}(O)}{\mathrm{N}(\mathfrak{n})^{2 s}}
$$
where $a_{\mathfrak{n}}(O):=\#\{I \subseteq O: \operatorname{nrd}(I)=\mathfrak{n}\}$ (see Voight's book, section 26.3). This could be generalised to general simple algebras.
So I want to ask: is their any relation between these two "zeta" functions? I think there must be some: when I was checking Tamagawa's annals paper, I found he mentioned Godement's Bourbaki's report on this, and he said:
"the ordinary $\zeta$-function of a division algebra was introduced by K.Hey, and generalized by M.Eichler to $L$-functions with abelian characters. The first attempt to generalize these theories to $\zeta$-functions with non-abelian characters is due to H.Maass. Later, R.Godement gave a method to get the most general formulations on these matters. In this note, we will define a type of $\zeta$-functions (maybe that's my question: the "calssical" ones) of a division algebra over a number field which are included in Godement's work as a special case, and for which one can develop the theory of Euler products. The latter theory has its own meaning as an application of the theory of spherical functions on $p$-adic algebraic groups.   ......"
Could any expert give me some help/advice? Thanks in advance!! @Paul Garrett

A: Let's recall some history about $L$-functions not on division algebras first.  Dirichlet introduced $L$-functions of certain characters, later extended by Hecke.  These characters may be viewed as automorphic representations of GL(1) in Langlands' paradigm.  For the trivial character over $\mathbb Q$, you get the Riemann zeta function, and for the trivial character over a number field $K$, you get the Dedekind zeta function for $K$.
Later, $L$-functions were attached to higher-dimensional objects by Hecke, Maass, Artin, Langlands, ...  E.g., $L$-functions of modular forms or 2-dimensional complex Galois representations should correspond to automorphic representations of GL(2) in the Langlands paradigm.
Now modular forms also correspond to automorphic forms on quaternion algebras, and one can directly try to construct $L$-functions on quaternion algebras $B$.  This is the degree 2 case of what Godement-Jacquet do---they construct zeta ($L$) functions associated to representations of $B$, which in the holomorphic case correspond to $L$-functions of classical modular forms.  However, if you take the trivial representation on $B^\times$ (giving the classical zeta function of $B$), this corresponds to an Eisenstein series in the language of modular forms.  The fact that these are equal amounts to the fact that you can write the classical zeta function of $B$ in terms of the Riemann/Dedekind zeta function.


text:
Q: elasticsearch querying a part of a string An elasticsearch index contains data from database where _id is set to the primary key that is of the format
ACC000223344782

The key is of fixed length and has 0 padding after ACC as shown.
There is a need to search docs whose key ends at specific numbers
Some sample use cases are
1- Last digit is 9
xxxxxxx9

2- 2nd last digit is 3 AND last digit is between 0 and 5
xxxxxx3[0>=5]

3- 3rd last digit is between 3 AND 8 and last digit is 4.
xxxxxx[3>=8]x4

You got the idea. Basically random parts of the digit part of the  _id key.
To solve this problem, currently I have split the key manually into individual digits and stored as another field in the doc at the time of inserting data. That way the above key becomes
_id: ACC000223344782,
split_key:
  0:A
  1:C
  2:C
  3:0
  4:0
  5:0
  6:2
  7:2
  8:3
  9:3
  10:4
  11:4
  12:7
  13:8
  14:2

And then I can use the search query on the split_key field string index.
This seems more like a poor man's indexing. split_key field is totally redundant and I have a feeling that if I am using the elasticsearch the right way, it should not be needed. Can someone point me towards the right direction on any way to improve this and handle the above mentioned scenarios gracefully?


text:
Q: Select a single character in an alphanumeric string in bash I have an issue with string manipulation in bash. I have a list of names, each name being composed of two parts, chars and numbers: for example
abcdef01234

I want to cut the last character before the numeric part starts, in this case
f

I think there is a regular expression to help me with this but just can't figure it out. AWK/sed solutions are accepted too. Hope someone can help.
Thank you.

A: You can use a regexp like [a-zA-Z]+([a-zA-Z])[0-9]+. If you know how to use sed is pretty easy.
Check https://regex101.com/r/XCkKM5/1

A: The match will be the letter you want.
^\w+([a-zA-Z])\d+$

As a sed command (on OSX) this will be :
echo "abcdef12345" | sed -E "s#^[a-zA-Z]+([a-zA-Z])[0-9]+\$#\1#"

A: In bash it can be done with parameter expansion with substring removal and string indexes, e.g.,
a=abcdef01234       # your string
tmp=${a%%[0-9]*}    # remove all numbers from right
echo ${tmp:(-1)}    # output last of remaining chars

Output: f

A: try following too once.
echo "abcdef01234" | awk '{match($0,/[a-zA-Z]+/);print substr($0,RLENGTH,1)}'

A: I have a list of names I assume is a file, file. Using grep's PCRE and (positive) lookahead:
$ grep -oP "[a-z](?=[^a-z])" file
f

It prints out the first (lowercase) letter followed by a non-(lowercase)-letter.


text:
Q: Why is 'real' and 'really' interchanged? I thought 'real' was an adjective and 'really' was an adverb?
Is it not improper usage to say things like, "I think the cake is real good" ?
Or to have a [news] websites called http://www.realclearpolitics.com/, which I suppose could be correct, though my brain does't process it right away. I'm inclined to think it is attempting to say really clear politics and not real, clear politics
Is this heavy usage and interchangeability of 'real' and 'really' something of the twitter era?


text:
Q: Algorithm over 2 pages I am writing a few rather large pseudocode functions using algorithm and algorithmic, i.e. my code looks something like:
\begin{algorithm}
\caption{Coolest Algorithm ever}
\label{findme}
\begin{algorithmic} [1]                   % enter the algorithmic environment
\REQUIRE    Here are a few variables \\
            variable 2 \\
            variable 3
\ENSURE     this is the output \\
            output 2

\STATE $some cool code here$
\STATE $some cool code here$
\STATE $some cool code here$
\STATE $some cool code here$
\end{algorithmic}
\end{algorithm}

Unfortunately this code does not fit on one page and I am definitely not able to split it into some subfunctions or so (I already did that as far as possible).
So now I need to split up the algorithm into two pages, but I have no idea how.
The easiest way I can imagine is just to start a new algorithm on the new page, but this time letting the line counter start at line 35 or so instead of 1. But how can I do that?
Please not that there is already a similar question here on this site, but it deals with the package algorithmicx.

A: You should use the algorithmicx package instead and its \algstore and \algrestore commands. If you don't want to rewrite all your algorithmic algorithms, you can still use algorithmicx either by loading the algpseudocode package with the compatible option, or by loading the algcompatible package:
\documentclass{article}
\usepackage{algcompatible}
\usepackage{algorithm}

\begin{document}

\begin{algorithm}
\caption{Coolest Algorithm ever}
\label{findme}
\begin{algorithmic} [1]                   % enter the algorithmic environment
\REQUIRE    Here are a few variables \\
            variable 2 \\
            variable 3
\ENSURE     this is the output \\
            output 2
\algstore{myalg}
\end{algorithmic}
\end{algorithm}

\begin{algorithm}
\begin{algorithmic} [1]                   % enter the algorithmic environment
\algrestore{myalg}
\STATE $some cool code here$
\STATE $some cool code here$
\STATE $some cool code here$
\STATE $some cool code here$
\end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: How to use lwd for specific points I would like to change the thickness of the line between two points [(4,1) and (5,0)] in R Plot.
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
y <- c(0, 1, 0, 1, 0, 1, 0, 1, 0)

plot(x, y, type="b", ann = FALSE, axes = FALSE, pch = 20, lwd=ifelse(x>=4 & x<=5, 3, 1))

But, I am only able to make the points thicker. I also need to make the line thicker. Could you guys advice me on where I am wrong.

I tried with lines and segments. I get a line that is touching both the points. But, I need the thicker line to be of the same length as other lines.
Solved using lines

A: With plot, lwd can't accept a vector.  You might want to try using lines instead
plot(x, y, type="b", ann = FALSE, axes = FALSE, pch = 20)

lines(x[4:5], y[4:5], lwd = 3, type = "b")

A: Segments takes (x0,y0) and draws to (x1,y1)
segments(x[4],y[4],x[5],y[5], lwd=3)

A: plot alone cannot actually do what you want. You need to call plot and then segments.
XMIN = 4
XMAX = 5

plot(x, y, type="b", ann = FALSE, axes = FALSE, pch = 20)
xinds = x>=XMIN & x<=XMAX
segments(x[xinds][1:sum(xinds)-1],y[xinds][1:sum(xinds)-1],
         x[xinds][2:sum(xinds)],y[xinds][2:sum(xinds)], lwd=3)


text:
Q: Create an inherited class dynamically, access using base class pointer using std::map? Not sure I can do this. I have question that is a variant of [this other question](Can you create a std::map of inherited classes?
).
Basically the answer to the question below is to create a map of pointers to inherited classes, where the map is searchable based on the first map entry. Then you call use a pointer to address any virtual function you want.
I have implemented a command processor application with a few commands. The map is:
std::map<string, BaseCmdClass*> cmd_map;

All good so far. However we are updating our code to provide potentially hundreds of derived classes. I don't want to create them all in a factory class at the start of the code, too much memory use.
I want to construct an inherited class dynamically when I need it, then delete using the base class pointer. I want to avoid a big case statement to call each constructor.
Is there a way I can create a std::map or use another STL container that can lookup what constructor to call? Then when I need the derived constructor I can lookup this map to find the correct derived constructor to call.

A: struct BaseCmdClass {
  virtual bool do_something() = 0;
  virtual ~BaseCmdClass() {}
};
using upCmd = std::unique_ptr<BaseCmdClass>;
using CmdFactory = std::function<upCmd()>;

using Command = std::string;

std::unordered_map<Command, CmdFactory>& command_factories() {
  static std::unordered_map<Command, CmdFactory> retval;
  return retval;
}
upCmd make_cmd( Command const& cmd ) {
  auto mit = command_factories().find(cmd);
  if (mit == command_factories().end() || !*mit) return {};
  return (*mit)();
}

// in CopyCmd.cpp
struct CopyCmd : BaseCmdClass
  bool do_something() override final {
    std::cout << "did copy";
  };
  static auto registered = command_factories().insert(
    "copy",
    []{ return std::make_unique<CopyCmd>(); }
  );
};

now anyone can make_cmd("copy") and get an instance of CopyCmd via unique pointer to its BaseCmdClass.

A:
Is there a way I can create a std::map or use another STL container that can lookup what constructor to call?

Sure. You cannot store pointers to the constructors directly, but you can store pointers to factory functions that call the constructors.
using CmdFactory = BaseCmdClass*();
std::map<std::string, CmdFactory*> factory_map;

You can use a helper template for generating the factory:
template<class T>
BaseCmdClass* factory() {
    return new T;
}

You can add a factory like this:
factory_map["Derived1"] = factory<Derived1>;

I want to construct an inherited class dynamically when I need it, then delete using the base class pointer. I want to avoid a big case statement to call each constructor.

Deleting using the base class pointer is just fine, as long as the destructor is virtual. No need for a case statement.

Further development:
You can use std::function instead of a function pointer if you have need for stateful factories.
I recommend returning a std::unique_ptr<BaseCmdClass> from the factories to avoid memory leaks.
For lower memory overhead, you can use an array instead of a map if you use an integer as the key, but the code that constructs the array will have to know about all of the children.

A: One of the solutions is to have parallel hierarchy for creators:
class BaseCmdClass {
  ...
};

class BaseCmdCreator;
class BaseCmdFactory {
public:
    static BaseCmdFactory &instance();
    void registerCreator( const std::string &name, BaseCmdCreator *cr );
    ...
};

class BaseCmdCreator {
public:
    BaseCmdCreator( const std::string &name )
    {
         BaseCmdFactory::instance().registerCreator( name, this );
    }
    virtual std::unique_ptr<BaseCmdClass> create() = 0;
};

template<class T>
class CmdCreator : public BaseCmdCreator {
public:
    CmdCreator( const std::string &name ) : BaseCmdCreator( name ) {}
    virtual std::unique_ptr<BaseCmdClass> create() override
    {
        return std::make_unique<T>();
    }
};

Now how to use it - in .cpp file where you define particular CmdClass you create a static object:
// Class FooCmdClass defined here

namespace {
    CmdCreator<FooCmdClass> registerFoo( "FooCmd" );
}

now if you link object file created from this .cpp your class FooCmdClass will be registered. You can do this even through plugin mechanism - fully dynamically. So adding new command will not require any change in base class, only adding new .cpp file to the project.


text:
Q: Updating store display PCs I have 8 PCs that are in our business lobbies that have a PowerPoint file on a constant loop and I want to find the easiest way for a non-admin person to put up a new PowerPoint file from time to time.  A side bonus would to have the computers automatically log in and open the file so we could script the PCs to turn off at night.  The BIOS is configured to return to last power state.
Windows 7
Domain member
Logged is as a local user
wirelessly connected to network

A: The main idea is to have a "Login Script" on each PC for the user logging into the PC.
If this is a Domain PC:
Let the non-admin login to the PC, and then let the login script take over (details below)
If this is a non-domain PC:
You can set auto-login --> run "netplwiz" and untick the "User must enter username and password" and go from there, and again after that let the login script take over.
Login script can be placed here:
C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just for that specific user.
Or if you don't care who is logged in and it will trigger the logon script, you place the script here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Sample code/idea (for a .bat file):
REM Connect to Network Server
net use X: \\SERVER\Share
REM Copy the file locally (so the file is not 'locked' on the network share)
copy /Y X:\path\to\ppt\myppt.ppt C:\temp\
REM Open Powerpoint (which already set to run in a kiosk mode unattended in a loop)
c:\temp\myppt.ppt

Now the server can be any PC that your non-admin have access to or just a share folder that your non-admin can have full access. They can simply throw a new PPT file in there, and at the next login (or forced restart) then the 8 PCs can get the new PPT the next time they boot up and someone logged in.
From here you have 2 options:

*

*Let the non-admin restart all 8 PCs remotely (use a batch script similar to below, but you need to prepare the correct access level for the non-admin)

*Get the non-admin to contact you/other admin, and you can restart the PC remotely.

And that batch file for restarting the PC can have something like:
shutdown /m \\PC01 /r /t 1
.....
shutdown /m \\PC08 /r /t 1

Note: restart the remote PC in 1 second.
About the PC turning off at night.. you can use similar script just change /r with /s for shutdown.
Hope this helps.

A: If you think they are able to edit a batch file in Notepad, and they know how to reference a (.ppt) file somewhere in your network, place two shortcuts on the desktop:

*

*One to edit a START.BAT file in Notepad (give it a useful name like 'Change Powerpoint presentation')

*One to execute that START.BAT ('Start Powerpoint presentation')

Place the START.BAT file in a network directory, so that it can be changed from any one of the 8 PCs.
Add the START.BAT file to the startup folder of each of the PCs.
You can even put instructions in the batch file like:
REM Change the below name of the PowerPoint file to switch to another presentation
You could even write the batch file to concatenate a folder name and a file name, so that all they have to change is the file name.
There's one thing I cannot figure out yet - if anyone knows it please edit my answer - and that's how to restart the other 7 PCs after the change...


text:
Q: object oriented database I am new to object oriented databases.
What is the error in this database schema?
It gives error after insertion query and not before that
insert into student_table values
(
  student_detail
  (
    name_student('abc','pqr'),add_student('ABCD','pqrs'),2000
  )

);

sqlfiddle

A: This works OK (tested on Oracle 11.2):
create or replace type name_student as object
(
  fname varchar2(10),
  lname varchar2(10)
);
/

create or replace type add_student as object
(
  street varchar2(10),
  city varchar2(10)
);
/

create or replace type student_detail as object
(
  name name_student,
  address add_student,
  salary number(10),
  member function getsalary return number
);
/

create or replace type body student_detail as
  member function getsalary return number as
  begin
    return (salary*10);
  end getsalary;
end;
/

show errors;

create table student_table(S student_detail);

Test:
SQL> insert into student_table values
(
  student_detail
  (
    name_student('abc','pqr'),add_student('ABCD','pqrs'),2000
  )
);  2    3    4    5    6    7

1 row created.

SQL> select * from student_table;

S(NAME(FNAME, LNAME), ADDRESS(STREET, CITY), SALARY)
--------------------------------------------------------------------------------
STUDENT_DETAIL(NAME_STUDENT('abc', 'pqr'), ADD_STUDENT('ABCD', 'pqrs'), 2000)

SQL Fiddle doesn't seem to like it too much!


text:
Q: How to toggle nano softwrap on mac I tried the following recommended approaches unsuccessfully to toggle softwrap in nano on MacOS  Catalina:

*

*I can't do Alt+S as in the manual, it gives ß on my keyboard.

*Esc-S gives "Smooth scrolling enabled"

*Esc-$ gives "Unknown command"
What can I do?

A: The default nano on macOS is release 2.0.6.
Soft line wrapping, enabled via the -a command line option or via Esc+$ inside the editor, was introduced in release 2.2.
To install a more recent release of the editor on macOS, use e.g. Homebrew:
brew install nano

This would (currently) install nano release 4.9.2, which also happens to be the most recent release.


text:
Q: Expand and show textbox on icon click I am looking to mimic this functionality : http://jsbin.com/cirafujinu/edit?html,output
<!DOCTYPE html>

    <title>My Geocoding Map</title>
    <meta charset="utf-8">
      <link rel="stylesheet" href="https://mapzen.com/js/mapzen.css">

I attempted to deconstruct the javascript being used to do it but its a 500+ line complicated object with probably more functionality than I need.
I have access to jQuery and jQuery UI. What is the approach I should start with?
I know that it has a focus event where if you focus off the text box it will go back to the minimized state.
I am open to demo/ideas people have seen very similarity functionality so I can use it as reference.

A: CSS-only
you could do it using a couple of elements,

*

*a  wrapper to help registering the :fucus state

*an <input> element with border styles etc, and left padding to accomodate the icon

*an  icon element (placed after the input)

*Target using :focus and use the next sibling + to target the icon when the input is focused:

tl;dr

.expandSearch{
  display: inline-block;
  position: relative;
  overflow: hidden;
}
.expandSearch i{
  position: absolute;
  top: 0;
  left: 0;
  padding: 8px 4px 8px 8px ;
  color: #777;
  cursor: pointer;
  user-select: none;
  transition: 0.24s;
}
.expandSearch i:hover{
  color: #0bf;
}
.expandSearch input{
  border:none;
  background: transparent;
  font:14px/1.4 sans-serif;
  padding-left: 26px;
  background:#fff;
  border: 2px solid #ddd;
  border-radius: 4px;
  transition: 0.24s;
  width: 0px;
  padding: 8px 0px 8px 34px;
}
.expandSearch input:focus{
  border-color: #aaa;
  outline: none;
  width:200px;
  padding: 8px 12px 8px 34px;
  border-color: #0bf;
}
.expandSearch input:focus + i{
  /*padding: 8px 4px 8px 8px ;*/
  color: #ddd;
  pointer-events: none;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <input type="text" placeholder="Search..." name="search">
  search

A: Basically you have to listen for a click on the icon, and then enlarge the box with jQuery UI
 $("#icon").on("click",function(){
      animate();
 })

 function animate(){
      //many ways to do the animation, one way would be to addClass
      $("#icon").addClass("large", 500)

      //Or you can hide an input field inside the icon and just animate that
      $("#input").show()
 }

A: Here is another example making use of both jQuery UI (Button & Autocomplete) and CSS. I've been growing more in my use of Font Awesome too.
HTML

  <form id="search-form">

    <input type="text" id="search" />
  </form>

CSS
.no-border {
  border-color: transparent;
  background-color: white;
}

.collapsed {
  width: 49px;
}

.collapsed input {
  display: none;
}

.expanded {
  width: 280px;
}

.expanded input {
  border: 0;
  width: 200px;
}

JavaScript
$(function() {
  $(".btn").button({
    classes: {
      "ui-button": "no-border",
      "ui-state-default": "no-background"
    }
  }).click(function(e) {
    e.preventDefault();
    var widg = $(this).closest(".item-wrapper");
    widg.toggleClass("collapsed expanded");
    if (widg.hasClass("collapsed")) {
      $("#search").val("");
    }
  });
  var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];
  $("#search").autocomplete({
    source: availableTags
  });
  $("#search-form").submit(function(e) {
    e.preventDefault();
    // Do something with the Search value
  })
});

Working Example: https://jsfiddle.net/Twisty/wfqv3orm/
Hope this helps.