text:
Q: Help with chemistry equation I'm trying to reproduce the following equation using the chemfig package :

I've been at this for a few hours, trying out different approaches but as soon as one thing works, something else seems to go wrong.
The main issue is either the brackets or the charges (or having something come after the brackets).
It doesn't need to be identical to the example. It just has to work and convey the same information.
Here are my best two attempts (there are probably errors, but it seems to partially work on Overleaf):
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{chemfig}
\usepackage[version=3]{mhchem}

\begin{document}

2 \chemfig{R-C(-[:0]\chemabove{O}{-})=[:90]O}\chemabove{Na}{+}}
+
\chemfig{Ca^{2+}}(aq)
\ce{->}
\chemfig{{(}R-C(-[:0]O)=[:90]O}{)_2}Ca}(s)
+

\vspace{2cm}

\schemestart
\chemname{\chemfig{2 R-C(-[:0]\chemabove{O}{-})=[:90]O}\chemabove{Na}{+}}{}(aq)
\+
\chemfig{Ca^{2+}}(aq)
\arrow(.mid east--.mid west)
\chemname{\chemfig{{(}R-C(-[:0]O)=[:90]O}{)}Ca}
    {}(aq)
\+
\chemname{\chemfig{H_2O}}{}
\schemestop
\chemnameinit{}

\end{document}

Here's the output:

A: The following code is a simplified and tweaked MWE that you've posted. In order to mimic sans font (likely Arial, as guidelines of ACS and most other publishers suggest) easier, I switched to XeLaTeX and enabled Fira (free alternative) typeface. Also, I use chemmacros package with all modules enabled as it offers many useful shortcuts, also for the states of aggregation (which, according to IUPAC, shouldn't be subscripts).

% !TEX program = xelatex

\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage{fontspec}
    \setmainfont{Fira Sans}
\usepackage[math-style = ISO]{unicode-math}
    \setmathfont{Fira Math}
\usepackage{siunitx}
\usepackage{chemmacros}
    \chemsetup{
        modules = all,
    }
\usepackage{chemfig}
    \setchemfig{
        atom sep = 1.75em,
        bond join = true,
        bond style = {
            line width = 0.6pt
        },
    }

\begin{document}

\schemestart
2\,\chemfig{R-C(=[:90]O)-O\rlap{${}^-$}}\; \ch{Na+ \aq}
\+
\ch{Ca^2+ \aq}
\arrow(.mid east--.mid west)
\chemleft{[}
    \chemfig{R-C(=[:90]O)-O}
\chemright{]_2}
\ch{Ca \sld}
\+
2\,\ch{Na+ \aq}
\schemestop

\end{document}


text:
Q: merging / combining kdd2009 dataset using Pandas I am trying to merge KDD 2009 dataset as follow as you can see there are 4 dataframes
df_a = pd.read_table( 'orange_large_train.data.chunk1')

df_b = pd.read_table('orange_large_train.data.chunk2')

df_c = pd.read_table( 'orange_large_train.data.chunk3')

df_d = pd.read_table('orange_large_train.data.chunk4')

frames = [df1, df2, df3,df4, df5 ]

orange_kdd_data = pd.concat(frames)

I got the following error, can anyone help?
C:\Users\User\Miniconda3\lib\site-packages\pandas\core\internals.py in concatenate_join_units(join_units, concat_axis, copy)
   4909         raise AssertionError("Concatenating join units along axis0")
   4910
-> 4911     empty_dtype, upcasted_na = get_empty_dtype_and_na(join_units)
   4912
   4913     to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,

C:\Users\User\Miniconda3\lib\site-packages\pandas\core\internals.py in get_empty_dtype_and_na(join_units)
   4898         return np.dtype('m8[ns]'), tslib.iNaT
   4899     else:  # pragma
-> 4900         raise AssertionError("invalid dtype determination in get_concat_dtype")
   4901
   4902

AssertionError: invalid dtype determination in get_concat_dtype

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do I get a java.lang.UnsatisfiedLinkError for com.sun.webkit.dom.HTMLInputElementImpl.clickImpl(J)V on Ubuntu 14.04.5 For some reason I get this execption
Exception in thread "JavaFX Application Thread" io.webfolder.ui4j.api.util.Ui4jException: java.lang.UnsatisfiedLinkError  com.sun.webkit.dom.HTMLInputElementImpl.clickImpl(J)V
    at io.webfolder.ui4j.webkit.aspect.WebKitAspect$CallableExecutor.run(WebKitAspect.java:41)
    at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
    at com.sun.glass.ui.monocle.RunnableProcessor.runLoop(RunnableProcessor.java:92)
    at com.sun.glass.ui.monocle.RunnableProcessor.run(RunnableProcessor.java:51)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsatisfiedLinkError: com.sun.webkit.dom.HTMLInputElementImpl.clickImpl(J)V
    at com.sun.webkit.dom.HTMLInputElementImpl.clickImpl(Native Method)
    at com.sun.webkit.dom.HTMLInputElementImpl.click(HTMLInputElementImpl.java:506)
    at io.webfolder.ui4j.webkit.dom.WebKitElement.click_aroundBody50(WebKitElement.java:299)
    at io.webfolder.ui4j.webkit.dom.WebKitElement$AjcClosure51.run(WebKitElement.java:1)
    at io.webfolder.ui4j.internal.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:149)
    at io.webfolder.ui4j.webkit.aspect.WebKitAspect$CallableExecutor.run(WebKitAspect.java:39)
    ... 6 more

My system is
~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

And my JAVA version is
:~# java -version
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) Server VM (build 25.151-b12, mixed mode)

And if I run the nm command on the so-lib I seem to think that the function is there
:~# nm /usr/lib/jvm/java-8-oracle/jre/lib/i386/libjfxwebkit.so | grep HTMLInputElementImpl | grep clickImpl
010254b0 t Java_com_sun_webkit_dom_HTMLInputElementImpl_clickImpl

What is it that I am missing in all of this ?
I have tried numerous times to reinstall Java, but that did not help.

A: I get the same issue on macOS. One workaround is to check if the node/element is a HTMLInputElement with type==submit and in those cases invoke .getForm().submit().

A: I ran into the same issue in JDK-14 and JFX-14. My workaround is to use webEngine.executeScript instead because getForm() returns null for my use case.


text:
Q: rename directories recursively window command line For I need to copy a directory tree and at the same time rename directories with a given name to another name anywhere such name is found in the path:
replace "d" to "k" any where it is found under c:\a\b\c and its sub directories. So,

from: c:\a\b\c\d
to:   c:\a\b\c\k
and
from: c:\a\b\c\d\e\d\f\d\...
to:   c:\a\b\c\k\e\k\f\k\...

for /r "C:\a\b\c\" %%x in (*d*) do ren "%%x" *k*

The command prompt window opens and closes very fast and no output in the directory c:\a\b\c is noted.  Any ideas?
Thank you


text:
Q: Do objects reflect light of their own color based off constructive wave interference? Note: Why objects reflect light of their color is already answered here:
Physics of color: why do visible colors absorb all colors except the color itself?
My question is whether my following theory of why this happens is also valid (stop me anywhere that I go wrong):
My thinking was that a red object has red light-waves. When a light-wave hits it, the red portion of the light-wave is in phase with the object's red light-waves, and so due to constructive interference the red light is amplified (which is why we see it most).
Conversely, most other color portions of the light-wave that hits the object are out of the phase with the object's red light-waves, and due to destructive interference we don't see these colors.
Is this theory correct?

A: First, in the article you mention, it says that biological color perception is different from physical color wavelength associations.
When you say a red object, it can reflect many wavelengths of EM waves, which altogether our eye and brain perceive as red.
But let us just talk about an object that would reflect only red wavelength EM waves, so in a physical way it would be red.
What happens with that object is, that the molecular structure of the object is so that the atoms' electrons energy levels (as per QM) have available levels so the atoms can be excited and so some wavelength photons will be absorbed. Other photons will not be absorbed (because they do not fit the available energy level's differences) and so those will be reflected.
The physical color of the object, so the EM waves that come from the object are reflected and emitted both. Some of the emitted are not even visible wavelengths.
So the physical color of the object comes from:
1.reflection of red wavelength photons
2.emission of red wavelength photons
So basically the object will absorb and re-emit some photons, and will reflect some others. All of those photons together will be the physical color of the object (the ones that are in the visible wavelength). So some of the EM waves coming from the object will not even be in the visible wavelength.
But you are talking about the visible red wavelength ones so I am going to talk about those wavelengths.
The photons that are reflected are usually elastically scattered, so their wavelength is the same, their energy level is the same, only their direction is changed.
The photons that are absorbed and re-emitted are sometimes not emitted at the same wavelength (some of them). It is because when an atom gets excited, and the electron moves to a higher energy level (as per QM), the electron will come down to the lower level again. But the electron can come down in multiple steps. And in that case it is emitted multiple photons with different wavelengths then the originally absorbed photon. So if a photon gets absorbed, sometimes it is re-emitted with the same wavelength, in that case the electron came down to the lower energy level in only one step.
But sometimes the electron will come down to the lower energy level in multiple steps, and sometimes the electron will be excited so (when absorbing a photon) that it will move to a higher energy level of more then one level away, so it will go up more then one level at one step (with one absorption).
So basically one absorption can have multiple re-emissions, and in that case the absorbed wavelength, in your case red, will have nothing to do with the re-emitted wavelength.
In your case, the reason the object is red (physically again, not biologically) is because:

*

*it is reflecting and emitting red wavelength photons.

*And because it is absorbing other wavelengths, non-reds.

*And it is only re-emitting red wavelength photons.

*Even if it is absorbing non-red wavelengths, it will still re-emit red wavelength photons.


text:
Q: Toast.LENGTH_LONG I am new to android, and I am understanding some already developed code. I am confused about Toast.LENGTH_LONG. I searched for it, and what I got is - Toast is like an alert message which will disappear after some time, but am not getting it further clearly,
so please anyone can help me?

A: try this
 Toast.makeText(getApplicationContext(), "Your Message", Toast.LENGTH_LONG).show();

exactly it is time period for toast still any doubt than please prefer here

