text:
Q: how to speed up Python nested loops for million elements I try to pair two objects (one data set contains about 0.5 million elements, another one contains about 2 million elements) which meet certain conditions, then save information of the two objects to a file. Many variables are not involved in the pairing calculation, but they are important for my following analysis, therefore I need to keep track of those variables and save them. If there is way to vectorize the whole analysis, it will be much faster. In the following I take the random number as an example:
import numpy as np
from astropy import units as u
from astropy.coordinates import SkyCoord
from PyAstronomy import pyasl

RA1 = np.random.uniform(0,360,500000)
DEC1 = np.random.uniform(-90,90,500000)
d = np.random.uniform(55,2000,500000)
z = np.random.uniform(0.05,0.2,500000)
e = np.random.uniform(0.05,1.0,500000)
s = np.random.uniform(0.05,5.0,500000)
RA2 = np.random.uniform(0,360,2000000)
DEC2 = np.random.uniform(-90,90,2000000)
n = np.random.randint(10,10000,2000000)
m = np.random.randint(10,10000,2000000)

f = open('results.txt','a')
for i in range(len(RA1)):
    if i % 50000 == 0:
        print i
    ra1 = RA1[i]
    dec1 = DEC1[i]
    c1 = SkyCoord(ra=ra1*u.degree, dec=dec1*u.degree)
    for j in range(len(RA2)):
        ra2 = RA2[j]
        dec2 = DEC2[j]
        c2 = SkyCoord(ra=ra2*u.degree, dec=dec2*u.degree)

        ang = c1.separation(c2)
        sep = d[i] * ang.radian
        pa = pyasl.positionAngle(ra1, dec1, ra2, dec2)

        if sep < 1.5:
            np.savetxt(f,np.c_[ra1,dec1,sep,z[i],e[i],s[i],n[j],m[j]], fmt = '%1.4f   %1.4f   %1.4f   %1.4f   %1.4f   %1.4f   %i   %i')

A: Here is an implementation using a buffer in memory to reduce I/O. Note: I prefer using io module for file input/output in order to be more compatible with Python 3. I think it is a best practice. You won't have lower performance with it.
import io

with io.open('results.txt', 'a') as f:
    buf = io.BytesIO()
    for i in xrange(len(RA1)):
        if i % 50000 == 0:
            print(i)
            f.write(buf.getvalue())
            buf.truncate(0)
        ra1 = RA1[i]
        dec1 = DEC1[i]
        c1 = SkyCoord(ra=ra1 * u.degree, dec=dec1 * u.degree)
        for j in xrange(len(RA2)):
            ra2 = RA2[j]
            dec2 = DEC2[j]
            c2 = SkyCoord(ra=ra2 * u.degree, dec=dec2 * u.degree)

            ang = c1.separation(c2)
            sep = d[i] * ang.radian
            pa = pyasl.positionAngle(ra1, dec1, ra2, dec2)

            if sep < 1.5:
                np.savetxt(buf, np.c_[ra1, dec1, sep, z[i], e[i], s[i], n[j], m[j]],
                           fmt='%1.4f   %1.4f   %1.4f   %1.4f   %1.4f   %1.4f   %i   %i')
    f.write(buf.getvalue())

Note: In Python 2, I use xrange instead of range to reduce memory usage.
The buf.truncate(0) could be replaced by a new instance like this: buf = io.BytesIO(). It could be more efficient…

A: First way to speedup: c2 = SkyCoord calculated for every pair in ra2, dec2 len(RA1) times. You can speedup by making a buffer array of SkyCoord:
f = open('results.txt','a')
C1 = [SkyCoord(ra=ra1*u.degree, dec=DEC1[i]*u.degree)
      for i, ra1 in enumerate(RA1)] )
C2 = [SkyCoord(ra=ra2*u.degree, dec=DEC2[i]*u.degree)
      for i, ra2 in enumerate(RA2)] )  # buffer coords

for i, c1 in enumerate(C1):  # we only need enumerate() to get i
    for j, c2 in enumerate(C2):
        ang = c1.separation(c2)  # note we don't have to calculate c2
        if d[i] < 1.5 / ang.radian:
            # now we don't have to multiply every iteration.
            # The right part is a constant

            # the next line is only executed if objects are close enough
            pa = pyasl.positionAngle(RA1[i], DEC1[i], RA2[j], DEC2[j])
            np.savetxt('...whatever')

You can speedup even more by reading SkyCoord.separation code and vectorizing it to replace SkyCoord, but I'm too lazy to do it myself. I assume if we had two 2xN coord matrices x1, x2 it will look similar to (Matlab/Octave):
cos = pdist2(x1, x2) / (sqrt(dot(x1, x1)) * sqrt(dot(x2, x2)))

A: The basic question you need to ask yourself is: Can you reduce the dataset?
If not I have some bad news: 500000 * 2000000 is 1e12. That means you're trying to do one trillion operations.
The angular seperation involves some trigonometric functions (I think cos, sin and sqrt are involved here) so it will be roughly in the order of hundreds of nanoseconds up to microseconds per operation. Assuming each operation takes 1us you'll still need 12 days to complete this. And this assumes you don't have any Python loop or IO overhead and I think 1us is reasonable for these kind of operations.
But there are certainly ways to optimize it: SkyCoord allows to vectorize but only 1D:
# Create the SkyCoord for the longer array once
c2 = SkyCoord(ra=RA2*u.degree, dec=DEC2*u.degree)
# and calculate the seperation from each coordinate of the shorter list
for idx, (ra, dec) in enumerate(zip(RA1, DEC1)):
    c1 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
    # x will be the angular seperation with a length of your RA2 and DEC2 arrays
    x = c1.separation(c2)

This will already yield a speedup of several orders of magnitude:
# note that I made these MUCH shorter
RA1 = np.random.uniform(0,360,5)
DEC1 = np.random.uniform(-90,90,5)
RA2 = np.random.uniform(0,360,10)
DEC2 = np.random.uniform(-90,90,10)

def test(RA1, DEC1, RA2, DEC2):
    """Version with vectorized inner loop."""
    c2 = SkyCoord(ra=RA2*u.degree, dec=DEC2*u.degree)
    for idx, (ra, dec) in enumerate(zip(RA1, DEC1)):
        c1 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
        x = c1.separation(c2)

def test2(RA1, DEC1, RA2, DEC2):
    """Double loop."""
    for ra, dec in zip(RA1, DEC1):
        c1 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
        for ra, dec in zip(RA2, DEC2):
            c2 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
            x = c1.separation(c2)

%timeit test(RA1, DEC1, RA2, DEC2)  # 1 loop, best of 3: 225 ms per loop
%timeit test2(RA1, DEC1, RA2, DEC2) # 1 loop, best of 3: 2.71 s per loop

This is already 10 times as fast and it scales MUCH better:
RA1 = np.random.uniform(0,360,5)
DEC1 = np.random.uniform(-90,90,5)
RA2 = np.random.uniform(0,360,2000000)
DEC2 = np.random.uniform(-90,90,2000000)

%timeit test(RA1, DEC1, RA2, DEC2)  # 1 loop, best of 3: 2.8 s per loop

# test2 scales so bad I only use 50 elements here
RA2 = np.random.uniform(0,360,50)
DEC2 = np.random.uniform(-90,90,50)
%timeit test2(RA1, DEC1, RA2, DEC2)  # 1 loop, best of 3: 11.4 s per loop

Note that by vectorizing the inner loop I was able to calculate 40000 times more elements in 1/4 of the time. So by vectorizing the inner loop you should be roughly 200k times faster.
Here we calculated 5 times 2 million seperations in 3 seconds, so it will be roughly 300 ns per operation. At this speed you'd need 3 days to complete this task.
Even if you could also vectorize the remaining loop away I don't think that would yield any great speedups because at that level the loop overhead is much less than the computation time in each loop. Using line-profiler supports this statement:
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    11                                           def test(RA1, DEC1, RA2, DEC2):
    12         1       216723 216723.0      2.6      c2 = SkyCoord(ra=RA2*u.degree, dec=DEC2*u.degree)
    13         6          222     37.0      0.0      for idx, (ra, dec) in enumerate(zip(RA1, DEC1)):
    14         5       206796  41359.2      2.5          c1 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
    15         5      7847321 1569464.2     94.9          x = c1.separation(c2)

If it's not obvious from the Hits that's from the 5 x 2,000,000 run and for comparison here is the one from a 5x20 run on test2:
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    17                                           def test2(RA1, DEC1, RA2, DEC2):
    18         6           80     13.3      0.0      for ra, dec in zip(RA1, DEC1):
    19         5       195030  39006.0      0.6          c1 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
    20       105         1737     16.5      0.0          for ra, dec in zip(RA2, DEC2):
    21       100      3871427  38714.3     11.8              c2 = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
    22       100     28870724 288707.2     87.6              x = c1.separation(c2)

The reason why test2 scales worse is that the c2 = SkyCoord part takes 12% of the total time instead of just 2.5% and that each single call to seperation has some significant overhead. So it's not really the Python loop overhead that makes it slow but the SkyCoord constructor and the static parts of seperation.
You obviously need to vectorize the pa calculation and the saving to file (I haven't worked with PyAstronomy and numpy.savetext so I can't advise there).
But there is still the problem that it's simply not feasible to do one trillion trigonometric operations on a normal computer.
Some additional ideas how to reduce the time:

*

*Use multiprocessing so each core of your computer works in parallel, in theory this could speed this up by the amount of your cores. In practice this won't be be reachable and I would recommend doing this only if you have more than >= 8 cores or a cluster avaiable. Otherwise the time spent on getting multiprocessing to work correctly might exceed the single-core running time. Especially because multiprocessing might not work correctly and then you have to rerun the calculation.

*Preprocess the elements: Remove items where the RA or DEC difference alone makes it impossible to find matches. However if this cannot remove a significant fraction of the elements the additional subtractions and comparisons might actually slow this down.

A: Assuming you want to reduce your dataset to <2 degree differences (as per your comment), you can make a mask by broadcasting (may need to do in chunks, but method is same)
aMask=(abs(RA1[:,None]-RA2[None,:])<2)&(abs(DEC1[:,None]-DEC2[None,:])<2)

In some smaller scale testing, this reduces the dataset by about 1/5000.  Then make a location array of the mask.
locs=np.where(aMask)

(array([   0,    2,    4, ..., 4998, 4999, 4999], dtype=int32),
 array([3575, 1523, 1698, ..., 4869, 1801, 2792], dtype=int32))

(from my 5k x 5k test).  Dump all your other variables through, for example, d[locs[0]] to create 1d arrays that you can push through SkyCoord as per @MSeifert's answer.
When you get your outputs and compare to 1.5, you'll get a boolean bmask that you can then outlocs=locs[0][bmask] and output RA1[outlocs] etc.
I've done similar things trying to do spatial derivatives on shells for FEM analysis, where taking the full rank of comparison between all the datapoints is similarly inefficient.

A: savetxt used this way is essentially
astr = fmt % (ra1,dec1,sep,z[i],e[i],s[i],n[j],m[j])
astr += '\n'  # or include in fmt
f.write(astr)

that is, just writing a formatted line to the file


text:
Q: Two wordpress sites using diiferent themes on the same database I want to run 2 wordpress sites, one.site.com and two.site.com from the same database. Everything remains the same except for the theme.

*

*one.site.com - Existing site

*two.site.com - Should use one.site.com's database except for the
theme

Is there any way this can be done ?
Since theme details are stored in wp_options table is it possible for two.site.com to use it to display a different theme ? Say duplicating that table and making two.site.com use it ?
I appreciate any help.
EDIT:
Both the sites do not have any plugins.

A: You can run two sites from a single database but not from the same set of database tables as the stored data includes the site's domain name.
There are two values in the options table: siteurl and home which are used. Using the same options table won't work, even if you update options forcefully for each php run.
So you would need to use two databases.
EDIT:
My advice is to replicate base and run both sites on different databases.

A: The solution below did the job for me,
Install 2 WordPress sites on a single database.
Create new table in your database. Call it wp_options2 and copy everything from wp_options into this new table
In second install go to wp-config.php, and before if (!defined('ABSPATH')) add define( 'M7_OPTIONS_TABLE', 'wp_options2');
In second install go to wp-includes/wp-db.php on line 1009 and add code:
if (isset( $tables['options'] ) && defined('M7_OPTIONS_TABLE')) $tables['options'] = M7_OPTIONS_TABLE;

These codes should be added in public function tables function, before if (isset( $tables['users']) && defined('CUSTOM_USER_TABLE')))
I found this solution here, https://wordpress.stackexchange.com/questions/84313/how-to-run-two-wordpress-blogs-with-different-themes-and-with-single-database-an#answer-175494
Since we use the same database, links will be same on both the sites. I had a lot of images linked and I removed them using
.single a[href$=".jpg"] {
    pointer-events: none;
    cursor: default;
}