A: Toast is a temporary view that runs in ui thread for a limited time and disappears automatically . Assume it as smoke comes out of toaster in real world . IT disappears after some time . This is how toast works in android . To implement it user .
 Toast.makeText(getApplicationContext(), "Your Message", Toast.LENGTH_LONG).show();

LENGTH_SHORT   Show the view or text notification for a short period of time.This time could be user-definable. This is the default.
LENGTH_LONG Show the view or text notification for a long period of time.This time could be user-definable.
Read this for further information.

A: Take always a look to the official android documentation.
Here are all informations you need: http://developer.android.com/reference/android/widget/Toast.html
LENGTH_LONG     Show the view or text notification for a long period of time.
LENGTH_SHORT    Show the view or text notification for a short period of time.


text:
Q: awk or sed to change column value in a file I have a csv file with data as follows
16:47:07,3,r-4-VM,230000000.,0.466028518635,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,0.50822578824,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.488406067907,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.467893525702,131072,0,0,0,0,0

I would like to shorten the value in the 5th column.
Desired output
16:47:07,3,r-4-VM,230000000.,0.46,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,0.50,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.48,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.46,131072,0,0,0,0,0

Your help is highly appreciated

A: awk '{$5=sprintf( "%.2g", $5)} 1' OFS=, FS=, input

This will round and print .47 instead of .46 on the first line, but perhaps that is desirable.

A: Try with this:
cat filename | sed 's/\(^.*\)\(0\.[0-9][0-9]\)[0-9]*\(,.*\)/\1\2\3/g'

So far, the output is at GNU/Linux standard output, so
cat filename | sed 's/\(^.*\)\(0\.[0-9][0-9]\)[0-9]*\(,.*\)/\1\2\3/g' > out_filename

will send the desired result to out_filename

A: If rounding is not desired, i.e. 0.466028518635 needs to be printed as  0.46, use:
cat <input> | awk -F, '{$5=sprintf( "%.4s", $5)} 1' OFS=,

(This can another example of Useless use of cat)

A: You want it in perl, This is it:
perl -F, -lane '$F[4]=~s/^(\d+\...).*/$1/g;print join ",",@F' your_file

tested below:
> cat temp
16:47:07,3,r-4-VM,230000000.,0.466028518635,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,10.50822578824,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.488406067907,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.467893525702,131072,0,0,0,0,0
> perl -F, -lane '$F[4]=~s/^(\d+\...).*/$1/g;print join ",",@F' temp
16:47:07,3,r-4-VM,230000000.,0.46,131072,0,0,0,60,0
16:47:11,3,r-4-VM,250000000.,10.50,131072,0,0,0,0,0
16:47:14,3,r-4-VM,240000000.,0.48,131072,0,0,32768,0,0
16:47:17,3,r-4-VM,230000000.,0.46,131072,0,0,0,0,0

A: sed -r 's/^(([^,]+,){4}[^,]{4})[^,]*/\1/' file.csv

A: This might work for you (GNU sed):
sed -r 's/([^,]{,4})[^,]*/\1/5' file

This replaces the 5th occurence of non-commas to no more than 4 characters length.


text:
Q: Reddit PRAW Failing to authenticate due to SSL error My code is currently this:
from bs4 import BeautifulSoup
from urllib.parse import urlparse

import requests
import praw
import time
import re
import bs4

USERAGENT = 'web:PeskyTrollBot:v0.1 (by /u/redacted)'
PASSWORD = 'NOTREALLYMYPASSWORD'
USERNAME = "PeskyTrollBot"
ID = 'redacted'
SECRET = 'redacted'

def authenitcate():
    print("Authenticating...")
    reddit = praw.Reddit(client_id=ID, client_secret=SECRET,
                     password=PASSWORD, user_agent=USERAGENT,
                     username=USERNAME)
    print("Authenticated as {}\n" .format(reddit.user.me()))
    return reddit

authenitcate()

and my console output (after now having installed pyopenssl) is as follows:
    C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/JoshLaptop/PycharmProjects/practice/TestBot.py
Authenticating...
Traceback (most recent call last):
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\contrib\pyopenssl.py", line 441, in wrap_socket
    cnx.do_handshake()
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\OpenSSL\SSL.py", line 1716, in do_handshake
    self._raise_ssl_error(self._ssl, result)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\OpenSSL\SSL.py", line 1456, in _raise_ssl_error
    _raise_current_error()
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\OpenSSL\_util.py", line 54, in exception_from_error_queue
    raise exception_type(errors)
OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 595, in urlopen
    self._prepare_proxy(conn)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 816, in _prepare_proxy
    conn.connect()
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connection.py", line 326, in connect
    ssl_context=context)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\contrib\pyopenssl.py", line 448, in wrap_socket
    raise ssl.SSLError('bad handshake: %r' % e)
ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py", line 440, in send
    timeout=timeout
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\retry.py", line 388, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.reddit.com', port=443): Max retries exceeded with url: /api/v1/access_token (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\requestor.py", line 47, in request
    return self._http.request(*args, timeout=TIMEOUT, **kwargs)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py", line 506, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='www.reddit.com', port=443): Max retries exceeded with url: /api/v1/access_token (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/JoshLaptop/PycharmProjects/practice/TestBot.py", line 19, in <module>
    authenticate()
  File "C:/Users/JoshLaptop/PycharmProjects/practice/TestBot.py", line 16, in authenticate
    print("Authenticated as {}\n" .format(reddit.user.me()))
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\praw\models\user.py", line 60, in me
    user_data = self._reddit.get(API_PATH['me'])
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\praw\reddit.py", line 367, in get
    data = self.request('GET', path, params=params)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\praw\reddit.py", line 472, in request
    params=params)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 175, in request
    params=params, url=url)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 121, in _request_with_retries
    retries, saved_exception, url)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 87, in _do_retry
    params=params, url=url, retries=retries - 1)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 121, in _request_with_retries
    retries, saved_exception, url)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 87, in _do_retry
    params=params, url=url, retries=retries - 1)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 109, in _request_with_retries
    data, files, json, method, params, retries, url)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 94, in _make_request
    params=params)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\rate_limit.py", line 32, in call
    kwargs['headers'] = set_header_callback()
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\sessions.py", line 135, in _set_header_callback
    self._authorizer.refresh()
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\auth.py", line 328, in refresh
    password=self._password)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\auth.py", line 138, in _request_token
    response = self._authenticator._post(url, **data)
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\auth.py", line 29, in _post
    data=sorted(data.items()))
  File "C:\Users\JoshLaptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\prawcore\requestor.py", line 49, in request
    raise RequestException(exc, args, kwargs)
prawcore.exceptions.RequestException: error with request HTTPSConnectionPool(host='www.reddit.com', port=443): Max retries exceeded with url: /api/v1/access_token (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

Process finished with exit code 1

I have tried multiple suggestions from other stackoverflow posts such as updating my useragent to fit the Reddit guidelines for one. I have tried telling it not to verify ssl certificates right after I created the praw object and the error still persists. I also tried using a try catch loop with a minute sleep after each catch to no avail. any ideas for troubleshooting? I've ran out of tips from other posts so I now am making my own.


text:
Q: Why does this operation execute faster on CPU than GPU? When I was reading the tensorflow official guide, there is one example to show Explicit Device Placement of the operations. In the example, why does CPU executed time is less than GPU? More usually, what kind of operation will be executed faster on GPU?
import time

def time_matmul(x):
  start = time.time()
  for loop in range(10):
    tf.matmul(x, x)

  result = time.time()-start

  print("10 loops: {:0.2f}ms".format(1000*result))

# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
  x = tf.random.uniform([1000, 1000])
  assert x.device.endswith("CPU:0")
  time_matmul(x)

# Force execution on GPU #0 if available
if tf.test.is_gpu_available():
  print("On GPU:")
  with tf.device("GPU:0"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.
    x = tf.random.uniform([1000, 1000])
    assert x.device.endswith("GPU:0")
    time_matmul(x)

### Output
# On CPU:
# 10 loops: 107.55ms
# On GPU:
# 10 loops: 336.94ms

A: GPU has high memory bandwidth and a high number of parallel computation units. Easily parallelizable or data-heavy operations would benefit from GPU execution. As, for example, matrix multiplication involves a large number of multiplications and additions that can be done in parallel.
CPU has low memory latency (which becomes less important when you read a lot of data at once) and a rich set of instructions. It shines when you have to do sequential calculations (fibonachi numbers might be an example), have to make random memory reads often, have complicated control flow etc.
The difference in the official blog is due to the fact, that PRNG algorithms are typically sequential and can not utilize parallelized operations quiet efficiently. But this is in general. Latest CUDA version already has PRNG kernels and does outperform CPU on such tasks.
When it comes to the example above, on my system I got 65ms on CPU and 0.3ms on GPU. Furthermore, if I set sampling size to [5000, 5000] it becomes CPU:7500ms while for GPU it stays the same GPU:0.3ms. On the other hand fo [10, 10] it is CPU:0.18 (up to 0.4ms though) vs GPU:0.25ms. It shows clearly, that even a single operation performance depends on the size of the data.
Back to the answer. Placing operations on GPU might be beneficial for easily parallelizable operations that can be computed with a low number of memory calls. CPU, on the other hand, shines when it comes to a high number of low latency (i.e. small amount of data) memory calls. Additionally, not all operations can be easily performed on a GPU.


text:
Q: Assign result of calculation in sympy to function I looked through several questions here on SO, but I could not find a solution for this problem:
I calculate a fourier transformation in sympy with fourier_transform(exp(-tau*abs(t)), t, w). I assigned tau, t and w with tau, t, w = symbols('tau t w'). How can I put the result of the FT into a function, e.g. something like
g(tau, w) = fourier_transform(exp(-tau*abs(t)), t, w)

? When I write it like that, I get the error can't assign to function call. When I do it like
g = fourier_transform(exp(-tau*abs(t)), t, w)

then I can not call it (as usually) with g(tau, w) or something similar. Is there a way to do that?
Edit: What I want to have as a final result is:
g(tau, w) = 2*tau/(tau**2 + 4*pi**2*w**2)

and I can call g simply with (f.eks) g(2, 3).
Edit II: Python call:
>>> fourier_transform(exp(-tau*abs(t)), t, w)
2*tau/(tau**2 + 4*pi**2*w**2)

A: Just if you want an inline solution, you can use lambda to approach so:
g = lambda tau,w: ourier_transform(exp(-tau*abs(t)), t, w)

Assuming the t is a local variable.
By the way, you can also use the standard function definition, but never try to define a function as a variable.

A: So you create your g method and use the fourier_transform inside the g method like this:
But you have to provide the t also
def g(tau, w):
    return fourier_transform(exp(-tau*abs(t)), t, w)


text:
Q: What is the difference between "In many ways" and "In many means" Can "in many means" be used at all? Like here, for example:

Tea and Ceylon are synonymous in many means

Or is it better to use "in many ways" in this situation?

A: "Means" is not right in this context.
I think the source of your confusion is that "ways and means" are often mentioned together, but they mean different things, otherwise it would be pointless saying both together!

*

*A way is a possible method, style or manner

*A means is an available resource
For example, driving and walking are two different ways of getting somewhere, but if you own a car then you have a means of transportation.
In the context of your example, a "way" means a particular aspect of something.
Your sentence should read:

Tea and Ceylon are synonymous in many ways.


text:
Q: convergence of bounded, holomorphic functions on the disk I want to show that a sequence of holomorphic, zero-free functions on the disk converges uniformly to zero on compact subsets of the disk if $|f_n| < 1$ and $\lim_{n \rightarrow \infty} f_n(0) = 0$.
My idea was to use Liouville's theorem to argue that $f_n$ must be constant , but I don't have a entire function. Is there a way to use Liouville for functions that are just holomorphic on the disk?

A: Each $f_n$ need not be zero, as we see from the example $f_n(z)=\frac{42+z}{2019n}$. On the other hand, it is still true that $(f_n)$ converges locally uniformly (converges uniformly on compact subsets) to the zero function.
Here is (possibly not the simplest) proof: Write $\mathbb{D}$ for the unit disk and let $f_n : \mathbb{D} \to \mathbb{D}$ be a sequence of holomorphic functions such that $f_n(0) \to 0$ as $n\to\infty$.

*

*For each subsequence $(f_{n_k})$ of $(f_n)$, there exists a further subsequence $(g_{j})$ which converges locally uniformly on $\mathbb{D}$. Indeed, let $0 < r_1 < r_2 < \cdots $and $r_n \uparrow 1$. Then for each $n$, the bound
$$ \forall z \in \overline{B(0,r_n)}, \qquad \left| f_n'(z) \right| = \left| \frac{1}{2\pi i} \int_{|\xi|=r_{n+1}} \frac{f(\xi)}{(z-\xi)^2} \, \mathrm{d}\xi \right| \leq \frac{r_{n+1}}{(r_{n+1} - r_n)^2} $$
shows that $(f_n)$ is equicontinuous on each $\overline{B(0,r_n)}$, and so, we can emply Arzela-Ascoli theorem and diagonal argument to extract a (further) subsequence $(g_j)$ of $(f_{n_k})$ which converges uniformly on each $\overline{B(0,r_n)}$.

*Since each $g_j$ is zero-free and converges locally uniformly, by Hurwitz's theorem,  its limit is either identically zero or also zero-free. Since the latter option is impossible, it follows that the limit is identically zero.

*We have shown that: for each subsequence of $(f_n)$, there is a further subsequence which converges locally uniformly to $0$. This implies that $(f_n)$ itself converges locally uniformly to $0$.


text:
Q: Groovy - How to trim spaces for each element in an array I need to remove spaces from the value of City --
Here is the JSON-
{
  "School" : New Elementary School,
  "District" : "District1",
  "City" : "NewTown",
     "Students" : [ {
     "Name": "Student1",
     "Grade": "1"
     "City":"     ABC"
    }, {
     "Name": "Student2",
     "Grade": "2"
     "City":"     DEF"
    }, {
     "Name": "Student3",
     "Grade": "1"
     "City":"     GHI"
    }, {
     "Name": "Student4",
     "Grade": "1"
     "City":"     JKL"
    }, {
     "Name": "Student5",
     "Grade": "1"
     "City":"     MNO"
    } ],
}

I tried using trim () by iterating on the Array. But the space still exists.
 def ArraySize = jsonIn."Students"."Row Set"[0].size()
 for(int i=0; i <= ArraySize ; i++)
 {
  jsonIn."Students"[0]."City"[i] = jsonIn."Students"[0]."City"[i].trim()
 }

A: Since after reading the data as json, you already have an copy, you can just reach into the structure and change it in place.  So your for was already in the right direction.  Iterate each Student and then replace the City in-place:
def data = new groovy.json.JsonSlurper().parseText("""{ "School" : "New Elementary School", "District" : "District1", "City" : "NewTown", "Students" : [ { "Name": "Student1", "Grade": "1", "City":" ABC" }, { "Name": "Student2", "Grade": "2", "City":" DEF" }, { "Name": "Student3", "Grade": "1", "City": " GHI" }, { "Name": "Student4", "Grade": "1", "City": " JKL" }, { "Name": "Student5", "Grade": "1", "City":" MNO" } ], }""")

data.Students.each{
    it.City = it.City.trim()
}

assert data.Students*.City == ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']


text:
Q: No effects with nivoSlider Nivo slider is working fine but does not do any effects.

A: Its a z-index problem, in nivo-slider.css:18
.nivoSlider img {
...
    z-index: 50;
}

This is covering up the animation, remove it and you'll see the transitions.

A: First thing, you need to give the <script> tags inside <head> tag.
<!-- Javascripts -->
<script src="http://ipmgroup.org/wp-content/themes/ipmgroup/scripts/jquery-1.7.1.min.js"></script>
<script src="http://ipmgroup.org/wp-content/themes/ipmgroup/scripts/jquery.nivo.slider.js"></script>
<script src="http://ipmgroup.org/wp-content/themes/ipmgroup/scripts/ipm.main.js"></script>

Try changing it and check out. Finally, the CSS Part:
// Need more z-index from default
//Line Number 45!
.nivo-slice {z-index: 100;}
//Line Number 18!
.nivoSlider img {z-index: 10;}

Try this and it works! :)


text:
Q: How to join two arrays in a LINQ query and use the result further in the query? Sorry for the noobish question, i have no idea about linq and have to extend a query in a code which is not from me.
Is it possible to join two enumerables which are results of two different method calls into one enumerable?
var attibutes = from MemberDescriptor a in
     (TypeDescriptor.GetProperties(this) **and** TypeDescriptor.GetEvents(this))
      let attribute = a.Attributes[typeof(MyAttributeAttribute)]
                                as MyAttributeAttribute
      where attribute != null
       select new AttributeTuple { Property = a, Attribute = attribute };

Thanks a lot!

A: You can use Enumerable.Concat to concatenate two IEnumerable<T> sequences, however, in your case, the two objects are of different types, so this will not work properly without also using Enumerable.Cast<T>.
You could potentially treat both as MemberDescriptor via:
var search = TypeDescriptor.GetProperties(this).Cast<MemberDescriptor>()
               .Concat(TypeDescriptor.GetEvents(this).Cast<MemberDescriptor>());

var attibutes = from MemberDescriptor a in search
            let attribute = a.Attributes[typeof(MyAttributeAttribute)] as MyAttributeAttribute
            where attribute != null
            select new AttributeTuple { Property = a, Attribute = attribute };


text:
Q: How to align a
* with an existing menu? I am having trouble aligning a

  with an existing navigation.  The more option floats on top of the second option.  How to make them all aligned?
Code:

name

Post

Post Article

Post Book

Post Other

Post Other

Post Other

Post Other

Post Other

Post Other

Post Other

Post Other

  Article
  Books
  Other
  Other
  Other
  Other
  Other

CSS:
 #nav {
 margin-left: 230px;
 margin-top:-19px;
 }

 #option {
 margin-left:20px;
 }

I am not using anything for thestuff tag.

A: Use a class for elements that you have more than one of.
By definition an id has to be unique


text:
Q: Comparing size of NULL macro with size of char I'm testing to see that the NULL constant does indeed occupy the size of a pointer:
ASSERT(sizeof NULL == sizeof(char*));

However, I accidentally wrote the following instead:
ASSERT(sizeof NULL == sizeof char);

That should have compiled, but instead it gave me the following error:
error: expected expression before 'char'

The same happened after I enclosed NULL in brackets
ASSERT(sizeof(NULL) == sizeof char);

Isn't the NULL constant usually suppose to be defined by a macro which associates it to a pointer which is equal to 0? The statement was obviously false but as far as I see there was no syntactic error.
If that is true, why was I receiving a compilation error?

A: "When the operand is a type name, it must be enclosed in parentheses": C sizeof operator
In C, NULL is usually defined as
#define NULL ((void*)0)


text:
Q: How can I use Helvetica Light or Neue in moderncv? I have gotten Helvetica working in Xavier Danaux's moderncv by placing in the following lines in banking.sty to typeset my cv.tex file. I'm using texShop on OSX.
\usepackage[scaled]{helvet}
\renewcommand\familydefault{\sfdefault}
\usepackage[T1]{fontenc}

I even tried
\usepackage{fontspec}
\setmainfont{Helvetica}

to access my system fonts (Helvetica, Hel Neue and Hel Light are installed in my OS X) however I get he following error:
LaTeX Font Warning: Some font shapes were not available, defaults substituted.

I checked my fc-list in terminal and Helvetica Light and Neue are there. Any suggestions or pointers?