A: This could probably be accomplished by using wildcard subdomains (https://codex.wordpress.org/Configuring_Wildcard_Subdomains).
It may be a little hacky, but you'd have to test the condition of your subdomain (maybe in wp-config.php?) and set the theme in the database (http://www.inmotionhosting.com/support/edu/wordpress/change-theme-in-db).
The only problem I could see with this is that your functions.php can change WP functionality, so a Parent theme with two Child Themes is probably a good idea(https://codex.wordpress.org/Child_Themes).

A: There is a lot of jiggery hackery regarding this question, but I think there's a fairly simple solution. First, ensure that both of your 2 sites have these hardcoded in wp-config.php:
define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');

These will help each site "override" whatever the database setting is for the URLs.
Next, decide which site is the MASTER site where you are going to be publishing new blog posts, making edits to site data, and such. On that site, activate the theme you want to use.
Now, go to your SLAVE site (I'm using these terms loosely) and delete that theme via SFTP, and upload whichever other theme you want to use on that site. Then, hardcode it like this:
define('WP_DEFAULT_THEME', 'twentytwenty');

In this way, the SLAVE site tries to find the correct theme from wp_options that is activated on the MASTER site but you deleted it already, so it reverts to using the default theme as defined in wp-config.php
Going forward, do not mess with site settings/plugins/etc on the SLAVE site, and make any changes to the design of your SLAVE site using the theme files only (like a static theme). Obviously if you are using a bloated theme and page builder type of situation that need MySQL, this isn't going to work...
Note: you may need to visit /wp-admin/themes.php on your SLAVE site at least once, to "force" WordPress to load the hardcoded theme.
If anyone is interested, SlickStack supports this approach.

A: Duplicate of https://wordpress.stackexchange.com/q/65560/wp-multisite-load-content-from-site-x-on-site-y
One might argue that using WP multisite-network functionality and adding a couple of documented API calls to ones theme could be a cleaner solution than manually modifying the database schema and messing with how WP access it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to strikeout text of QStandardItem in Qt/PyQt? I have a QStandardItemModel in PySide, and want to strikeout text on certain rows (it is a to do list application and when a task is done, I want to strike through the text). Given a QStandardItem that displays fine, based on the documentation I try to strikethrough the text with:
QStandardItem.setFont(QtGui.QFont.setStrikeOut(True))

But the text is unchanged, and I get error:
TypeError: descriptor 'setStrikeOut' requires a 'PySide.QtGui.QFont' object but received a 'bool'

A: setStrikeOut returns void and you should not pass it as the argument for setFont. You should pass an instance of QFont there.
It would be better to retrieve the font of the item in question, set its  strikeout property, and then set this revised QFont as the new font of the item :
f = item.font()
f.setStrikeOut(True)
item.setFont(f)

This way you would keep other options of the item's font previously set.


text:
Q: Prevent 'aria-live' element from being focused by screen reader Is there a way to prevent an 'aria-live' element from being focused by a screen reader?
I'm developing a calendar and would like to notify user whenever the currently selected month is changed.

A: As others have said, keyboard focus does not have to move to the aria-live region.  Any changes made to a live region will just be announced.  The focus will not move.
However, if you are asking whether you can prevent the user from moving their screen reader focus to the element, no, you can't prevent that.  As long as the element is part of the accessibility tree (a subset of the DOM), the user can navigate to that element and hear its contents.
The rules on whether a DOM element is part of the accessibility tree are spelled out pretty well in "5.1 General rules for exposing WAI-ARIA semantics".  Specifically, in the "5.1.2 Including..." section, it says elements that have text will be included.  I'm presuming your aria-live element has text because it's being announced as you change it.  If you jump back up to the "5.1.1 Excluding..." section, you can prevent the element from being on the accessibility tree if you use aria-hidden="true", but if you do that, then the live changes won't be read.

A: If implemented correctly, aria-live region will never receive visual focus.
Make sure that the live region is present on the page initially, only then dynamically added/changed content will be announced. Live region of the page that gets announced whenever content changes but the focus doesn't shift to the live region.


text:
Q: Calculate how much bits is in int without sizeof() i am trying to create simple game. Task is to create program that calculate size of int in bites.
Their code is
#include <stdio.h>
int intSize(void)
{
    unsigned int x,
        i = 0;
        x = ?;
    while ((?) != 0)
        ?;
    return ?;
}
int main()
{
    printf("Size is %d bits\n",?);
    return 0;
}

? is place where i should put my code.
This is what one of my tries
#include <stdio.h>
int intSize(void)
{
    unsigned int x,
        i = 0;
        x = 0;
    while ((x>>1) != 0)
        i++;
    return i;
}
int main()
{
    printf("Size ise %d bits\n", intSize());
    return 0;
}

I know that usigned int is 4bytes so i use bitwise operation to move bits it should be 32 but i am getting 1. I will be thankfull for any help.

A: Having
x = 0;
while ((x>>1) != 0)
  ...

the while stops immediately, so i is unchanged and the return value is 0.
The right way was to initialize x with~0u to have all bits valuing 1 (suppose 2-complements)
Out of that the test is not the right one and you missed to modify the value of x.
In

printf("Size ise %d bits\n", intSize);

you missed the () to call the function, currently you try to write its address, I say try because an address must be printf with the format %p.
Finally:
#include <stdio.h>

int intSize(void)
{
  unsigned int x,
     i = 0;

  x = ~0u;
  while ((x & 1) != 0)
    (i+= 1, x /= 2); /* not x >= 1 in case it is a rotate rather than a shift */
  return (int) i;
}

int main()
{
    printf("Size is %d bits\n", intSize());
    return 0;
}

Compilation and execution:
pi@raspberrypi:/tmp $ gcc -Wall s.c
pi@raspberrypi:/tmp $ ./a.out
Size is 32 bits
pi@raspberrypi:/tmp $

So in order the '?' are :

*

*~0u

*x & 1

*(i+= 1, x /= 2)

*(int) i

A: I'd solve this problem by putting a 1 in the low bit of an integer and shift left until it's zero, which means the bit clocked all the way out.
#include <stdio.h>
int intSize(void)
{
    unsigned int x,
        i = 0;
        x = 1;
    while ((x <<= 1) != 0)
        i++;
    return i+1;
}

int main()
{
    printf("Size is %d bits\n", /*?*/ intSize());
    return 0;
}

No concerns about signed/unsigned as far as I can tell.
EDIT to reflect the ? placeholder requirements of the project.


text:
Q: Mysql workbench, introducir los mismo datos en varios esquemas y otra duda Estoy recién empezando en mysql y estamos usando mysql workbench, tengo algunas dudas. ¡Gracias a todos!
Cuando inicio mysql shell me sale "MySQL JS" aunque puedo cambiar a "MySQL sql". No puedo ni cargar ni usar la base de datos con el JS, al menos no sé cómo hacerlo y en cambio, en el modo sql no tengo problema. ¿Alguien me puede explicar la diferencia? ¿Y cómo puedo cargar y usar una base de datos con JS?
Por otra parte, cuando trabajo en el workbench e introduzco datos, sale la siguiente sintáxis:
INSERT INTO sakila.actor (first_name, last_name) VALUES ('Juan', 'Ruíz');
La cuestión es que si pongo sakila.actor, solo puedo introducir la información en el esquema de sakila, ¿habría alguna forma de introducir la línea para cualquier esquema y en la tabla actor?
De nuevo, gracias!

A: Respecto a la segunda parte de tu pregunta, es posible insertar en cualquier esquema, en la tabla actor? Sí se puede, sin embargo, requiere algo de trabajo.
No sé cómo consultarlas en MySQL, pero, en SQLServer las tablas de sistema pueden darte la información que buscas. Lo que puedes hacer es:
1-. Obtener los nombres de los esquemas que han sido creado por los usuarios a través de las tablas de sistema.
2-. Creas un cursor para iterar sobre los nombres.
3-. Con sql dinámico, en el Insert, deberás reemplazar el esquema por el valor del cursor
Por ejemplo en Transact-Sql:
DECLARE @sql as nvarchar(MAX);
set @sql = N'
   Insert into ' +@nombreEsquema+ '.Usuario (first_name,last_name)
   Values('+@first_name+','+@last_name+')'

Y luego se ejecuta el sql dinámico con :
 sp_executesql @sql

Para cada row del cursor.
Nuevamente, eso es T-SQL. Tendrás que buscar cómo hacerlo en MySQL.
Recuerda evaluar si la tabla existe en el esquema. Si no existe, habrá un error. Tal vez quieras obtener de las tablas de sistema los esquemas donde sí exista una tabla llamada Actor
Tu pregunta es algo extraña, pero ya he necesitado algo así. Espero esto te ayude y apunte en la dirección correcta


text:
Q: Rvest web scrape returns empty character I am looking to scrape some data from a chemical database using R, mainly name, CAS Number, and molecular weight for now.  However, I am having trouble getting rvest to extract the information I'm looking for.  This is the code I have so far:
library(rvest)
library(magrittr)

# Read HTML code from website
# I am using this format because I ultimately hope to pull specific items from several different websites
webpage <- read_html(paste0("https://pubchem.ncbi.nlm.nih.gov/compound/", 1))

# Use CSS selectors to scrape the chemical name
chem_name_html <- webpage %>%
                  html_nodes(".short .breakword") %>%
                  html_text()

# Convert the data to text
chem_name_data <- html_text(chem_name_html)

However, when I'm trying to create name_html, R only returns character (empty).  I am using SelectorGadget to get the HTML node, but I noticed that SelectorGadget gives me a different node than what the Inspector does in Google Chrome.  I have tried both ".short .breakword" and ".summary-title short .breakword" in that line of code, but neither gives me what I am looking for.

A: I have recently run into the same issues using rvest to scrape PubChem. The problem is that the information on the page is rendered using javascript as you are scrolling down the page, so rvest is only getting minimal information from the page.
There are a few workarounds though. The simplest way to get the information that you need into R  is using an R package called webchem.
If you are looking up name, CAS number, and molecular weight then you can do something like:
library(webchem)
chem_properties <- pc_prop(1, properties = c('IUPACName', 'MolecularWeight'))
The full list of compound properties that can be extracted using this api can be found here. Unfortunately there isn't a property through this api to get CAS number, but webchem gives us another way to query that using the Chemical Translation Service.
chem_cas <- cts_convert(query = '1', from = 'CID', to = 'CAS')
The second way to get information from the page that is a bit more robust but not quite as easy to work with is by grabbing information from the JSON api.
library(jsonlite)
chem_json <-
read_json(paste0("https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/", "1", "/JSON/?response_type=save$response_basename=CID_", "1"))
With that command you'll get a list of lists, which I had to write a convoluted script to parse the information that I needed from the page. If you are familiar with JSON, you can parse far more information from the page, but not quite everything. For example, in sections like Literature, Patents, and Biomolecular Interactions and Pathways, the information in these sections will not fully show up in the JSON information.
The final and most comprehensive way to get all information from the page is to use something like Scrapy or PhantomJS to render the full html output of the PubChem page, then use rvest to scrape it like you originally intended. This is something that I'm still working on as it is my first time using web scrapers as well.
I'm still a beginner in this realm, but hopefully this helps you a bit.


text:
Q: Find answered % rate of any Stack Exchange community There is an option to find answered percentage for each tag on Stack Overflow, but I want to know if there is any way I can check the answered rate of Super User.

A: In the Sites list on stackexchange.com:


text:
Q: Return (self) generated value from insert statement (no id, no returning) sorry, if the question title is misleading or not accurate enough, but i didn't see how to ask it in one sentence.
Let's say we have a table where the PK is a String (numbers from '100,000' to '999,999', comma  is for readability only).
Let's also say, the PK is not sequentially used.
Now i want to insert a new row into the table using java.sql and show the PK of the inserted row to the User. Since the PK is not generated by default (e.g. insert values without the PK didn't work, something like generated_keys is not available in the given environment) i've seen two different approaches:
in two different statements, first find a possible next key, then try to insert (and expect that another transaction used the same key in the time between the two statements) - is it valid to retry until success or could any sql trick with transaction-settings/locks help here? how can i realize that in java.sql?
for me, that's a disappointing solution, because of the non-deterministic behaviour (perhaps you could convince me of the contrary), so i searched for another one:
insert with a nested select statement that looks up the next possible PK. looking up other answers on generating the PK myself I came close to a working solution with that statement (left out the casts from string to int):
INSERT INTO mytable (pk,othercolumns)
VALUES(
(SELECT MIN(empty_numbers.empty_number)
  FROM (SELECT t1.pk + 1 as empty_number
    FROM mytable t1

    LEFT OUTER JOIN mytable t2
    ON t1.pk + 1  = t2.pk

    WHERE t2.pk IS NULL
    AND t1.pk > 100000)
  as empty_numbers),
 othervalues);

that works like a charm and has (afaik) a more predictable and stable solution than my first approach, but: how can i possibly retrieve the generated PK from that statement? I've read that there is no way to return the inserted row (or any columns) directly and most of the google results i've found, point to returning generated keys - even though my key is generated, it's not generated by the DBMS directly, but by my statement.
Note, that the DBMS used in development is MSSQL 2008 and the productive system is currently a DB2 on AS/400 (don't know which version) so i have to stick close to SQL standards. i can't change the db-structure in any way (e.g. use generated keys, i'm not sure about stored procedures).

A: DB2 for i allows generated keys, stored procedures, user defined functions - pretty much all of the things SQL Server can do.  The exact implementation is different, but that's what manuals are for :-)  Ask your admin what version of IBM i they're running, then hit up the Infocenter for specifics.
The constraining factor is that you can't alter the database design; you are stuck with apparently multiple processes trying to INSERT while backfilling 'holes' in the existing keyspace.  That's a very tough nut to crack.  Because you can't change the DB design, there's nothing to be done except to allow for and handle PK collisions.  There's no SQL trick that'll help - the SQL way is to have the DB generate the PK, not the application.
There are several alternatives to suggest, in the event that some change is allowed.  All have issues needing a workaround, but that is unavoidable at this point due to the application design.

*

*Create a UDF that all INSERT clients use to retrieve the next available PK.  Use a table of 'available numbers' and delete them as they are issued.

*Pre-INSERT all the available numbers.  Force clients to do an UPDATE.  Make them FETCH...FOR UPDATE where (rest of data = not populated).  This will lock the row, avoiding collisions as well as make the PK immediately available.

*Leave the DB and the other application programs using this table as-is, but have your INSERT process draw from a block of keys that's been set aside for your use.  Keep the next available number in an SQL SEQUENCE or an IBM i data area.  This only works if there's a very large hole in the keyspace that's not yet used.


text:
Q: Inoic : Ionic avatar is not displaying item-avatar not working in my project it's not showing item-avatar element at all.
  <ion-content padding>
  <ion-list>
      <ion-list-header>
          Recent Conversations
      </ion-list-header>
      <ion-item>
          <item-avatar start>

          </item-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>

      <ion-item item-start>
          <item-avatar start>

          </item-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>

      <ion-item slot="start">
          <item-avatar start>

          </item-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>
  </ion-list>
</ion-content>

Package JSON
"rxjs": "5.4.0",
"core-js": "2.4.1",
"zone.js": "0.8.12",
"typescript": "2.3.4",
"@angular/core": "5.2.9",
"@angular/http": "4.1.3",
"ionic-angular": "3.9.2",
"@angular/forms": "5.2.9",
"@angular/common": "5.2.9",
"@angular/compiler": "5.2.9",
"@angular/compiler-cli": "5.2.9",
"@angular/platform-browser": "5.2.9",
"@angular/platform-browser-dynamic": "5.2.9"

below is the stackblitz url of project
https://stackblitz.com/edit/ionic-mntalz
It should show the image in the left-hand side

A: You made a mistake at <item-avatar start>
Change to :
<ion-avatar item-start>

 </ion-avatar>

Workin code :
<ion-content padding>
  <ion-list>
      <ion-list-header>
          Recent Conversations
      </ion-list-header>
      <ion-item>
          <ion-avatar item-start>

          </ion-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>

      <ion-item item-start>
          <ion-avatar item-start>

          </ion-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>

      <ion-item slot="start">
         <ion-avatar item-start>

          </ion-avatar>
          <ion-label>

Finn

I'm a big deal

Listen, I've had a pretty messed up day...

          </ion-label>
      </ion-item>
  </ion-list>
</ion-content>

Reference Link: https://ionicframework.com/docs/v3/components/#multiline-list
Working demo : https://stackblitz.com/edit/ionic-z5icij

A: You made a mistake at
Change to :
<ion-list>
  <ion-item>
   <ion-avatar item-start>

   </ion-avatar>

Cher

Ugh. As if.

  </ion-item>
</ion-list>

Reference Link: https://ionicframework.com/docs/v3/components/#avatar-list
you should remove extra "item-start" on other elements. Use only on avatar "item-start"
You need to check this answer.


text:
Q: How to set variables via eval() when JS compressors rename variables? I have a JS file that does something like this:
var value = localStorage.getItem(somekey);
if ( !value )
{
  eval("value = String(" + somevariablename + ");");
}

This script tries to retrieve a value from Local Storage. If the value does not exist in Local Storage, it sets to using an eval off of the value of a previously defined variable. The eval is necessary for me in this case since the value of value has to be set to the String value of a variable name. I don't know any other way around this.
The problem is that most good JS Compressors offer a way to automatically rename variable names in order to save space. I end up with something like this:
var f=localStorage.getItem(e);
if(!f){eval("value = String("+e+");")}

So the problem is that my variable got renamed but the compressor doesn't know to change the name of the variable in the eval string. I have never seen a compressor that was smart enough to figure that out.
What is the best way to deal with this in an automated fashion in a build environment? Going in and manually changing the variable name in the evals is pretty time consuming since in my case, code like this occurs a lot.

A: Do not use eval to create variable on the fly.
You can simply catch the global object, and then any property created on it is a variable on the global scope anyway...
window["value"] = "something";
And then by creating your variable this way, you do not have to use eval to get the variable names since you are creating them with a string.


text:
Q: What is the purpose of launch images in an iOS application? How important is it to add Launch Images to an iOS application? I assume that these are like a cached file to show on the screen while the application is getting setup, when there might otherwise be nothing to show until it is fully running. Is this right?
If so, what should a launch image be if your app might start in different states, or does this not effect return to foreground when multitasking? If it is only for the very first initial launch of the app, then the launch image should just be the same as whatever graphic normally appears when you first start the app, right?
Apple must not care too much about whether your app actually includes these, since mine never have.

A: Note:  as Zev mentions below, the Apple HIG recommendation has changed since I originally answered this question.  Apple now recommends that you take all of the static elements of your first screen and make that into your default or launch page.  All dynamic elements are to be removed, to give the impression that your app is going through an initialization process -- which in some cases may mean that your default screen is simply a background from your app.  Thanks to Zev Eisenberg for pointing that out, "splash" pages are not recommended.
The launch image will show while your app is initializing, it's a good idea to have one.  If you don't have one the user is likely to stare at a blank screen while waiting for your app to load.  I believe the recommendation is to use an image that looks like the first page of your app.  Here is the reference:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW5

A: how about if app is starting immediately and no time passed ?
what if you see (or cannot see) for a 0.1 sec launch image ?
would it be still useful to have two images in main bundle that will never be seen or used ?


text:
Q: Python multiprocessing using pickle, kwargs, and function references I have a situation where I encounter problems using any efficent multiprocessing framework in python (no matter whether scoop or multiprocessing).
I have the following situation:

*

*One class 'Foo' which holds a function 'f'

*A second class 'Bar' which gets the arguments (kwargs) and holds an instance of class 'Foo' (containing the function)

*In 'Bar', the function of class Foo is executed using the arguments given.

*The results are, for reasons of statistical significance, averaged over multiple runs, in this case 10 times (not shown in given example).

Here is the example:
import multiprocessing as mp

class Foo:
    def __init__(self, f):
        self.f = f

class Bar:
    def __init__(self, foo, **kwargs):
        self.args = kwargs
        self.foo = foo

    def execute(self):
        pool = mp.Pool(5)
        f = lambda x : self.foo.f(**x)
        args = [self.args] * 10
        results = pool.map(f, args)

if __name__ == '__main__':
    def anything(**kwargs):
        print(kwargs['z'])
        return kwargs['x'] * kwargs['y']
    foo = Foo(anything)
    args = {'x':10, 'y':27, 'z':'Hello'}
    bar = Bar(**args)

I know that functions must be on module level in order to be pickable. Is there any way to be able to get the function pickable? Unfortunately, I am not very experiences in Python OOP, so probably I am missing an important point!
Thank you!
EDIT:
Unfortunately, even with using the module "multiprocess" which uses dill instead of pickle (thanks to Mike McKerns) it is not guaranteed that my problem is solved. For some short runs of my program, things are fine. For some reasons, multiprocess seems to generate race conditions as I get following error:
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/multiprocess/pool.py", line 389, in _handle_results
    task = get()
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 209, in loads
    return load(file)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 199, in load
    obj = pik.load()
  File "/usr/lib/python2.7/pickle.py", line 864, in load
    dispatch[key](self)
  File "/usr/lib/python2.7/pickle.py", line 1096, in load_global
    klass = self.find_class(module, name)
  File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 353, in find_class
    return StockUnpickler.find_class(self, module, name)
  File "/usr/lib/python2.7/pickle.py", line 1132, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Individual'

(Individual is a class which is used by my program [genetic algorithm using deap]) Any idea?

A: (repeating the comments above)
Substitute the multiprocess package for multiprocessing and the code should work with no other changes.  This is because multiprocess is a fork of multiprocessing that uses dill instead of pickle… so you are able to serialize almost anything in python, including stuff you write in the interpreter session. That's the only change made for the fork of multiprocessing.
See https://stackoverflow.com/a/21345273/2379433 and https://stackoverflow.com/a/21345308/2379433 and https://stackoverflow.com/a/21345423/2379433 and etc.


text:
Q: Add column to dataset in MLDB So I'm playing with http://mldb.ai/ and I have a simple question. I have a csv file that I want to import using http://mldb.ai/doc/#builtin/datasets/TabularCsvDataset.md.html
It works fine but I would like to add a column. I actually have a bunch of csv files to I will merge but in order to differentiate them I would like to add the csv file name as a value in a new column.
Say I have the file filea.csv and fileb.csv, both with columns X Y Z. I would like to add a column so I get
X Y Z name
How do I add this column?

A: The text.csv.tabular dataset (which has been renamed to tabular, as you will see in the next release) is immutable, so you cannot add columns to it. You can create a new dataset with the result of a JOIN or merge operation.


text:
Q: substitute minus for plus symbol between 2 quotation marks The original text is like

a = a + "a + b" + c + "a + b" + c

How to use regex in vim to archive the following result:

*

*to substitute - for + out of the every pair of quotation marks.

a = a - "a + b" - c - "a + b" - c

*to substitute - for + in every pair of quotation marks.

a = a + "a - b" + c + "a - b" + c

I've tried lookbehind and lookahaed with lazy or greedy multiplier to get the result step by step. However, I want to know whether these is a general statement for such a case, which can make substitution clearly and beautifully.
Thanks

A: try the couple of cmds in vim:
for the first one:
s/\zs+\ze\s*"\|"\s*\zs+\ze/-/g

for the 2nd one:
s/"[^+"]*\zs+\ze[^+"]*"/-/g

A: 1.: \+(?=(?:[^"\n]*"[^"\n]*")*[^"\n]*$)
2.: \+(?=(?:[^"\n]*"[^"\n]*")*[^"\n]*"[^"\n]*$)

Demo 1.
Demo 2.
The idea is simple: Match a + only if there's an even/uneven number of quotes behind it.
Explanation of the first pattern:
\+ // match "+"
(?= // assert there's an even number of quotes left
    (?:
        [^"\n]*" // consume one quote, and all text in front of it...
        [^"\n]*" //...twice
    )* //...as often as possible
    [^"\n]*$ // finally, assert there's no more quotes in this line.
)

A: \+(?=(?:[^"]*"[^"]*")*[^"]*$)

This will be for the first case.exclude + if between " and ".See demo.
http://regex101.com/r/nA6hN9/44
\+(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)

This will be for the second case.If between " abd ".
See demo.
http://regex101.com/r/nA6hN9/45


text:
Q: Javascript problems with code, TypeError: comp1GameTitle is null Welcome again,and again. I have a lot of errors,it's just joking with me.
The code is works here => https://jsfiddle.net/jh5tkfpp/ posted by a forum member (Sridhar). But in my local-webserver it's throwing TypeError: comp1GameTitle is null .

var cGamePic = new Array("https://c6.staticflickr.com/9/8804/28522899701_efbaa953a7_n.jpg", "https://c5.staticflickr.com/7/6003/6004770804_692aecf57c_b.jpg", "https://c5.staticflickr.com/7/6006/6004652276_87ba0278a9_b.jpg", "https://c7.staticflickr.com/7/6139/6007896022_c7ac652043_b.jpg");
var cGameName = new Array("beach", "cycle1", "cycle2", "cycle3");
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1

var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2

var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container
var comp1GameImage = document.querySelector("#container1 img"); //Image from main container

var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container
var comp2GameImage = document.querySelector("#container2 img"); //Image from main container

comp1GameTitle.innerHTML = cGameName[randomItemContainer1];
comp1GameImage.src = cGamePic[randomItemContainer1]; //Random image
<!doctype html>

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

Title

Title

A: It works in jsfiddle since they are executed onload. But you have put scripts in the head. So when they are executed DOM is not ready there is no element with id container1. So you can make changes as following snippet

//Rest of code

else you can still keep rnd.js inside header tag but put all code in rnd.js inside  a window.onload function


text:
Q: Does an std::optional parameter create a copy? I have a function that takes an std::optional
void foo(const std::optional<T>& opt);
But copying T is expencive.
Does this create a copy of T?
If so, how can I not create a copy?

A: I think you will find useful this documentation page. See the section about "Optional function parameters".
When you call the function and pass an instance of T, an optional will be constructed which will own its own copy of T, therefore it will call T's copy constructor.
int main()
{
  T t;
  optional<T> ot;
  foo(t);  // will create a copy
  foo(ot); // won't create a copy
}

If you're using boost::optional, not std::optional, you can declare foo as receiving an optional reference, i.e.
void foo(boost::optional<const T&> t)

A: As clarified by your follow up comment, you are calling the function foo like this:
T t;
...
foo({t});

In this case, the answer is yes. A copy of t will be created. To avoid that, you can use std::reference_wrapper to avoid copying:
void foo(const std::optional<std::reference_wrapper<const T>> &optT) {
    ...
}

With these changes to the function, calling the it in the same manner will not result in creation of a copy.

A: Yes, std::optional stores a copy of whatever you pass to it. The C++17 standard explicitly prohibits storing references in std::optional. See: https://en.cppreference.com/w/cpp/utility/optional#:~:text=There%20are%20no%20optional%20references
As suggested by others, passing std::optional<std::reference_wrapper<const T>> is one way to avoid making copies.
void foo(const std::optional<std::reference_wrapper<const T>>& opt) {
  if (opt) {
    // Do something.
  }
}

T t;
foo(t);

But consider that the C++ committee had good reasons for disallowing references in std::optional. For instance, an "optional reference" essentially describes what a plain pointer does, and plain pointers don't suffer from the long type name.
void foo(const T* opt) {
  if (opt) {
    // Do something.
  }
}

T t;
foo(&t);


text:
Q: How to 'set timezone' for psql from jpa entitymanager? How should I manipulate timestamp in UTC to be able to append offset?
I know the basics from here:
http://blog.untrod.com/2016/08/actually-understanding-timezones-in-postgresql.html
But yet to find a proper solution for this problem:
Psql  database is in UTC, for a date stored in db I want to pass the zone and get back the correct timezone result:
say passing Europe/Berlin should result in : 2018-02-03 02:00:00+00 -> 2018-02-03 04:00:00+02:00
When I use select my_date with time zone 'Europe/Berlin' will increment the hour correctly but unfortanetly will truncate the offset.
One solution I have found is 'set timezone=Europe/Berlin' before the query which works like a charm when I use
it from pure sql. However when I try to invoke it as nativequery it results in error, maybe because it isnt a DML query.
I have tried to set the session's timezone from java code for a session :
session = HibernateUtil.getSessionFactory().withOptions()
.jdbcTimeZone(TimeZone.getTimeZone("Europe/Berlin"))
.openSession();

But a query in the same session ( SELECT current_setting('TIMEZONE');) says it is still UTC.
I can overcome this problem from code(transforming result from java code according to the zone), however I want to do it from
sql query.
Is that possible somehow?


text:
Q: Observe singleton timer value changes with Publisher in Combine One of the requirements of my application is the ability to start multiple timers, for reporting purposes.
I've tried to store the timers and seconds passed in an @EnvironmentObject with @Published variables, but every time the object refreshes, any view that observes the @EnvironmentObject refreshes too.
Example
class TimerManager: ObservableObject {
   @Published var secondsPassed: [String: Int]
   var timers: [String:AnyCancellable]

   func startTimer(itemId: String) {
      self.secondsPassed[itemId] = 0
      self.timers[itemId] = Timer
          .publish(every: 1, on: .main, in: .default)
          .autoconnect()
          .sink(receiveValue: { _ in
                self.secondsPassed[itemId]! += 1
          })
   }

   func isTimerValid(itemId: String) -> Bool {
       return self.timers[itemId].isTimerValid
   }

   // other code...
}

So for example, if in any other view I need to know if a particular timer is active by calling a function isTimerValid, I need to include this @EnvironmentObject in that view, and it won't stop refreshing it because the timer changes secondsPassed which is Published, causing lags and useless redrawings.
So one thing I did was to cache the itemId of the active timers somewhere else, in a static struct that I update every time I start or stop a timer.
It seemed a bit hacky, so lately I've been thinking to move all this into a Singleton, like this for example
class SingletonTimerManager {

   static let singletonTimerManager = SingletonTimerManager()

   var secondsPassed: [String: Int]
   var timers: [String:AnyCancellable]

   func startTimer(itemId: String) {
      self.secondsPassed[itemId] = 0
      self.timers[itemId] = Timer
          .publish(every: 1, on: .main, in: .default)
          .autoconnect()
          .sink(receiveValue: { _ in
                self.secondsPassed[itemId]! += 1
          })
   }

   // other code...
}

and only let some Views observe the changes to secondsPassed. On the plus side, I can maybe move the timer on the background thread.
I've been struggling how to do this properly.
These are my Views (albeit a very simple extract)
struct ContentView: View {

    // set outside the ContentView
    var selectedItemId: String

    // timerValue: set by a publisher?

    var body: some View {
        VStack {
            ItemView(seconds: Binding.constant(timerValue))
        }
    }
}

struct ItemView: View {
    @Binding var seconds: Int

    var body: some View {
        Text("\(self.seconds)")
    }
}

I need to somehow observe the SingletonChronoManager.secondsPassed[selectedItemId] so the ItemView updates in real time.

A: By putting the timer publisher results into Environment, you are propagating change notifications to all views within the tree that define that environment object, which I'm sure will cause un-needed redraws and performance issues (and as you've seen).
A better mechanism is strongly limiting the views (or subviews) that need to display the constantly updating time, and pass in a reference to a timer publisher directly to them rather than layering it into the environment. Putting the timer itself into a singleton is one option but not critical to this, and won't effect the cascading redraws you're seeing.
How to use a timer with SwiftUI has a "shoving a timer into the view itself", which may work for what you're trying to do, but slightly better is the video here: https://www.hackingwithswift.com/books/ios-swiftui/triggering-events-repeatedly-using-a-timer
In Paul's example, he's stuffing the timer into the view itself - wouldn't be my choice, but for a simple real-time clock view it's not bad. You could just as easily pass in the timer publisher from an external object - like your singleton for example.

A: I've ended up using the following solution, combining @heckj suggestion and this one from @Mykel.
What I did was separating the AnyCancellable from the TimerPublishers by saving them in specific dictionaries of SingletonTimerManager.
Then, every time an ItemView is declared, I instantiate an autoconnected @State TimerPublisher. Every Timer instance now runs in the .common RunLoop, with a 0.5 tolerance to better help the perfomance as suggested by Paul here: Triggering events repeatedly using a timer
During the .onAppear() call of the ItemView, if a publisher  with the same itemId already exists in SingletonTimerManager, I just assign that publisher to the one of my view.
Then I handle it like in @Mykel solution, with start and stopping both ItemView's publisher and SingletonTimerManager publisher.
The secondsPassed are shown in a text stored inside @State var seconds, which gets updated with a onReceive() attached to the ItemView's publisher.
I know that I'm probably creating too many publishers with this solution and I can't pinpoint exactly what happens when copying a publisher variable into another, but overall perfomance is much better now.
Sample Code:
SingletonTimerManager
class SingletonTimerManager {
   static let singletonTimerManager = SingletonTimerManager()

   var secondsPassed: [String: Int]
   var cancellables: [String:AnyCancellable]
   var publishers: [String: TimerPublisher]

   func startTimer(itemId: String) {
      self.secondsPassed[itemId] = 0
      self.publisher[itemId] = Timer
          .publish(every: 1, tolerance: 0.5, on: .main, in: .common)
      self.cancellables[itemId] = self.publisher[itemId]!.autoconnect().sink(receiveValue: {_ in self.secondsPassed[itemId] += 1})
   }

   func isTimerValid(_ itemId: String) -> Bool {
       if(self.cancellables[itemId] != nil && self.publishers[itemId] != nil) {
           return true
       }
       return false
   }
}

ContentView
struct ContentView: View {

    var itemIds: [String]

    var body: some View {
        VStack {
            ForEach(self.itemIds, id: \.self) { itemId in
                ItemView(itemId: itemId)
            }
        }
    }
}

struct ItemView: View {
    var itemId: String
    @State var seconds: Int
    @State var timerPublisher = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
        Button("StartTimer") {
            // Call startTimer in SingletonTimerManager....
            self.timerPublisher = SingletonTimerManager.publishers[itemId]!
            self.timerPublisher.connect()
        }
        Button("StopTimer") {
            self.timerPublisher.connect().cancel()
            // Call stopTimer in SingletonTimerManager....
        }
        Text("\(self.seconds)")
            .onAppear {
                // function that checks if the timer with this itemId is running
                if(SingletonTimerManager.isTimerValid(itemId)) {
                     self.timerPublisher = SingletonTimerManager.publishers[itemId]!
                     self.timerPublisher.connect()
                }
            }.onReceive($timerPublisher) { _ in
                self.seconds = SingletonTimerManager.secondsPassed[itemId] ?? 0
            }
    }
}
}


text:
Q: React testing components with children components I recently started developing components with React, and now that things start looking good, I want to test them using Mocha and Enzyme.
Here is my proposition/question/request for answer:
I  have a Fieldset component which contains a "title" props and other components (several Field components) which I pass using {this.props.children) like the following:
Component:
export default class Fieldset extends React.Component {
  constructor(props) {
      super(props);
  }

  render() {
    return (
      <fieldset>

{this.props.title || ""}

         {this.props.children}
      </fieldset>
   );
 }
}

Use:
<Fieldset title="Log In">
    <Field
      label={}
      input={
        <TextInput
          fieldName="username"
          type="text"
          placeholder="Enter your username"
          state={this.props.state}
          handleChange={this.props.handleInputChange}
        />
      }
    />
    <Field
      label={}
      input={
        <TextInput
          fieldName="password"
          type="password"
          placeholder="Enter your password"
          state={this.props.state}
          handleChange={this.props.handleInputChange}
        />
      }
    />

Test:
I already made a few tests which work such as
describe('<Fieldset />', () => {
  let wrapper;

  beforeEach(() => {
     wrapper = mount(
        <Fieldset
           title="My title"
        />
     )
  });

  it('should have a title variable in the props', () => {
     expect(wrapper.props().title).to.equal('My title');
  });

Questions:
1) Is it a good practice to use components as props of other components like "input={ [TextInput title="blabla"] } ?
2) How do I test the behavior of {this.props.children} in my Test ?
a: Should I use something like that and not worry too much with node except making sure that it's equal to the content of my node variable ?
   const node =
Hi

   beforeEach(() => {
      wrapper = mount(
         <Fieldset
            title="My title"
            {node}
      />
    )
   });

b: Should I import the other components (in this case the Field component) with mock props and so on (like a real use of the component with children) and use it to test the Fieldset component ? Would not I be out of context for the purpose of this Fieldset test ?
<Fieldset title="Log In">
    <Field
      label={}
      input={
        <TextInput
          fieldName="username"
          type="text"
          * etc etc *
        />
    />
 </Fieldset>

Thank you for helping me finding out which way is the best to test my components.


text:
Q: iOS Share Extension Doesn't Terminate I've created an iOS share extension with a custom UI (not using SLComposeServiceViewController) and everything works great.
Once the extension is invoked, it takes a shared URL or text and sends it. That's all it does and it works well.
The custom UI is simple. One image view that shows a graphic indicating that it is sending and then that changes to say "Sent" once done. Then this fades out.
What is going wrong is after this is done, the extension seems to disappear, but I can't control the host application anymore. It's as if an invisible window or view is on top of everything. (For example, an image rotator in Safari still rotates, but I can't scroll or tap links or buttons, etc.)
I'm calling [self.extensionContext completeRequestReturningItems:nil completionHandler:nil]; once the share is done, and as I understand it, that should dismiss my UI. I've also tried [self.view removeFromSuperview] without any luck.
Happens on Simulator and Device. Is there something I'm missing?
Edit: This is what the view hierarchy of a simple app I built to test sharing looks like in Reveal before and after sharing. The app has two buttons: share text and share url, each of which bring up a standard share sheet.
Before
http://joshh.is/1utYnKS
After
http://joshh.is/1rdVo34

A: Ok, I don't know why it took me 10 hours to realize that I was not including a call to super inside of my beginRequestWithExtensionContext: method.
I don't know what other problems that caused, but it certainly caused my problem above.


text:
Q: Chemmacros: Undefined control sequence. \end When I try to create a reaction from chemmacros/reactions I got the following error. I dunno what I am missing. Please help. Thank you.

line 11: Undefined control sequence. \end
  line 11: Missing number, treated as zero. \end
  line 11: Missing number, treated as zero. \end

Minimum Working Example
\documentclass[12pt,a4paper]{article}
\usepackage{chemmacros}
\chemsetup{modules={reactions}}
\begin{document}
\begin{reaction}
    A + B -> C
\end{reaction}
\end{document}

A: This issue has been fixed in v5.8b (2017/08/28), the new version is on its way to CTAN and will reach the major distributions soon.


text:
Q: How to convert a +/-12 V digital signal to 0/+5 V? What would be a simple way to convert RS-232 +/-12 V digital levels into +5/0 V respectively?

*

*I considered an optocouple, but I can't find one that can withstand -12 V reverse voltage. I considered adding a two-resistor voltage divider, but I suspect that will worsen the slew rate of the device, and I have no idea if that will be enough to become a problem (I'm aiming at the switching speed of 19 200 baud).

*There's this simple answer, but it requires a transistor that can withstand +/-12 V as well - I'm looking for one right now but haven't found a suitable part yet. I'm also slightly worried about not having galvanic decoupling.

*I considered a 5 V linear stabilizer, but I suspect it may not be fast enough to turn off/on, after all, they weren't designed for this task.

Perhaps, an optocouple with a bulky diode in series capable of withstanding -12 V?

A: Why not a MAX232? Purpose designed for exactly this application.
https://en.wikipedia.org/wiki/MAX232


text:
Q: Read Json to object I am currently trying to read json file into an object. The version of nlohmann-json that I am using is 3.7.3. I followed the example code in that documentation that goes like this
// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;

My implementation for this was to  have a simple  function that returns a json object, so simply:
nlohmann::json UTSF::readJSONFile(std::string filename)
{
       std::ifstream i("file.json");
       json j;
       i >> j;
       return j;
}

I get the following error no operator ">>" matches these operands operand types are: json >> std::ifstream
So I did some investigating that this way of doing it is no longer used in version 3.7.3. I also looked into using json.parse and did not work as well.
What is the most update way to do this for nlohmann-jsonversion 3.7.3 ?
I'm also having similar issues with writing json to file as well
This is a minimal reproducible example I wrote that gives me the same error;
#include <iostream>
#include <nlohmann/json.hpp>
#include <fstream>
using json = nlohmann::json;

nlohmann::json readJSONFile(std::string filename)
{
    std::ifstream i(filename);
    json j;
    i >> j;
    return j;
}

int main()
{
    nlohmann::json x;
    x = readJSONFile("file.json");
    std::cout << x.dump(4) << std::endl;
}

A: For nlohmann i use this simple function
#include <nlohmann/json.hpp>

....

nlohmann::json ReadJsonFromFile(std::string file_name) {

    try {
        return nlohmann::json::parse(std::ifstream{file_name, std::ios::in});
    } catch (nlohmann::json::parse_error& e) {
        std::cerr << "JSON parse exception : " << e.what() << std::endl;
    } catch (std::ifstream::failure& e) {
        std::cerr << "Stream exception : " << e.what() << std::endl;
    } catch (std::exception& e) {
        std::cerr << "Exception : " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "Unk error" << std::endl;
    }

    return {};
}


text:
Q: Error al copiar una una celda a otra con macro? Buen dia.
Tengo el siguiente detalle:
Cuando una celda tenga una P la copie y la pegue en una hoja llamada "temporal" en la primera celda vacia. Y asi cada vez que encuentre una P.
Les dejo el codigo:
 Sub CopiarPegar()
 Dim celda As Object
 Dim rango As Range
 Dim UltimaFila As Long
 UltimaFila = 0
 UltimaFila = ActiveWorkbook.Sheets("temporal").Range("A1").End(XlDirection.xlUp).Offset(1, 0)
 Set rango = ActiveWorkbook.Sheets("Cambium").Range("BN9:BN179")

 For Each celda In rango
    If celda = "P" Then MsgBox "Encontrado"
       celda.Copy
       'ActiveWorkbook.Sheets("temporal").Range("A1").Offset(1, 0).Select'
       'ActiveWorkbook.Sheets("temporal").Range("A1").End(xlUp).Offset(0, 0).PasteSpecial xlPasteAll'
       'ActiveWorkbook.Sheets("temporal").Range("A1").Offset(1, 0) = 1'
       UltimaFila.PasteSpecial xlPasteAll
       UltimaFila = UltimaFila + 1
  Next celda
  ActiveWorkbook.Sheets("temporal").Select
  End Sub

Cuando la ejecuto me arroja un error en UltimaFila.PasteSpecial xlPasteAll

Espero me puedan ayudar.

A: Lo solucione de la siguiente manera:
 Sub CopiarPegar()
 Dim celda As Object
 Dim rango As Range

 Set rango = ActiveWorkbook.Sheets("Cambium").Range("BN9:BN179")

 For Each celda In rango
    If celda = "P" Then ActiveWorkbook.Sheets("temporal").Range("A" & Rows.Count).End(XlDirection.xlUp).Offset(1, 0) = celda.Value

 Next celda
 ActiveWorkbook.Sheets("temporal").Select
 End Sub


text:
Q: Trying to remove nested tag I have the following HTML:

ESPN SUMMER 2013, Bristol, CT

I was chosen for a Summer 2013 internship at ESPN, in Bristol, Connecticut. This was a dream come true opportunity for me since it combined my love of sports with my love of web development. I was part of the dotcom team which maintains the overall website. Specifically, I was part of the live events team. We handled creating pages for live games, home run derby, the Sportscenter mobile app, and many other things.

I am trying to generate slider indicator tooltips dynamically based on the
 text (just so I don't have to maintain this infinitely long list). I am only interested in the text leading up to the  tag though. I tried doing the following:
$(".item").eq(count).find("h2").clone().find("small").remove().text(); //count is for loop iterator to loop through all slides

This, however didn't work. I am not terribly advanced in JS, so could someone point me in the correct direction?

A: do you mean like:
var a = $(".item");
a.find("small").remove();
console.log(a.text());

Demo:: jsFiddle

A: you have to do like this using end():
HTML

ESPN SUMMER 2013, Bristol, CT

JQUERY
console.log($("h2").clone().find("small").remove().end().text());

EXAMPLE FIDDLE
UPDATED HTML:

ESPN SUMMER 2013, Bristol, CT

I was chosen for a Summer 2013 internship at ESPN, in Bristol, Connecticut. This was a dream come true opportunity for me since it combined my love of sports with my love of web development. I was part of the dotcom team which maintains the overall website. Specifically, I was part of the live events team. We handled creating pages for live games, home run derby, the Sportscenter mobile app, and many other things.

JQUERY:
console.log($(".item").find("h2").clone().find("small").remove().end().text());

FIDDLE WITH UPDATED HTML


text:
Q: How would I implement an efficient powers method in java Say someone is doing encryption, and it requires the use of numbers greater than the max value of long, so I need the ability to do something just as quickly (as in few steps) and efficiently as possible. take this example. I need to take (65^17) % LARGENUMBER, and so I decided to use the 65^17 part like below:
65^17=65(((65^2)^2)^2)^2. (please forgive my formatting, I dont know how to do it for this equation)
Now, I have a question about what I chose. how, per say, would I implement that into a Java code line? would it just be a for loop such as:
int fin = 65;
int times = 17/2;
int extra = 17 % 2;
for(int i = 0; i < times; i++){
    ...code...
}

and then what would be in the code? would it just be:
fin = (fin * 65) % LONGNUMBER;

would that even work? or what would I change about this to make it work? This is all theory by the way.
Thanks for the help, in advance :)

A: Java's java.math.BigInteger class has a modPow method to perform modular exponentiation. Does that do what you want?
If you want to do it yourself, here is pseudocode for the "square-and-multiply" algorithm, which I will leave to you to translate into Java with appropriate datatypes:
function modPow(base, exp, mod)
    x := 1
    while exp > 0
        if exp % 2 == 1
            x := (x * base) % mod
        base := (base * base) % mod
        exp := exp // 2 # integer division
    return x


text:
Q: UIAppearanceProxy background image bugs I'm using UIAppearance selectors for UIToolBar, UINavigationController, UISegmentedControl, UIBarButtonItem etc. and I'm seeing some REALLY strange behavior occasionally.
Somehow it's almost like the UIControls reset themselves after certain actions.  Here's a screenshot of what I mean.  Basically it's as if they no longer have the images.  If I click on the controls or rotate to reset them, they'll eventually reset but I have no idea what's causing this.
Any help is much appreciated.
Thanks in advance.


text:
Q: Best practice holding data over whole application with Spring We introduced Spring Boot and Spring Data JPA. In the old world we have a singelton for holding data which needs the whole application (list of countries and so on). The data is stored in our database.
What is the best practice to refactor it in our new world with Spring?
Should I create a bean with application scope or is nowadays best practice to handle it with caching (@Cacheable)?

A: I would recommend keeping the data in your database, but caching it with a popular in-memory caching library like caffeine or Google Guava. These libraries allow you to quickly configure an in-memory cache that can refresh the data once in a while (every 15 minute; every hour; every day; whatever you want). Your program code can hit the cache as many times as it wants, it'll always be fast. The library has the logic for periodically updating the cache.
If your data is particularly static, like application config that you may change once every few months/years, you could also consider moving it to a static config file. Spring Boot has a wide variety nifty features built-in for loading external config (JSON or YAML) and binding it to a Java-based object model. I find the @ConfigurationProperties annotation particularly useful. The external config can either be packaged in the fat-jar, or loaded externally through Spring Config Server. The major advantage of this approach is that your config will be stored in your version control system (GIT). You can also perform boot-time validation on your config, which may reveal errors that would otherwise be revealed when your service is live. Finally, your configuration is no longer dependent on a database.

A: Both approaches are OK. I prefer @Cacheable as it is a little bit less code to do things like conditional caching and evicting are easily available.


text:
Q: How to recognize users from a unique custom store listing URL? I want to create an app for different professions.
Each user will receive a unique custom store listing URL and will see relevant app info in PlayStore (Like app name, description etc).
Then I need to recognize the user in the app and use the user's API (Check screenshot below) to display relevant UI, how can I do so?
Maybe you have some suggestions for a better solution?
Thank you good sir/ ma'am and have a nice day.


text:
Q: BusyIndicator does not show up I want to show a BusyIndicator while a long process is going on. The problem is it does not show up when I make it run and shows afterwards when the process is completed. According to the docs

The busy indicator should be used to indicate activity while content is being loaded or the UI is blocked waiting for a resource to become available.

I have created a minimal code that based upon the original code
Window {
    id: win
    width: 300
    height: 300

    property bool run : false

    Rectangle {
        anchors.fill: parent
        BusyIndicator {
            anchors.centerIn: parent
            running: run
        }

        MouseArea {
            anchors.fill: parent
            onClicked: {
                run = true
                for(var a=0;a<1000000;a++) { console.log(a) }
                run = false
            }
        }
    }
}

So when the Rectangle is clicked I want to display the BusyIndicator for the time till the calculations gets completed.
For example purpose I have used the for loop here. In actual scenario I call a function (which inserts some 1000 rows into the Database) through the ContextProperty. But in that case too the BusyIndicator is not displayed.
Am I doing it the right way? Or what would be the best way to do it?

A: You cannot view your BusyIndicator just because long operation in onClicked handler blocks application GUI and indicator does not update. You should run such operation in a different thread to avoid freezing of GUI. Simple example:
QML
Window {
    id: win
    width: 300
    height: 300

    property bool run : false

    Rectangle {
        anchors.fill: parent
        BusyIndicator {
            id: busy
            anchors.centerIn: parent
            running: win.run
        }

        MouseArea {
            anchors.fill: parent
            onClicked: {
                win.run = true
                thread.sendMessage({run : true});
            }
        }

        WorkerScript {
            id: thread
            source: "handler.js"
            onMessage: {
                win.run = messageObject.run;
            }
        }
    }
}

handle.js
WorkerScript.onMessage = function(message) {
    if(message.run === true) {
        for(var a=0;a<1000000;a++) { console.log(a) }
    }
    WorkerScript.sendMessage({run : false});
}

A: There is a way to do this using QQuickWindow's afterSynchronizing signal:
import QtQuick 2.4
import QtQuick.Controls 1.3

ApplicationWindow {
    width: 400
    height: 400
    visible: true

    Component.onCompleted: print(Qt.formatDateTime(new Date(), "mm:ss:zzz"), "QML loaded")

    onAfterSynchronizing: {
        print(Qt.formatDateTime(new Date(), "mm:ss:zzz"), "Window content rendered")
        if (!loader.item) {
            loader.active = true
        }
    }

    Item {
        anchors.fill: parent

        BusyIndicator {
            running: !loader.item
            anchors.centerIn: parent
        }

        Loader {
            id: loader
            active: false
            anchors.fill: parent
            sourceComponent: Text {
                wrapMode: Text.Wrap

                Component.onCompleted: {
                    for (var i = 0; i < 500; ++i) {
                        text += "Hello, ";
                    }
                }
            }
        }
    }
}

The idea is to use a Loader to have control over when the expensive operation happens. You could also use a dynamically loaded component via Qt.createQmlObject(), or Qt.createComponent() to dynamically load a component in a separate file.
If you run the example, you'll see that you get the following output:

qml: 58:12:356 QML loaded
  qml: 58:12:608 Window content rendered

We use QQuickWindow's afterSynchronizing signal to know when the content of the window has been displayed, and only act on it the first time (via if (!loader.item)).
When the signal is initially emitted, we can be sure that the BusyIndicator has started its animation, so the user will actually see a spinning icon.
Once the Loader has finished loading the text, its item property will become non-null and the BusyIndicator will disappear.

A: Run into the same problem today! I will assume you are controlling your BusyIndicator from a C++ property called busy. And you are setting busy to true just before your calculations and to false just after. Doing this solved it for me. It's not a very elegant solution but it works:
QML
BusyIndicator {
    running: CPPModule.busy
}

CPP
void CPPModule::setBusy(const bool &busy)
{
    m_busy = busy;
    emit busyChanged();
}
void CPPModule::InsertIntoDB()
{
    setBusy(true);
    QThread::msleep(50);
    QCoreApplication::processEvents();
    /*
    very Long Operation
    */
    setBusy(false);
}


text:
Q: create a link to download the file I have an input through which I upload files, put them in an array and display them in a loop. How to make sure that by clicking I can download a file that I uploaded and displayed in a loop? What should be in href ? or do you need to do something else ??
When I click link I get error file.
    {item.name}

.........................................................................................................................................................................
import React, {useState} from 'react';

import '../opros-page.scss';
import QuestionNewEntity from 'models/entity/QuestionNewEntity';

export interface TextResponseProps extends React.ComponentProps<'div'> {
  question: QuestionNewEntity;
  answerArray: any;
}

const Attachment: React.FC<TextResponseProps> = ({question, answerArray}) => {
  // console.log(question)

  const [array, setArray]: any = useState([]);
console.log(array)
  return (

      {question.title}

        {array.map((item: any, i: number) => {
          return

            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
              <g clip-path="url(#clip0)">
                <path
                  d="M18.3049 2.0953C16.1128 -0.0494691 12.6086 -0.0490026 10.4171 2.09636L1.22597 11.2875C-0.43597 12.9887 -0.404209 15.7149 1.29692 17.3769C2.97005 19.0115 5.64217 19.0115 7.31531 17.3769L15.638 9.05415C16.72 7.97218 16.72 6.21793 15.638 5.13596C14.5561 4.05399 12.8018 4.05399 11.7198 5.13596L3.75896 13.0968C3.48129 13.3843 3.48926 13.8425 3.77677 14.1201C4.05724 14.391 4.50185 14.391 4.78232 14.1201L12.7432 6.15928C13.2711 5.65355 14.109 5.67158 14.6147 6.19948C15.1051 6.71144 15.1051 7.51887 14.6147 8.03083L6.29199 16.3535C5.16766 17.4619 3.35768 17.4489 2.24934 16.3246C1.15219 15.2116 1.15219 13.4238 2.24934 12.3109L11.4405 3.11968C13.0777 1.48191 15.7325 1.48144 17.3702 3.11858C19.008 4.75571 19.0085 7.41057 17.3713 9.04834L8.18016 18.2395C7.87658 18.4995 7.84122 18.9564 8.1012 19.26C8.36119 19.5635 8.81806 19.5989 9.12164 19.3389C9.14996 19.3147 9.17634 19.2883 9.2006 19.26L18.3918 10.0688C20.5696 7.84297 20.5307 4.2731 18.3049 2.0953Z"
                  fill="#1FAF75"/>
              </g>
              <defs>
                <clipPath id="clip0">
                  <rect width="20" height="20" fill="white"/>
                </clipPath>
              </defs>
            </svg>
            {item.name} ({item.size}МБ)
            <button
              className="label-block-files__file-btn-delete"
              onClick={() => {
                setArray(array.filter((item: any, k: any) => i !== k));
                answerArray(question, array.filter((item: any, k: any) => i !== k));
              }}
            >
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 1.2L10.8 0L6 4.8L1.2 0L0 1.2L4.8 6L0 10.8L1.2 12L6 7.2L10.8 12L12 10.8L7.2 6L12 1.2Z"
                      fill="#F43649"/>
              </svg>
            </button>

        })}

      <button className="label-block__btn">
        <input
          type="file"
          onChange={(e: any) => {
            setArray([...array, e.target.files[0]]);
            answerArray(question, [...array, e.target.files[0]])
          }}
          multiple
        />
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
          <g clip-path="url(#clip0)">
            <path
              d="M18.3049 2.0953C16.1128 -0.0494691 12.6086 -0.0490026 10.4171 2.09636L1.22597 11.2875C-0.43597 12.9887 -0.404209 15.7149 1.29692 17.3769C2.97005 19.0115 5.64217 19.0115 7.31531 17.3769L15.638 9.05415C16.72 7.97218 16.72 6.21793 15.638 5.13596C14.5561 4.05399 12.8018 4.05399 11.7198 5.13596L3.75896 13.0968C3.48129 13.3843 3.48926 13.8425 3.77677 14.1201C4.05724 14.391 4.50185 14.391 4.78232 14.1201L12.7432 6.15928C13.2711 5.65355 14.109 5.67158 14.6147 6.19948C15.1051 6.71144 15.1051 7.51887 14.6147 8.03083L6.29199 16.3535C5.16766 17.4619 3.35768 17.4489 2.24934 16.3246C1.15219 15.2116 1.15219 13.4238 2.24934 12.3109L11.4405 3.11968C13.0777 1.48191 15.7325 1.48144 17.3702 3.11858C19.008 4.75571 19.0085 7.41057 17.3713 9.04834L8.18016 18.2395C7.87658 18.4995 7.84122 18.9564 8.1012 19.26C8.36119 19.5635 8.81806 19.5989 9.12164 19.3389C9.14996 19.3147 9.17634 19.2883 9.2006 19.26L18.3918 10.0688C20.5696 7.84297 20.5307 4.2731 18.3049 2.0953Z"
              fill="#1FAF75"/>
          </g>
          <defs>
            <clipPath id="clip0">
              <rect width="20" height="20" fill="white"/>
            </clipPath>
          </defs>
        </svg>
        Добавить
      </button>

  );
};

export default Attachment;

A: ok I found this solution
URL.createObjectURL(e.target.files[0])