text:
Q: Runtime error when pushing to a vector of a vector I've been having run-time errors with this program for a few days now, and have finally been able to find what the issue is: the push_back function is for some reason never completing, leading to a crash.
The Constructor is fine, the stringstream is fine (I've cout tested both of them), but anything after vctr[i].push_back(Pixel(r,g,b); does not run whatsoever. The program will immediately time out at that point.
Also, it does the same thing when trying directly assign values to the vector. Ex: vctr[i][j] = Pixel(r,g,b);
Code in Question:
bool Picture::filetoVector(ifstream& fin, vector<vector<Pixel> >& vctr, int& cmax){
    string line, filetype;
    istringstream ssin;
    int width, height, r, g, b;

    //if fin fails to open file, return false & quite function.
    if(fin.fail()) return false;

    //This for loop grabs filetype, # of rows & columns (height & width), and cmax.
    for(int i = 0; getline(fin,line) && i < 3;i++){....}

    //This loop reads to vctr.
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            getline(fin,line);
            ssin.clear();
            ssin.str(line);

            ssin >> r >> g >> b;
            //This is where things are breaking.
            vctr[i].push_back(Pixel(r,g,b));
        }
    }
    return true;
}

Pixel Class:
struct Pixel{
    int red, green, blue;
    Pixel();
    Pixel(int r, int g, int b);
};

Pixel is very basic, containing only 3 integers and two Constructors. Pixel() sets red, green & blue to zero, Pixel(int r, int g, int b) sets red to r, green to g and so on.
filetoVector's call:
if(newpicture.filetoVector(filein, newvector, colorMax)){
    cout << "Error: unable to read PPM file " << inputFilename;
    return -1;
}

A: Welcome to StackOverflow Dante. You definitely did not post enough information to get a quick and smart answer here. You should post more code, specially:

*

*the one calling the function so that people can figure out how vctr is initialized.

*the Pixel class definition (does this one respect the rule of three? If not, pushing Pixel items to a vector is most likely unsafe)

I give it a try in "blind mode" anyway, you're most likely accessing vctr with an out-of-bound index when you do vctr[i]:
So you should simply do:
vctr.resize(height)

before your start the two nested for loops. To make sure there are height elements available in there...


text:
Q: Accessing RouterLinkActive in a nested component using Angular 6 I have a list-group defined as a list of recipe-items. I'm using the child routing in order to display a description of the item whenever the user clicks on a list element. So far the click event and the routing are working but I want to mark the clicked item as active.
recipe-list.component.html

<app-recipe-item
  *ngFor="let recipeEl of recipes; let i = index"
  [recipe]="recipeEl"
  [routerLink]="i"
  style="cursor: pointer;"
  >
</app-recipe-item>

In order to do it I'm trying to use the routerLinkActive directive within my nested RecipeItemComponent but it looks like the directive is out of scope for the nested component.
recipe-item.component.html

     TO BE MARKED AS ACTIVE WHEN CLICKED

What am I missing? Even using a localRef it's impossible to retrieve its value in a nested component.

A: Using the RouterLinkActive directive and its property isActive
Using the RouterLinkActive and a local reference it's possible to pass the value of isActive to an @Input() property of the nested component in order to use it in its template to trigger ngClass.
recipe-list.component.html
 <app-recipe-item
  *ngFor="let recipeEl of recipes; let i = index"
  [recipe]="recipeEl"
  [routerLink]="i"
  routerLinkActive
  #rla="routerLinkActive"
  [currentlySelected]="rla.isActive"
  style="cursor: pointer;"
  >
</app-recipe-item>

recipe-item.component.ts
@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
  @Input() recipe: Recipe;
  @Input() currentlySelected: boolean;

recipe-item.component.html
...

...

A: routerLinkActive directive add special styles to actived link by subscribing to router's navigate event, see source code.
You can do the same in your app-recipe-item component as well without using routerLinkActive directive.(code is the same)

Another way, routerLinkActive provides an isActive property which shows whether current routerLink is active or not. You can inject it as your component as well to retrieve its value and change to active style.
<app-recipe-item
  *ngFor="let recipeEl of recipes;
  let i = index" [recipe]="recipeEl"
  [routerLink]="i" style="cursor: pointer;"
  routerLinkActive
>
</app-recipe-item>

constructor(
  @Inject(RouterLinkActive) private activeRouter: RouterLinkActive  // inject
) { }

  TO BE MARKED AS ACTIVE WHEN CLICKED

Refer demo.


text:
Q: React-Redux mapStateToProps doesn't trigger when state changes I'm learning Redux state management and got stuck with an issue. The mapStateToProps within a component is not triggered when the state changes. Gone through a lot of blogs, couldn't able to figure out the problem.
The store seems to update properly, as the "subscribe" method on store prints new changes. Attached screenshot as well.
Actions.js
export const GET_ITEMS_SUCCESS = "GET_ITEMS_SUCCESS";
export const GET_ITEMS_FAILURE = "GET_ITEMS_FAILURE";
export const getItemsSuccess = (items) => ({
    type: GET_ITEMS_SUCCESS, payload: items
});
export const getItemsFailure = (error) => ({
    type: GET_ITEMS_FAILURE, error: error
});
export function getItems(dispatch) {
    return dispatch => {
    fetch(myList)
        .then(res => res.json())
        .then(res => {
            if(res.error) {
                throw(res.error);
            }
            store.dispatch(getItemsSuccess(res));
            return res;
        })
        .catch(error => {
            store.dispatch(getItemsFailure(error));
        })
   }
}

Reducer
let initialState = {items: [], error: null}
function GetItemsReducer (state = initialState, action) {
    switch (action.type) {
        case GET_ITEMS_SUCCESS:
           return Object.assign({}, state, {pending: false, items: action.payload});
       case GET_ITEMS_FAILURE:
           return Object.assign({}, state, {pending: false, error: action.error});
       default:
           return state;
    }
}
export default const rootReducer = combineReducers({
    GetItemsReducer: GetItemsReducer
});

Store
const mystore = createStore(rootReducer, applyMiddleware(thunk, promise));
mystore.subscribe(() => console.log("State Changed;", mystore.getState()));

Component
class Home extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        this.props.fetchItems();
    }
    render() {
       return (
          <div>{this.props.items.length}</div>
       )
    }
}
const mapStateToProps = (state) => {
   console.log('mapStateToProps ----------> ', state);
   return {
      items: state.GetItemsReducer.items,
      error: state.GetItemsReducer.error
   }
}
const mapDispatchToProps = (dispatch) => {
    return {
       fetchItems: bindActionCreators(getItems, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);

Main
class App extends React.Component {
    render() {
       return (
          <Provider store={mystore}>
             <Home />
          </Provider>
       )
   }
}
ReactDOM.render(<App />, document.querySelector("#app"))

Thanks in advance.


text:
Q: Eclipse on Windows 7 Every time I open eclipse Galilio on Windows 7 64bit this message appear
and it won't work
-------------------------------------------------------------------------------------
Faild to load the JNI shared library "C:\Program Files(x86)\java\jre6\client\jvm.dll"
-------------------------------------------------------------------------------------

Help me please.

A: If you are using the 64-bit distribution of Galileo, you need a 64bit distribution of JRE (not a 32bit installed in "C:\Program Files(x86)").
If not (you are using a 32bit) version, you can (as in this thread),

*

*Check your path variable,

*make sure that if you type "java -version" at a command prompt you get the version you expect.

*Or better yet, edit your eclipse.ini file to specify a particular JVM location.
  See http://wiki.eclipse.org/Eclipse.ini for examples.

A: Now check out what's below. This should help you fix your Eclipse issue with Java and Windows 7 64-bit.
Eclipse will not open when the exe is clicked on Windows 7 64-bit OS.
Eclipse Standard/SDK
Version: Kepler Release
Build ID: 2013614-0229
This is for the Firefox v22 64-bit browser
OS: Windows OS 64-bit

*

*Okay, you assume that Java is set properly on your Windows 64-bit PC and you've loaded Eclipse in a folder on your desktop. You've also created a separate folder called Eclipse Workspace which also resides on the desktop. Now you're ready to go and then in the Eclipse/Eclipse directory you click the Eclipse.exe and then you get this janky error message after the Eclipse window opens:

"Java was started but returned exit code=1" (with other related data)
or ------->

*

*You clicked the Eclipse.exe file and this message was displayed: "A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java Virtual Machine was found after sending the following locations: c:\Program Files (x86)\Java\jre7\javaw.exe" or something like this. Now I'm not saying that this solution will work for everyone but note that this is a good baseline starting point to find out your solution.

--- or ---
2b. In DOS, you typed Java or java -version in the command line, pressed  then this error was thrown:
"Picked up_Java_options:
-Xrunjvmhook -Xbootclasspath/a:C"\Program~2\hp\Quickt~1\bin\Java_S~1\classes;c:\Progra~2\hp\Quickt~1\bin\Java_S~1\classes\jasmine.jar
Error occurred during initialization fo VM could not find agent library JVMhook on the library path; with error" Can't find dependent libraries..."

* Again, keep in mind, this process is being done with the FireFox v22 64-bit browser** If using this browser, you need to check the following, to see if Java is enabled in the browser. I know what you're thinking but just do it!

*

*Open or maximize the Firefox browser.

*At the top left of the page, click Tools then the Add-ons option.

*Click the Plugins option in the left pane.

*You should see:
Java Development Toolkit 7.0.250.17 10.25.2.17 NPRuntime Script Plug-in Library for
Java (TM) Deploy. (or a plugin with a relevant version number)

*Look to the right and make sure this plugin is Enabled~! If it is not Enabled, enable it!

*If you do not see this plugin, at the top of this page, enter "Java" in the Search All Add-ons field, locate the plugin then install it.

*

*Now go to Java.com and download the current version of Java for 64-bit. You need a JRE (Java Runtime Environment) and a JDK (Java Development Kit files and both have to be 64-bit!!!!!!! Once downloaded run both. They usually sit at either of these locations with these path distinctions:

c:\Program Files\Java\jre7   (This is the location of the JRE=Java Runtime Environment)
c:\Program Files\Java\jdk1.7.0_25  (This is the location of the JDK=Java Development Kit)
--- or ---
c:\Program Files (x86)\Java\jre7  (This is the location of the JRE=Java Runtime Environment)
c:\Program Files (x86)\Java\jdk1.7.0_25 (This is the location of the JDK=Java Development Kit)
* Now keep in the these version numbers will change but here are the preferred locations.

*

*Environment Variables Edits

*Click Windows Start button (bottom left on Windows 7) then click Computer.

*At the upper left, click System Properties. The Control Panel Home window opens.

*Click the Advanced System Settings option.

*Your User Account Control window may open.

*Click the [Yes] button.

*The Systems Properties window opens.

*Click the [Environment Variables] button.

*Go to the User Variables for (Your System Name here).

*Delete everything here accept, the following:

*

*PATH

*TEMP

*TMP

*Now highlight the PATH variable and then click the [Edit] button.

*The Edit User Variable window opens.

*You want to add the following:
;c:\users\Your User Name\desktop\eclipse\eclipse\jre\bin;c:\Program Files (x86)\Java
 \jre\bin;c:\Program Files (x86)\jre7\;c:\Program Files (x86)\Java\jdk1.7.0_25\bin

*Click the [OK] button and the Edit User Variable window closes.

*Now go to the System Variables section.

*Delete all the Variables accept the following:

*

*asl.log

*CLASSPATH

*Comspec

*FP_NO_HOST_C...

*NUMBER_Of_P...

*OnlineServices

*OD

*PATH

*PATHTEXT

*PCBRANDS

*Platform

*PROCESSOR_A...

*PROCESSOR_id...

*PROCESSOR_LE...

*PROCESSOR_R...

*PSModulePath

*TEMP

*TERM

*TMP

*USERNAME

*Click the [New...] button.

*The New System Variable window opens.

*In the Variable Name field (which the cursor is currently blinking in...), enter JAVA_HOME.

*Then go to the Variable Value field and enter c:\Program Files (x86)\Java\jdk1.7.0_25\bin;%JAVA_HOME%/bin.(Without the period, of course!)

*Click the [OK] button and the New System Variable window closes.

*Now highlight the PATH option and click the [Edit...] button.

*The Edit System Variable window opens.

*Go to the Variable value field and add the following at the end of the string already there:
;c:\Users\Your username here\desktop\eclipse\eclipse\jre\bin;c:\Program Files
(x86)\Java\jre7\;c:\Program Files (x86)\Java \jdk1.7.0_25\bin

*Click the [OK] button and the Edit System Variable window closes.

*Click the [OK] button to close the Environment Variables window.

*Click the [OK] button to close the System Properties window.

*

*Now for the Pista Resistance!!!!!!! Go back to the Eclipse folder on your desktop (or alternative location), then click open. Now download Notepad ++ from http://notepad-plus-plus.com and install it.

*Use Notepad ++ to open the eclipse.ini file from the Eclipse folder. Using Notepad ++ keeps the eclipse.ini file's format correct.

*With the eclipse.ini file opened with Notepad ++, look for -- launcher.append Vmargs. Once you've found this entry, place the cursor after it and then press . You should now see a space.

*In that space enter the following: (and this must be entered exactly like what's listed below)
-vm
c:\Program Files (x86)\Java\jre7\bin\
c:\Program Files (x86)\Java\jdk1.7.0_25\bin

*Now click File then Save as, with the file name as Eclipse.ini, then click the [Save] button.

*A message box will display asking "Do you want to replace the file?", click the [Yes] button.

*Now click File then Exit and Notepad ++ closes.

*

*Now close then restart the Firefox browser.

*

*Now close then reopen the Eclipse folder. ( I know what you're thinking but just listen and nod and do it.)

*Click the Eclipse.exe file and now you should see the Eclipse splash screen.

*After a few seconds, a message displays asking you to select an Eclipse Workspace. You should have this Workspace on your desktop

or some where you can make this connection.

*

*Now Eclipse is working! Let me know if this process worked for you!


text:
Q: Can a synchronous buck converter be operated in reverse? Consider the following buck converter circuit:

When Q1 is on and Q2 is off, current flows through the inductor and into the capacitor and the load, and the energy stored in the inductor increases.  When the switches change states, the inductor and the capacitor use their stored energy to supply the load; Q2 is on and completes the current loop.
Now, if we connect the supply to the "output" side and the load to the "input" and reverse the order of the two steps, we see that the inductor charges up when Q2 is on, then discharges into the load when Q1 is on.  This is equivalent to a boost converter circuit.
My question is:  If we connect two devices (two batteries, a battery and a motor/generator, etc.) to each side of the converter, are we able to change the direction of current flow?

A: Yes, and boy, didn't it come as a surprise to me the first time I did it!  I saw what was happening, said "T'oh!", and had to spin the board.
If you put a capacitor across \$V_{in}\$ and look at the power flow from right to left, you'll see that you have a boost converter.
To a first order (i.e., ignoring components going up in puffs of smoke, possibly with sound effects), the inductor insures that the average voltage at \$v_{SW}\$ is equal to \$V_o\$.  The FETs -- if they're switched in the "typical" way where the top FET is on whenever the bottom FET is off, and visa versa -- insure that the average voltage at \$v_{SW}\$ is equal to the duty cycle times \$V_{in}\$.
This is a well-known effect when you're driving a motor -- the motor can back-drive the \$V_{in}\$ rail, and unless the supply behind it can absorb the power you need to have a mechanism for dumping the current into something safe, like a great big resistor (AKA "braking resistor", which, when you buy switching motor drives, you are often expected to supply yourself).

A: Yes, it's possible to pass energy in either direction, but with a caveat: the left-side voltage must be higher than the right side.
Have a look at this Q about boost converters: Difference between synchronous and conventional dc-dc boost converter?
Notice something? The synchronous boost looks a lot like a synchronous buck, turned the other way.
So the 'buck' with a voltage source on the 'output', back-feeding to the other side, the two phases will be:

*

*Q2 on: inductor flux increasing, switch node toward ground

*Q1 on: inductor flux collapsing, switch node above 'output', dumps to 'input'

Why does this work? The FETs can conduct in both directions, and it so happens Q1 is 'on' when the body diode is forward biased. Even if Q1 never turned on, you would still get conduction through the body diode.

A: Yes, this works and is normal.
Note that there are some things to be aware of.
If the controller is a current-mode one, it may not be able to handle negative current flow.
While the circuit is boosting the V applied on the right to the load on the left; the regulation is on the right-hand side -- it doesn't regulate the output - it regulates the input. This is probably not what you want, although it does have some uses (e.g. draw power from a solar panel and charge a battery).


text:
Q: Spring data neo4j method findAllByQuery from Repository cannot pass pagination parameters I'm trying to achieve fulltext query by using spring data neo4j repository method findAllByQuery, but i am not able to pass pagination parameters.
From [doc]: http://docs.spring.io/spring-data/neo4j/docs/current/reference/htmlsingle/#d0e2149
@NodeEntity
class Person {
    @Indexed(indexName = "people-search", type=FULLTEXT) String name;
}

GraphRepository<Person> graphRepository =
         template.repositoryFor(Person.class);

Person mark = graphRepository.findAllByQuery("people-search", "name", "ma*");


text:
Q: Empty page when creating data-url to download d3.js graph as svg I am trying to download a graph that I created with D3.js to a png (any other format would do though), very much unsuccessfully.
I am trying to create a data-url and then pass it to a function which should allow me to download it.
Like so:
First I want to create a function to create data-urls:
function svgDataURL(argument) {
         var svgAsXML = (new XMLSerializer).serializeToString(argument.node());
         return "data:image/svg+xml," + encodeURIComponent(svgAsXML);
       }

Next I am saving my url with my svg as argument in a varaiable:
var dataURL = svgDataURL(svg)
 console.log(dataURL)

when debugging this outputs the following: data:image/svg+xml,%3Cg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20transform%3D%22translate(100%2C20)%22%3E%3Crect%20class%3D%22bar%22%20width%3D%225.244670050761421%22%20y%3D%22394.44444444444446%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22526.3857868020305%22%20y%3D%22338.8888888888889%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22283.3333333333333%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22840%22%20y%3D%22227.77777777777777%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%225.116751269035533%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2256.96649746192893%22%20y%3D%22116.66666666666666%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2260.079187817258884%22%20y%3D%2261.1111111111111%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2229.932994923857866%22%20y%3D%225.555555555555543%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Cg%20transform%3D%22translate(0%2C450)%22%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22middle%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M0.5%2C6V0.5H840.5V6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0.5%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E0%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(85.77918781725889%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E2%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(171.05837563451777%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E4%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(256.33756345177665%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E6%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(341.61675126903555%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E8%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(426.8959390862944%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E10%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(512.1751269035533%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E12%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(597.4543147208122%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E14%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(682.7335025380711%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E16%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(768.0126903553299%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E18%2C000%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3Cg%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22end%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M-6%2C450.5H0.5V0.5H-6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C419.44444444444446)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding1%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C363.8888888888889)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding2%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C308.3333333333333)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding3%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C252.77777777777777)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3ETradeCenter%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C197.22222222222223)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding13%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C141.66666666666666)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding8%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C86.1111111111111)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding7%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C30.555555555555543)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding6%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fg%3E
I am assuming that this is the data link to my svg I want to create. But hey, it looks kinda long and wrong. So maybe I am already going the wrong way here.
finally I call my download function and pass my URL
 function download(){
      var dl = document.createElement("a");
      document.body.appendChild(dl);
      dl.setAttribute("href", dataURL);
      dl.setAttribute("download", "graph.svg");
      dl.click();
    }

Ok fail, it doesn't work. When I open the link or click on my download link I get an empty page.
Has anyone an idea where I go wrong? Any help is very much appreciated.
Here is my graph btw:

var data = build
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// set the ranges
var y = d3.scaleBand()
          .range([height, 0])
          .padding(0.1);

var x = d3.scaleLinear()
          .range([0, width]);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select(".svg-net-area").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

  // format the data
  data.forEach(function(d) {
    d.buildings__net_leased_area = +d.buildings__net_leased_area;
  });

  // Scale the range of the data in the domains
  x.domain([0, d3.max(data, function(d){ return d.buildings__net_leased_area; })])
  y.domain(data.map(function(d) { return d.buildings__name; }));
  //y.domain([0, d3.max(data, function(d) { return d.buildings__net_leased_area; })]);

  // append the rectangles for the bar chart
  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      //.attr("x", function(d) { return x(d.buildings__net_leased_area); })
      .attr("width", function(d) {return x(d.buildings__net_leased_area); } )
      .attr("y", function(d) { return y(d.buildings__name); })
      .attr("height", y.bandwidth())
      .attr("fill", "#348496");

  // add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // add the y Axis
  svg.append("g")
      .call(d3.axisLeft(y));


text:
Q: Why do I need to provide NG_VALUE_ACCESSOR at the component level? Take a look at this example:
https://stackblitz.com/edit/angular-nxjeu3
It does not work.
But if I move the providers from the @NgModule to HelloComponent, it does work. Why? Shouldn't providing at the @NgModule level or @Component level be the same?

A: Because the NG_VALUE_ACCESSOR is binding things to component's :host and linking to methods (ControlValueAccessor methods) there. Your module does not have any of those form methods (like writeValue, registerOnTouched etc). Your form element does. So providing at component level binds this for that specific element. Additionally, providing so deep down means each form control has it's own control value accessor and not a shared one.
Angular Form controls and its API is not the same as the DOM form controls. What angular does is binds to the inputs/outputs of the dom element and provides you with the results. Now, with your custom control, you must provide the same bindings there. By implementing ControlValueAccessor and providing NG_VALUE_ACCESSOR, you are telling Angular's Forms API how it can read and write values from/to your custom form control.
Take a look at the source.


text:
Q: How to configure Eclipse EGit to use custom proxy settings? I'm behind a corporate firewall, so most of the time (e.g. Eclipse updates) I want to be going through a proxy. However, the servers I pull from in Git are all internal. I currently have to change my proxy settings every time I switch, but I'd like to set it up so that EGit uses a direct connection.
My guess is that it's just not a feature EGit has, but can anyone think of a workaround maybe?
Thanks!

A: EGit should follow the General > Network configuration settings.
If you set that Network mode to "Manual", you can:

*

*set your proxy (with authentication)

*add sites you want in "no_proxy" (in order to not try to contact a proxy)

This seems also valid for ssh protocol, as illustrated by bug 349702.

A: For me the answer of VonC didn't work (Eclipse Neon.2). I had to enter my proxy at the Settings under:
Window -> Preferences
and then
General -> Network connections
Also note that some proxy servers block the git:// and ssh:// protocols. If you face issues, try to use the https:// or http:// protocol.


text:
Q: Provide data from a code class to the Reporting Services designer in VS 2013 I'm trying to create a local SQL Server Reporting Services report (.rdlc file) and connect this report to some data sets that I generate in code (no direct SQL Server connection).
I create a ReportDataProvider class with some instance methods that return IList<T> for various sets of criteria - but I cannot seem to find a way to make those data providing methods show up in the Reporting Services designer inside Visual Studio 2013.
When I look at the dialog that appears after clicking on Add DataSet on the Datasets node in the Report Data explorer window, I see a ton of my classes listed there - but not my data provider class.

Is there anything special I need to be aware of (make the class static? Decorate it with some attribute?) in order for it to show up in that dropdown list of possible data sources? I tried various things, but have failed to find any way to get this to work properly...

A: I do some research, and try different ways to add classes. Unfortunatly it happends that you can't see static classes in this designer. I tried different ways but no luck.
For non static classes this manual works for me every time, even with Interfaces like IList, but i don't represent it here:

*

*Make sure that namespace with your Data Report Classes available in your project with .rdlc files. Can be that you need to add reference.

*Write Data Report Class and rebuild solution.

*Close and reopen .rdlc files in your VS.

I using VS 2013 Ultimate Update 2.
This is my classes:
using System.Collections.Generic;

namespace YourReportNamespace
{
    public class ReportClass
    {
        public List<string> TestReportData()
        {
            return new List<string>();
        }
        public static List<string> StaticTestReportData()
        {
            return new List<string>();
        }
    }

    public class ReportWithFieldsClass
    {
        private List<string> Data = new List<string>();

        public List<string> TestReportData()
        {
            return Data;
        }

        public List<string> TestReportData2()
        {
            return Data;
        }

        public static List<string> StaticTestReportData()
        {
            return new List<string>();
        }
    }

    public static class ReportWithFieldsStaticClass //This class will not appear
    {
        private static List<string> Data = new List<string>();

        public static List<string> StaticTestReportDataFromField()
        {
            return Data;
        }
        public static List<string> StaticTestReportData()
        {
            return new List<string>();
        }
    }
}

This is what i got in designer after i pass through manual:

A: Had a similar problem.  Found if managed to get a build with no errors then my namespace would appear to select from in the data sources.

A: I had the same problem and discovered another case which might be easy to miss. In my case the class containing List returning methods had a single constructor with required parameters and it did not show up on DataSource dropdown. After I added a parameterless constructor to my class and rebuild, it is now visible!
This might have to do with how RDLC UI analyzes eligible methods, it probably tries to instantiate the class in the process.


text:
Q: Node.js - better error handling than process.on('uncaughtException', fn)? At the top of my app, I have this code:
process.on('uncaughtException', function(err) {
  console.log("We found an uncaught exception.");
  console.log(err);
});

And if I search my logs for grep -i -A10 -B3 'uncaught exception' logfile, I can get some decent info.  But I have no idea what execution context the exception got thrown in, what the error was, and so forth.
What pattern should I use instead?

A: The "err" argument of uncaughtException is an object and you can request some of its properties to get more information for that error.
As an example you can use its "stack" property to have a better understanding about where the error is coming from:
console.log(err.stack);

See: http://docs.nodejitsu.com/articles/errors/what-is-the-error-object


text:
Q: What is the time complexity of if-else statement inside a while loop? I want to calculate the time complexity of if-else statement inside a while loop but I am not sure how.

A: If you want to measure the elapsed time in the BEGIN END block;
[![DECLARE @Counter INT
DECLARE @TimeStart AS DATETIME
DECLARE @TimeStop AS DATETIME
SET @Counter=1
WHILE ( @Counter <= 10)
BEGIN
 PRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)
     IF @Counter %4 =0
     BEGIN
     SET @TimeStart=GETDATE()

     WAITFOR DELAY '00:00:001';
     END
   SET @TimeStop =GETDATE()
   PRINT 'The elapsed time is = ' + CAST(DATEDIFF(MICROSECOND,@TimeStart,@TimeStop) AS VARCHAR(1000)) + ' microsecond'
   SET @TimeStart= NULL
   SET @TimeStop= NULL

    SET @Counter  = @Counter  + 1
END


text:
Q: How to reframe the dataset based on Id ignoring the null and empty lists How can I reframe the dataset  based on column ID.
   id   time    A   B   C   D
A   11111   []  []  []  None
A   22222   [aaaa]  None    []  []
A   33333   []  []  [ccccc] sasasasasa
A   44444   None    None    []  ddfdfdf
A   55555   []  []  []  []
A   66666   []  [aaaa]  []  None
A   77777   [a1a1a1]    []  None    []
A   88888   None    []  []  None
A   99999   []  []  None    ssdskd
A   100000  []  []  []  sdsdsd
A   101111  None    [a1a1a1]    []  []
B   120000  [xxxx]  []  None    []
B   333333  []  None    []  []
B   130000      None    None    []
B   443430  []  []  [zzzz]  []
B   543434  none    [xxxx]  None    None

Based on the time column can we rearrange the dataset  as below
 ID data A  data B  A   B   c   D
A   22222   44444   aaaa    aaaa    ccccc   sasasasasa,ddfdfdf
A   55555   77777   a1a1a1  a1a1a1  nan ssdskd , sdsdsd
B   120000  130000  xxxx    xxxx    zzzz    nan

here column data A is the time when column A has appeared and data B is when time column B has appeared. Column C will always appear between A and B.
Code :
df1 = (df.set_index('id')
         .applymap(lambda x: np.nan if x == [] else x)
         .stack()
         .unstack()
         .apply(lambda x: x.str[0])
       )

A: First part solution is similar - created MultiIndex by both columns, replaced empty lists to missing values, reshaped by DataFrame.stack, removed ene element lists to scalars by indexing and convert time level of MultiIndex to column:
df1 = (df.set_index(['id','time'])
         .applymap(lambda x: np.nan if x == [] else x)
         .stack()
         .str[0]
         .reset_index(level=1, name='new')
       )
print (df1)
        time     new
id
A  A   22222    aaaa
   C   33333   ccccc
   B   44444    aaaa
   A   55555  a1a1a1
   B   77777  a1a1a1
B  A  120000    xxxx
   C  333333    zzzz
   B  130000    xxxx

Then reshape by DataFrame.unstack, only is necessary deduplicate MultiIndex by new level with GroupBy.cumcount and then flatten columns with join for no MultiIndex in columns:
df1 = (df1.set_index(df1.groupby(level=[0,1]).cumcount(), append=True)
          .unstack(1)
          .reset_index(level=1, drop=True)
          .rename(columns={'time':'data'}, level=0))
df1.columns = df1.columns.map('_'.join)
df1 = df1.reset_index()
print (df1)
  id    data_A    data_B    data_C   new_A   new_B  new_C
0  A   22222.0   44444.0   33333.0    aaaa    aaaa  ccccc
1  A   55555.0   77777.0       NaN  a1a1a1  a1a1a1    NaN
2  B  120000.0  130000.0  333333.0    xxxx    xxxx   zzzz

EDIT: Solution is modify with aggregation first and join if duplicated consecutive values, here in column D, but it seems somt typo in data, because data columns created from time column not match:
df1 = (df.set_index(['id','time'])
         .applymap(lambda x: np.nan if x == [] else x)
         .stack()
         .astype(str)
         .str.strip("[']")
         .reset_index(name='new')
         .rename(columns={'level_2':'cols'})
       )
df1['g'] = df1['cols'].ne(df1.groupby('id')['cols'].shift()).cumsum()
df1 = (df1.groupby(['id','cols', 'g'])
          .agg({'time':'first', 'new': ', '.join})
          .reset_index(level=2, drop=True))
print (df1)
           time                  new
id cols
A  A      22222                 aaaa
   A      77777               a1a1a1
   B      66666                 aaaa
   B     101111               a1a1a1
   C      33333                ccccc
   D      33333  sasasasasa, ddfdfdf
   D      99999       ssdskd, sdsdsd
B  A     120000                 xxxx
   B     543434                 xxxx
   C     443430                 zzzz

df1 = (df1.set_index(df1.groupby(level=[0,1]).cumcount(), append=True)
          .unstack(1)
          .reset_index(level=1, drop=True)
          .rename(columns={'time':'data'}, level=0))
df1.columns = df1.columns.map('_'.join)
df1 = df1.reset_index()
print (df1)
  id    data_A    data_B    data_C   data_D   new_A   new_B  new_C  \
0  A   22222.0   66666.0   33333.0  33333.0    aaaa    aaaa  ccccc
1  A   77777.0  101111.0       NaN  99999.0  a1a1a1  a1a1a1    NaN
2  B  120000.0  543434.0  443430.0      NaN    xxxx    xxxx   zzzz

                 new_D
0  sasasasasa, ddfdfdf
1       ssdskd, sdsdsd
2                  NaN


text:
Q: How to plot a confidence interval in R So I need to graph a confidence interval for a prediction I ran.  I can run the prediction, but when I go to graph the prediction I get a line through all of my data points as opposed to getting the actual confidence interval.
GunRate <- seq(0,100, length = 51)

LinearPredictionA <- predict(ModelA,
    interval = "confidence",
    newdata = data.frame(ProportionAdultsLivingWithGun = GunRate,
                         LogMedianIncome = FinalSet$LogMedianIncome,
                         PctofPeopleinMetro = FinalSet$PctofPeopleinMetro,
                         PovertyRate = FinalSet$PovertyRate))

##This is my prediction model

plot(x = FinalSet$ProportionAdultsLivingWithGun,
     y = FinalSet$ViolentCrime1K,
     col = "red",
     xlim = c(0, 80), ylim = c(0, 15),
     xlab ="Proportion of Adults Living With a Gun",
     ylab = "Violent Crime Rate per 1000",
     main = "Violent Crime vs. Gun Ownership",
     sub = "All 50 States & D.C.")

## This plot shows the actual data we used to obtain the prediction

lines(GunRate, LinearPredictionA[, "fit"], type = "l")
lines(GunRate, LinearPredictionA[, "lwr"], lty = "dashed", col = "green")
lines(GunRate, LinearPredictionA[, "upr"], lty = "dashed", col = "green")

These line functions are supposed to graph my CI, but instead I get the following graph

A: Here's an example of what's going wrong, using the built-in mtcars data frame:
# Regression model
m1 = lm(mpg ~ wt + hp + cyl, data=mtcars)

Now let's get predictions of mpg vs. wt, but with 2 different alternating values of hp and 3 different alternating values of cyl:
predData = data.frame(wt=seq(1,5,length=60), hp=rep(c(200,300), 30), cyl=rep(c(4,6,8), 20))
predData = cbind(predData, predict(m1, newdata=predData, interval="confidence"))

Note how the prediction jumps around, because hp and cyl change for each successive value of wt:
plot(predData$wt, predData$fit, type="l")
lines(predData$wt, predData$lwr, type="l", col="red")
lines(predData$wt, predData$upr, type="l", col="red")

But when we keep hp and cyl fixed, we get a straight line prediction for mpg vs. wt:
predData2 = data.frame(wt=seq(1,5,length=60), hp=rep(300,60), cyl=rep(6, 60))
predData2 = cbind(predData2, predict(m1, newdata=predData2, interval="confidence"))

plot(predData2$wt, predData2$fit, type="l")
lines(predData2$wt, predData2$lwr, type="l", col="red")
lines(predData2$wt, predData2$upr, type="l", col="red")

Instead of a single line, you can also plot predicted mpg vs. wt lines for several values of another variable. Below is an example where we plot a line for each value of cyl that we used to create predData. This is easier with ggplot2 so I've used that package. Using lines for the confidence intervals would make the plot difficult to understand, so I've shown the CI with a fill instead:
library(ggplot2)

ggplot(subset(predData, hp==200), aes(wt, fit, fill=factor(cyl), colour=factor(cyl))) +
  geom_ribbon(aes(ymin=lwr, max=upr), alpha=0.2, colour=NA) +
  geom_line() +
  labs(x="Weight", y="Predicted MPG", colour="Cylinders", fill="Cylinders") +
  theme_bw()


text:
Q: Java HeapSize Usage Estimation AWT Buffer Image
I can calculate that how much heap memory This Image Object will aquire ,
Like
BUfferedImage(W,H,TYPE)

then

Total memory used by it = W * H * 4

is there any way that i can estimate memory Usage
For Excel Spread Sheet and a Simple XML file that how much memory they will need if they are of specific size and/or contains specifics rows/nodes ?
Thanks

A: You can monitor your application when opening a file and get sensate  estimation for future configuration: see for example hpjmeter: https://h20392.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=HPJMETER

A: This is not an easy problem. To start with, you need to know exactly what you want to measure. For a BufferedImage, you need to specify which TYPE because the number of bytes needed per pixel depends on it.
For excel spread sheets and XML files, you need to specify which library you want to use.
Event then, the only way to know is by measuring. You can take several measurements and extrapolate - this is not guaranteed to be exactly correct but will yield useful estimates.
These posts show how you can do that:

*

*Size of the specific object's subtree in the JVM memory

*In Java, what is the best way to determine the size of an object?
The last post, "In Java, what is the best way to determine the size of an object?", only measures the size of the object itself, not the object graph that it creates.
This external link titled Again about determining size of Java object has an extension of the solution in the last post, which estimates the size of an object graph. It's too long to reproduce here (and it's not my code to copy) but the link has existed since 2007 so I believe it's quite stable.


text:
Q: Downloading multiple files with Qt I want to download a batch of about 50 single images, process and save them. What is the best way to handle a lot of downloads?
I know how to use QHttp to download a single file, but I don't know how to work with a list of files.

A: QHttp is obsolete, use QNetworkAccessManager. Each GET, PUT, etc. returns a QNetworkReply object you can use to wait for the results of the respective request. If that is not enough, you could write a small QObject-derived helper class that monitors the reply object for error(), finished() and readyRead() signals and handles the received data, e.g. by writing it to a file.


text:
Q: Java: setRequestMethod not works I have the next part of code:
dCon = (HttpURLConnection) new URL(torrentFileDownloadLink).openConnection();
dCon.setRequestProperty("Cookie", "uid=" + cookies.get("uid") + ";pass=" + cookies.get("pass"));
dCon.setRequestMethod("GET");
dCon.setConnectTimeout(30000);
dCon.setDoOutput(true);

But Wireshark shows that request method is "POST". What am I doing wrong or this is just a bug? Btw, getRequestMethod say that method is "GET" but in reality it's POST.

A: Setting the URLConnection#setDoOutput() to true means that you're about to write request data to the request body by URLConnection#getOutputStream(). This is impossible in combination with GET (which expects the request parameters in the request URL), thus the request method will implicitly be set to POST.
If you don't need to write any data to the request body, then just remove that line. It defaults to false (and thus GET) anyway.
See also:

*

*How to use URLConnection to fire and handle HTTP requests?


text:
Q: jquery mouse over link that will highlight image position With this script, when i mouse over the link it will highlight the image coordinate that i specify in the <area>:

This is just a simple exampleof how the maps look.

<area id="squidhead" href="#" shape="circle" coords="50,71,10" alt="Octoface" data-maphilight='{"stroke":false,"fillColor":"ff0000","fillOpacity":0.6}' title="Metadata'd up a bit">

Now my problem now is that when i need to add multiple link that script would be too long to my liking and i believe there you should be a way to simplify it.What currently i am doing is to add this for each new link that point new position.
  $('.squidheadlink2').mouseover(function(e) {
            $('#squidhead2').mouseover();
        }).mouseout(function(e) {
            $('#squidhead2').mouseout();
        }).click(function(e) { e.preventDefault(); });
    });

the function is same so how can i make it so that for different (link1),(link2) that share same image (position 1) and (link3),(link4) that share same image (position 2) can be set by class or id without adding new script for each new link and image position?

A: You need to give all of your links a common class name or something then write a function that will iterate over them and use $(this) on each one to get and assign things. Let me know if you need code.
The easiest way is to use custom attributes on the links like this..
link
link
link

Then...
 $('[pairwith]').mouseover(function(e) {
            $('#'+ $(this).attr('pairwith')).mouseover();
        }).mouseout(function(e) {
            $('#'+ $(this).attr('pairwith')).mouseout();
        }).click(function(e) { e.preventDefault(); });
    });

You are using a custom attribute to pair with the other items. Problem Solved.


text:
Q: How to I review an application to choose the right indexes - php & mysql We have an existing PHP/MySQL app which doesn't have indexes configured correctly (monitoring shows that we do 85% table scans, ouch!)
What is a good process to follow to identify where we should be putting our indexes?
We're using PHP (Kohana using ORM for the DB access), and MySQL.

A: The answer likely depends on many things. For example, your strategy might be different if you want to optimize SELECTs at all costs or whether INSERTs are important to you as well. You might do well to read a MySQL Performance Tuning book or web site. There are several decent-to-great ones.
If you have a Slow Query Log, check it to see if there are particular queries that are causing problems.  http://dev.mysql.com/doc/refman/5.5/en/slow-query-log.html
If you know the types of queries you'll be running or have identified problematic queries via the Slow Query Log or other mechanisms, you can then use the EXPLAIN command to get some stats on those queries. http://dev.mysql.com/doc/refman/5.5/en/explain.html
Once you have the output from EXPLAIN, you can use it to optimize.  See http://dev.mysql.com/doc/refman/5.5/en/using-explain.html

A: Indexes are not just for the primary keys or the unique keys. If there are any columns in your table that you will search by, you should almost always index them.
I think this will help you on your database problems.
http://net.tutsplus.com/tutorials/other/top-20-mysql-best-practices/


text:
Q: Xamarin forms convert image uri address to real image I am trying to solve uri address converting to image issue. Main idea , what I am doing I want to pick image from a gallery, bind it and save it to database. Everything is working, I can save string image path to class property, but unfortunately I can't convert that address to my imageSource where I will displaying my image, because now I see empty image circle.
This is where I am selecting image from gallery and trying to convert into image:
IGalleryImageService galleryService = Xamarin.Forms.DependencyService.Get<IGalleryImageService>();
            galleryService.ImageSelected += (o, imageSourceEventArgs) =>
            {
                Uri uri = new Uri(imageSourceEventArgs.ImageSource);
                (ActivePage.Page as PageTemplate).CarImage.Source = ImageSource.FromFile(uri.ToString());
                ActivePage.CarImageBindable = (ActivePage.Page as PageTemplate).CarImage.Source.GetValue(StreamImageSource.StreamProperty).ToString(); // here I am trying to convert from path address to image
            };
            galleryService.SelectImage();

Here is my PageTemplate
    public partial class PageTemplate: ContentPage
    {
public CircleImage CarImage
        {
            get
            {
                return Car;
            }
            set
            {
                Car = value;
            }
        }
}

and PageTemplate.xaml where I am displaying images.
<controls:CircleImage x:Name="Car" AbsoluteLayout.LayoutBounds=".5,0,-1,-1" AbsoluteLayout.LayoutFlags="PositionProportional" Aspect="AspectFill">
</controls:CircleImage>

This is my bindable property from Unit2 class:
public string CarImageBindable
        {
            get
            {
                return base.CarImage;
            }
            set
            {
                base.CarImage = value;
                OnPropertyChanged(nameof(CarImageBindable));
            }
        }

And another property from Core project Unit class:
public int Id { get; set; }
public DateTime StartDate { get; set; }
public string CarImage { get; set; }

That's why I decided to make all properties as string data type, because I want to save image path. And yes, then convert again from database to physical image.
Thank you for answers or suggestions.

A: Well, I solved issue like this:
IGalleryImageService galleryService = Xamarin.Forms.DependencyService.Get<IGalleryImageService>();
            galleryService.ImageSelected += (o, imageSourceEventArgs) =>
            {
                ActiveParking.CarImageBindable = imageSourceEventArgs.ImageSource.ToString();
                (ActiveParking.Page as PageTemplate).CarImage.Source = galleryService.GetImage(imageSourceEventArgs.ImageSource.ToString());

            };
            galleryService.SelectImage();


text:
Q: Display logout menu after login from another component? I want to enable display the logout button after login from detailed-page.component.ts. The Join Us/Logout menu is in header compoent.
This is i have tried. But after login not enable the logout menu. How to fix this issue?.
header.component.html

Join Us

Logout

detailed-page.component.ts
constructor(

    private headerComponent: HeaderComponent

) {}

login() {

    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.lpassword)
        .subscribe(
                data => {
                this.headerComponent.loginStatus= 1;
                })
}

app.component.ts
    @Component({
      selector: 'my-app',
      template: `
        <app-header></app-header>
        <router-outlet></router-outlet>
        <app-footer></app-footer>`,
      styleUrls: ['../app/app.component.css'],
    })

    export class AppComponent {

    }

A: Assuming that you won't be needing to do much state management you could use a very simple service like this.  Basically this StoreService would contain all data that needs to be shared across all components:
export class StoreService {
  public loginStatus = 0; // 0 = not logged in, 1 = logged in

  setLoginStatus(status: number) {
    this.loginStatus = status;
  }
}

This would then get injected into your head and detailed component like so:
@Component({
  selector: 'app-detailed',
  template: `
 <button *ngIf="store.loginStatus === 0" (click)="login()">Login</button>
`,
})
export class DetailedComponent {
  constructor(public store: StoreService) {
  }

  login() {
    this.store.setLoginStatus(1);
  }
}

@Component({
  selector: 'app-header',
  template: `

Join Us

Logout

`,
})
export class HeaderComponent {
  constructor(public store: StoreService) {
  }

  showmodel() {
  }

  logout() {
    this.store.setLoginStatus(0);
  }
}

Here's a working plunker:
https://plnkr.co/edit/xBnWAP7EacoIc5j3USQv?p=preview
Note that the StoreService doesn't scale for applications that need to a lot of modifications to the shared state.  For a more scalable solution look into using ngrx.


text:
Q: facebook user_id returning 0 always Please someone help me. I trying this  almost 1 month ...  i want to retrieve the message and data. Im using the latest FB API, I tried my best I couldn't find whats wrong on it.Also I cant retreive user_id  .. Do I need do anything on call back function?
App url : https://apps.facebook.com/greetingz/
this is my whole code
 <?php
    session_start();
    if(!empty($_REQUEST['request_ids'])) {
    require_once('src/facebook.php');

    $config = array();
    $config["appId"] = "XXXXXXXX";
    $config["secret"] = "XXXXXXXXXXXX";
    $config["fileUpload"] = false; // optional

    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => $config["appId"],
      'secret' => $config["secret"],
      'cookie' => true,
    ));

        $user_id= $facebook->getUser();

    if($user_id){
      try {

            $app_token = $facebook->getAccessToken();

            $requests = explode(',',$_REQUEST['request_ids']);
            foreach($requests as $request_id) {

            $data = $facebook -> api('/'.$user_id.'/apprequests?'.$app_token);

            //you will delete the request here
            $delete_url = "https://graph.facebook.com/".$request_id."_".$user_id."?".$app_token."&method=delete";
            $result = file_get_contents($delete_url);
        }

      } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
      }
    }else{
    ?>

    <?php
    };
    }

    else{

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <title>Greetings</title>

      <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="664" height="626">
        <param name="movie" value="flash/Candle_jey.swf" />
        <param name="quality" value="high" />
        <param name="wmode" value="opaque" />
        <param name="swfversion" value="6.0.65.0" />

        <param name="expressinstall" value="Scripts/expressInstall.swf" />

        <object type="application/x-shockwave-flash" data="flash/Candle_jey.swf" width="664" height="626">

          <param name="quality" value="high" />
          <param name="wmode" value="opaque" />
          <param name="swfversion" value="6.0.65.0" />
          <param name="expressinstall" value="Scripts/expressInstall.swf" />

Content on this page requires a newer version of Adobe Flash Player.

        </object>

      </object>

            Greeting :

            <textarea type="text" name="message" id="msg" style="height:40px; width:350px;" ></textarea>

            <input type="submit" value="Send" id="one" style="color:#CCC; background-color:#603; border:none; width:80px; height:40px;"
            onclick="sendRequestViaMultiFriendSelector(); return false;">

    <?php }?>

A: Buddy read this in detail, it will solve your problem, you need to parse signed_request, in signed_request you get the user_id, you can get signed request like this authResponse.signed_request
Alternatively you can use below Facebook graph api method in place of this line "$user_id= $facebook->getUser();" in your code.
FB.login(function(loginResponse) {
    if (loginResponse.authResponse) {
        var userId = loginResponse.authResponse.userID;

        // Work with userId here
        var signed_request = loginResponse.authResponse.signedRequest;
        //Work with signed request here
    }
    else {
        //User cancelled login or did not fully authorize
    }
});


text:
Q: Should I limit the number of Executors I have? I have a Java project where I need to run things in parallel. I do this with executors. The thing is, I need to use executors in a great many places. Should I favor passing a few executors around to do the work (forget about limiting the global number of threads for a moment) or is it preferable to create the executors where I need them?

A: What you really need to think about is controlling the number of Threads working off any Executors you create.
The number of threads you create off each executor will be a function of the frequency of arrival and expected duration (processing time) of each task being submitted. Having a queue per logical task type allows you to tune the executor for just that task, so that you don't have more threads than required, and you can always keep up with the expected task throughput.
If you have one monolithic Executor shared across all processing stages in your app it becomes much harder to tune.
SEDA is a typical concurrency pattern that reflects this principle of queue per processing stage.
In some instances it does make sense to have a shared executor, such as for infrequent, ad-hoc or low priority scheduled tasks.

A: There's no strict rule that will tell you how many executors should be used. One thing, though can be recommended. Use some dependency injection mechanism or framework to inject executor implementations. This will allow quick and easy replacement and configuration of used executors.


text:
Q: Setting the width of a Silverlight application based on screen size On a silverlight 4.0 application I need to set the width of the main window to be the maximum possible width based on the size of the screen of user.
How can this be achieved?


text:
Q: How to use array in PHP language I have this code but when I run it it give me error ( Notice: Undefined offset: 1 in C:\wamp\www\test3.php on line $str[$row['term_no']] += ",".$row['code']; )
How can I solve this problem?
<?php

$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, "uoh");
$q = " SELECT * FROM `degree_plan` LEFT JOIN courses ON
    degree_plan.course_number=courses.course_number
    where major='COE'";

$result = mysqli_query($con, $q);
if ($result) {

    $str = [];
    while ($row = mysqli_fetch_array($result)) {
        {
            $str[$row['term_no']] += "," . $row['code'];
        }
        foreach ($str as $key => $value) {

            echo $value;
            echo $key;
        }

    }
}

?>

A: In your code, you are puting all codes in one element which is never defined.
change this:
$str[$row['term_no']] += ",".$row['code'];

to this:
$str[$row['term_no']] = $row['code'];

A: The error happens because the array element doesn't exist, so, first check the element : if it exist, add, if it doesn't, create:
while($row = mysqli_fetch_array($result))
{
   if ( isset( $str[$row['term_no']] ) ) // IF ELEMENT EXISTS...
        $str[$row['term_no']] .= ",".$row['code']; // ADD TO ELEMENT.
   else $str[$row['term_no']] =  $row['code'];  // CREATE ELEMENT.
}


text:
Q: Runing multiple instances with the same, single ip address Using Amazon VPC, what is the best possible way to attach multiple instances to a single ip address?
My company needs the ability to open/shutdown instances upon request and traffic. All instances created must have the same ip address attached, as the service I try to connect to allows only certain IPs that I can define every once in a while.

A: You want to use Elastic Load Balancer (ELB). It was built specifically for the purpose of balancing a large number of requests to the same IP across several EC2 instances.
http://aws.amazon.com/elasticloadbalancing/

A: If you want to whitelist the IPs of your instances to some other third party service, then you would have to use elastic IPs in that case. You can not associate one IP to more than one instance.
However, if you want only one endpoint for your service, you can very well use load balancer as also suggested above.