text:
Q: Solving system of nonlinear equations numerically in python I want to solve the following problem numerically and first defined it as a function:
def F(x, na=1, nb=2, L=6, A=0.09, V=0.54, dh=0.03, k=10**-2, dB=0.005, fB=38, ur=0.39, rhoW=998, rhoG=1.2, g=9.81, pu=10**5, myW = 10**-3):

    #variables
    uWa = x[0]
    uWb = x[1]
    ta = x[2]
    tb = x[3]
    ea = x[4]
    eb = x[5]
    rhoa = x[6]
    rhob = x[7]
    ua = x[8]
    ub = x[9]
    pa0 = x[10]
    pb0 = x[11]
    Rea = x[12]
    Reb = x[13]
    lambdaa = x[14]
    lambdab = x[15]

    #nonlinear equations in form f=0:
    f = np.zeros(16)
    f[0] = ta - L/(ur+uWa)
    f[1] = tb - L/(ur-uWb)
    f[2] = ea - na*ta*fB*np.pi*dB**3/(6*V)
    f[3] = eb - nb*tb*fB*np.pi*dB**3/(6*V)
    f[4] = rhoa - rhoW + ea*(rhoW-rhoG)
    f[5] = rhob - rhoW + eb*(rhoW-rhoG)
    f[6] = rhoa*ua - ea*rhoG*(ur+uWa) - (1-ea)*rhoW*uWa
    f[7] = rhob*ub + eb*rhoG*(ur-uWb) - (1-eb)*rhoW*uWb
    f[8] = (-rhoa*ua + rhob*ub + rhoG*(na+nb)*fB*np.pi*dB**3/(6*A**2))*A
    f[9] = pb0 - pa0 - rhoa*rhob*(ua**2-ub**2)/(rhoa+rhob)
    f[10] = pa0 - pu - rhoa*((ua**2*lambdaa*dh*np.pi)/(8*A)+g)*L
    f[11] = pb0 - pu + rhob*((ub**2*lambdab*dh*np.pi)/(8*A)+g)*L
    f[12] = Rea - rhoa*ua*dh/myW
    f[13] = Reb - rhob*ub*dh/myW
    f[14] = lambdaa - fixpunktiteration(colebrook, 0.05, args=(Rea,k,dh))
    f[15] = lambdab - fixpunktiteration(colebrook, 0.05, args=(Reb,k,dh))

    return f

Following functions I defined for the equations f[14] and f[15]:
def colebrook(lam,args):
    Re, k, d = args
    return ( 1/(4*np.log10( 2.51/(Re*lam**0.5) + (k/d)/3.71 )**2) )

def fixpunktiteration(f,xalt,args,kmax=500,tol=1.e-7):
    for k in range(1,kmax):
        xneu = f(xalt,args)
        xdiff = xneu - xalt
        if abs(xdiff/xneu) < tol:
            break
        xalt = xneu
    else:
        xneu = None
    return xneu

Then I defined all the parameters and initial values of the function F and tried to solve with
fsolve (after importing it from scipy):
xinit = np.array([uWa_0, uWb_0, ta_0, tb_0, ea_0, eb_0, rhoa_0, rhob_0, ua_0, ub_0, pa0_0, pb0_0, Rea_0, Reb_0, lambdaa_0, lambdab_0])
loesung = fsolve(func=F,x0=xinit)

It works without error but it returns all initial values as solution which I don't understand. If I substitute f[14]=64/Rea the program gives a solution which is different from the initial values but physical nonsense. So I think the problem must have something to do with equations f[14] and f[15] or colebrook but I don't find it.


text:
Q: Mechanize: Follow links inside a div Whats the most pythonic way to make Mechanize follow links (br.follow_link) that are located inside a certain div? I know how to do it with a bit of help from BeautifulSoup but is there a way of doing it with Mechanize?
Sample div:

 1 |
 2 |
 3 |
 NEXT

A: I ran into similar problem recently and here is what i did
url = "www.somewhere.com"
br = mechanize.Browser()
br.open(url)

encoded_data = UnicodeDammit(br.response().read(),isHTML=True).unicode
parser = lxml_html.fromstring(encoded_data)

soup_xpath = "//div[@id='BODYCON']//a/@href"
valid_links = soup.xpath(soup_xpath)
links  = [ link for link if link.url in valid_links ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sails.js rolling sessions A rolling session is a session that expires in a set amount of time should there be no user activity(excluding websockets live updating data). If the user visits another part of the site before expiry, the expiry should then be extended. How would I do this with Sails.js? Setting maxAge and expires under cookie in /config/session.js does not have the desired effect. The expiry does not get extended with another page load. It stays constant.
EDIT: Will this be resolved once Sails.js upgrades its Express version? I see https://github.com/expressjs/session has a rolling option.
EDIT2: I see this answer: ExpressJS session expiring despite activity Would I need to copy and paste
req.session._garbage = Date();
req.session.touch();

onto each route in the controller? Is there a better way?

A: Changing the Express dependency in Sails is not something we take lightly.  But in the meantime, you can handle this in a couple of ways, depending on the conditions you'd like to trigger the cookie refresh:

*

*If you only need the refresh to happen when a controller action is run, you can put your code in a global policy.  This won't apply to routes that are mapped directly to views, or to static assets.

config/policies:
'*': 'refreshSessionCookie'

api/policies/refreshSessionCookie:
module.exports = function(req, res, next) {
    req.session._garbage = Date();
    req.session.touch();
    return next();
}

*

*If you want the refresh to happen any time a user with a session makes a request for anything, be it a controller, view or static asset, you can put the code in custom middleware that will run for every request.

config/http.js:
middleware: {

    refreshSessionCookie: function(req, res, next) {
        req.session._garbage = Date();
        req.session.touch();
        return next();
    },

    order: [
      'startRequestTimer',
      'cookieParser',
      'session',
      'refreshSessionCookie', // <-- your custom middleware
      'bodyParser',
      'handleBodyParserError',
      'compress',
      'methodOverride',
      'poweredBy',
      '$custom',
      'router',
      'www',
      'favicon',
      '404',
      '500'
    ]
}


text:
Q: How to alter database on the linked server WITHOUT SYSADMIN rights? My requirement is that user performing alter CANNOT be sysadmin (it can have all other rights but not sysadmin).
I am running a query from local server which should modify a remote one
EXEC ('ALTER DATABASE REMOTEDB MODIFY FILEGROUP ftfg_REMOTEDB NAME=ftfg_REMOTEDB') at [REMOTESERVER]

This query works once I add sysadmin right to the user but without the right, it give the following error:
The server principal "USERWITHOUTSYSADMIN" is not able to access the database "REMOTEDB" under the current security context.

I am on SQL Serve 2008.
Please Help!

A: After much research: This is not possible:(

A: Put the EXEC command in a stored procedure and grant execute on the procedure to the user. It won't STOP a sysadmin from executing it, but it will allow others to execute it as well. Be VERY, VERY careful with this!

A: Can you allow the user to impersonate someone with the appropriate permissions?
EXEC ('ALTER DATABASE REMOTEDB MODIFY FILEGROUP ftfg_REMOTEDB NAME=ftfg_REMOTEDB')
    AS USER = 'UserWithAppropriatePermissions'
    AT [REMOTESERVER]


text:
Q: Pandas JSON Orient Autodetection I'm trying to find out if Pandas.read_json performs some level of autodetection. For example, I have the following data:
data_records = [
    {
        "device": "rtr1",
        "dc": "London",
        "vendor": "Cisco",
    },
    {
        "device": "rtr2",
        "dc": "London",
        "vendor": "Cisco",
    },
    {
        "device": "rtr3",
        "dc": "London",
        "vendor": "Cisco",
    },
]

data_index = {
    "rtr1": {"dc": "London", "vendor": "Cisco"},
    "rtr2": {"dc": "London", "vendor": "Cisco"},
    "rtr3": {"dc": "London", "vendor": "Cisco"},
}

If I do the following:
import pandas as pd
import json

pd.read_json(json.dumps(data_records))
---
  device      dc vendor
0   rtr1  London  Cisco
1   rtr2  London  Cisco
2   rtr3  London  Cisco

though I get the output that I desired, the data is record based. Being that the default orient is columns, I would have not thought this would have worked.
Therefore is there some level of autodetection going on? With index based inputs the behaviour seems more inline. As this shows appears to have parsed the data based on a column orient by default.
pd.read_json(json.dumps(data_index))

          rtr1    rtr2    rtr3
dc      London  London  London
vendor   Cisco   Cisco   Cisco

pd.read_json(json.dumps(data_index), orient="index")

          dc vendor
rtr1  London  Cisco
rtr2  London  Cisco
rtr3  London  Cisco

A: We can't speak of auto-detection, but rather of a nested hierarchical structure determined by a specified orientation or by the one used by default.
Moreover, it should be specified that we cannot use any data structure with a given orientation.
Case 1 : Dataframes to / from a JSON string
read_json : Convert a JSON string to Dataframe with argument typ = 'frame'
to_json : Convert a DataFrame to a JSON string
Orient value is explicitly specified with the Pandas to_json and read_json functions in case of split, index, record, table and values orientations.
This is not necessary to specify orient value for columns because orientation is columns by default.
Case 2 : Series to / from a JSON string
read_json : Convert a JSON string to Series with argument typ = 'series'
to_json : Convert a Series to a JSON string
If typ = series in read_json, default value for argument orient is index  see Pandas documentation
When trying to convert a Series into a JSON string using to_json, default orient value is also index.
With the other allowed orientation values for a Series split, records, index, table argument orient must be specified.
Resources
We have some oriented structures in the comment section at this github link (have a look around line 680 in the _json.py file).
Note that there are no examples with orient=columns in the code comments on git-hub.
This is simply because in the absence of an orientation specification, columns is used by default.
Clearer view of a nested hierarchical structure
import pandas as pd
import json

##### BEGINNING : HIERARCHICAL LEVEL #####

# Second Level - Values levels
d21 = {'v1': "value 1", 'v2': "value 3"}
d22 = {'v1': "value 3", 'v2': "value 4"}

# First Level - Rows levels
d1 = {'row1': d21, 'row2': d22}

# 0-Level - Columns Levels
d = {'col1': d1}

##### END : HIERARCHICAL LEVEL #####

print(pd.read_json(json.dumps(d))) # No need for specification : orient is columns by default

#                                     col1
# row1  {'v1': 'value 1', 'v2': 'value 3'}
# row2  {'v1': 'value 3', 'v2': 'value 4'}

Be careful here
Data structures cannot be used with any value given to the orient argument. Otherwise, a builtins.AttributeError exception should be raised (see the github link to see the diffrent structures).
pd.read_json(json.dumps(data_records))
#   device      dc vendor
# 0   rtr1  London  Cisco
# 1   rtr2  London  Cisco
# 2   rtr3  London  Cisco

#### Like orient is columns by default the previous is the same as following
pd.read_json(json.dumps(data_records), orient='columns')
#   device      dc vendor
# 0   rtr1  London  Cisco
# 1   rtr2  London  Cisco
# 2   rtr3  London  Cisco

pd.read_json(json.dumps(data_records), orient='values')
#   device      dc vendor
# 0   rtr1  London  Cisco
# 1   rtr2  London  Cisco
# 2   rtr3  London  Cisco

#### Dataframe shape is also important and exception could be raised

pd.read_json(json.dumps(data_records), orient='index')
# ...
# builtins.AttributeError: 'list' object has no attribute 'values'

pd.read_json(json.dumps(data_records), orient='table')
# builtins.KeyError: 'schema'

pd.read_json(json.dumps(data_records), orient='split')
# builtins.AttributeError: 'list' object has no attribute 'items'

Is there an autodetection mechanism ?
After some experimentations I can say now answer is no.
On github, split data shape is presented like the following :
data = {\
"columns":["col 1","col 2"],\
"index":["row 1","row 2"],\
"data":[["a","b"],["c","d"]]\
}

So let's do an experiment.
We will use read_json to read the data without filling in the orientation and see if the split shape is recognized.
Then we will read the data by entering the split orientation.
If there is an automatic shape recognition, the result should be the same in both cases.
import pandas as pd
import json

data = {\
"columns":["col 1","col 2"],\
"index":["row 1","row 2"],\
"data":[["a","b"],["c","d"]]\
}

json_string = json.dumps(data)

we print without filling in the orientation :
>>> pd.read_json(json_string)
  columns  index    data
0   col 1  row 1  [a, b]
1   col 2  row 2  [c, d]

and now we print with filling in the split orientation.
>>> pd.read_json(json_string, orient='split')
      col 1 col 2
row 1     a     b
row 2     c     d

Dataframes are different, Pandas do not recognize the split shape. There is no automatic detection mechanism.

A: TL;DR
When using pd.read_json() with orient=None, the representation of the data is automatically determined through pd.DataFrame().
Explanation
The pandas documentation is a bit misleading here. When not specifying orient, the parser for 'columns' is used, which is self.obj = pd.DataFrame(json.loads(json)). So
pd.read_json(json.dumps(data_records))

is equivalent to
pd.DataFrame(json.loads(json.dumps(data_records)))

which again is equivalent to
pd.DataFrame(data_records)

I.e., you pass a list of dicts to the DataFrame constructor, which then performs the automatic determination of the data representation. Note that this does not mean that orient is auto-detected. Instead, simple heuristics (see below) on how the data should be loaded into a DataFrame are applied.
Loading JSON-like data through pd.DataFrame()
For the 3 most relevant cases of JSON-structured data, the DataFrame construction through pd.DataFrame() is:

*

*Dict of lists

In[1]: data = {"a": [1, 2, 3], "b": [9, 8, 7]}
  ...: pd.DataFrame(data)
Out[1]:
   a  b
0  1  9
1  2  8
2  3  7

*Dict of dicts

In[2]: data = {"a": {"x": 1, "y": 2, "z": 3}, "b": {"x": 9, "y": 8, "z": 7}}
  ...: pd.DataFrame(data)
Out[2]:
   a  b
x  1  9
y  2  8
z  3  7

*List of dicts

In[3]: data = [{'a': 1, 'b': 9}, {'a': 2, 'b': 8}, {'a': 3, 'b': 7}]
  ...: pd.DataFrame(data)
Out[3]:
   a  b
0  1  9
1  2  8
2  3  7

A: If you want to understand every detail of a function call, I would suggest using VSCode and setting "justMyCode": false in your launch.json for debugging.
That being said, if you follow what's going on when you call pd.read_json() you'll find out that it instantiates a JsonReader, before reading it which then instantiates a FrameParser in turn parsed with _parse_no_numpy:
def _parse_no_numpy(self):
  json = self.json
  orient = self.orient

  if orient == "columns": # default
      self.obj = DataFrame(
          loads(json, precise_float=self.precise_float), dtype=None
      )
  elif orient == "split":
      decoded = {
          str(k): v
          for k, v in loads(json, precise_float=self.precise_float).items()
      }
      self.check_keys_split(decoded)
      self.obj = DataFrame(dtype=None, **decoded)
  elif orient == "index": # your second case
      self.obj = DataFrame.from_dict(
          loads(json, precise_float=self.precise_float),
          dtype=None,
          orient="index",
      )
  elif orient == "table":
      self.obj = parse_table_schema(json, precise_float=self.precise_float)
  else:
      self.obj = DataFrame(
          loads(json, precise_float=self.precise_float), dtype=None
            )

As you can see, like stated in a previous answer, in terms of orientation:
pd.read_json(json.dumps(data_records))

is equivalent to
pd.DataFrame(data_records)

and
pd.read_json(json.dumps(data_index), orient='index')

to
pd.DataFrame.from_dict(data_index, orient='index')

So in the end it all boils down to how pd.DataFrame handles the passed list of dict.
Going down this hole, you'll find that the constructor checks if the data is list-like and then calls nested_data_to_arrays which in turn calls to_arrays that finally calls _list_of_dict_to_arrays:
def _list_of_dict_to_arrays(
    data: list[dict],
    columns: Index | None,
) -> tuple[np.ndarray, Index]:
    """
    Convert list of dicts to numpy arrays

    if `columns` is not passed, column names are inferred from the records
    - for OrderedDict and dicts, the column names match
      the key insertion-order from the first record to the last.
    - For other kinds of dict-likes, the keys are lexically sorted.

    Parameters
    ----------
    data : iterable
        collection of records (OrderedDict, dict)
    columns: iterables or None

    Returns
    -------
    content : np.ndarray[object, ndim=2]
    columns : Index
    """
    if columns is None:
        gen = (list(x.keys()) for x in data)
        sort = not any(isinstance(d, dict) for d in data)
        pre_cols = lib.fast_unique_multiple_list_gen(gen, sort=sort)
        columns = ensure_index(pre_cols)

    # assure that they are of the base dict class and not of derived
    # classes
    data = [d if type(d) is dict else dict(d) for d in data]

    content = lib.dicts_to_array(data, list(columns))
    return content, columns

The "autodetection" is actually the hierarchical handling of all possible cases/types.

A: No, Pandas does not perform any autodetection when using the read_json function.
It is entirely determined by the orient parameter, which specifies the format of the input json data.
In your first example, you passed the data_records list to the json.dumps function, which is then converted it to a json-string. After passing the resulting json string to pd.read_json, it is seen as a  record orientation.
In your second example, you passed the data_index to json.dumps which is thenseen as a "column" orientation
In both cases, the behavior of the read_json function is entirely based on the value of the orient parameter and not by an automatic detection by Pandas.


text:
Q: How to get value from a resolved JavaScript promise? Let's say I have a promise p. I have the following code:
var entries = getEntries();

var getEntries = function() {
    ...SOME_CODE...
    return p.then(function(result) {
        return result;
    });
}

Using the debugger, I can see that result has the data that I want. How can I save it to the global variable entries (getEntries() currently returns an undefined value)?


text:
Q: UnitTest reports SQL error - cant find data type I use this code:
using (var unitOfWork = this.unitOfWorkFactory.Create())
{
    var tagParam = new SqlParameter
                       {
                           ParameterName = "@tagList",
                           SqlDbType = System.Data.SqlDbType.Structured,
                           Value = tags.ToTVP(),
                           TypeName = "[dbo].[TagList]"
                       };

    unitOfWork.Context.Database.ExecuteSqlCommand("exec sp_InsertTagList @tagList", tagParam);
    // unitOfWork.Context.Database.ExecuteSqlCommand("INSERT INTO dbo.Tags SELECT Name FROM @tagList", tagParam);
}

ToTvp is just an extension method making a DataTable for me from a list of items.
I get this error:

Test method InspiredBlog.UnitTests.UnitTest1.TestMethod1 threw
  exception:  System.Data.SqlClient.SqlException: Column, parameter, or
  variable @tagList. : Cannot find data type dbo.TagList.

I have created the table type in the my database.
CREATE TYPE TagList AS TABLE
(
    Name VARCHAR(MAX)
)
GO

I don't know why this error is coming back!
I can easily create a SQL query and execute within SSMS


text:
Q: .NET 4.5.2 conditions in a Wix bundle I'm working on a Wix project to learn more about Wix. I'm trying to configure my Wix bundle to detect and install .NET 4.5.2 but I'm a little confused. I've seen a lot of examples where the registry is checked but I wanted to know if I can do something like this:
<Chain>
    <PackageGroupRef Id="NetFx452Redist" />

    <ExePackage Id="Netfx452"
                Cache="no"
                Compressed="yes"
                PerMachine="yes"
                Permanent="yes"
                Vital="yes"
                InstallCommand="/q /norestart"
                SourceFile="$(var.ProjectDir)Resources\NDP452-KB2901907-x86-x64-AllOS-ENU.exe"
                DetectCondition="NetFx452"
                InstallCondition="NOT NetFx452" />
    <MsiPackage Id="ShittyMsi"
                SourceFile="$(var.MyInstaller.TargetDir)"
                Name="$(var.MyInstaller.TargetFileName)" />
</Chain>

If I can't do this and I need to check the registry, how do I know what I need to be looking for in the registry?

A: You're already using <PackageGroupRef Id="NetFx452Redist" /> so you don't need to check the registry; the package group already takes care of checking the registry and setting the right attributes.


text:
Q: WP: How to get the id of certain post by title I would like to get the id of a post by title.
The script below shows the content of a post by id.
  $content_post = get_post($postID);
  $content = $content_post->post_content;

  return apply_filters('the_content', $content);

My goal is to use the title as parameter in order to get the related id.

A: Can you please check this code?
$page = get_page_by_title(' Your page title '); // enter your page title

$pageID = $page->ID;

echo $pageID;

for more information you can refer this link get_page_by_title ?

A: You can use get_page_by_title. You may have more than one post with the same name so that may return more than one entry.

A: Description
Retrieves a post given its title. If more than one post uses the same title, the post with the smallest ID will be returned.
Because this function uses the MySQL '=' comparison the $page_title will usually be matched as case insensitive with default collating.
Usage
<?php
 get_page_by_title( $page_title, $output, $post_type );
?>

Parameters
$page_title
(string) (required) Page title
Default: None

 $output
 (string) (optional) Output type. OBJECT, ARRAY_N, or ARRAY_A.
 Default: OBJECT

$post_type
(string) (optional) Post type like 'page', 'post', 'product' etc.
Default: page

Return Values
(mixed)
OBJECT, ARRAY_N, or ARRAY_A.

NULL when no posts found.
Check it out on wordpress codex.
Another way of doing this is as follows.
The problem
The function converts a post / page name to a post /page ID.
function get_id_by_post_name($post_name)
{
    global $wpdb;
    $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'");
    return $id;
}

Function call
Call the function somewhere in your theme.
<?php echo get_id_by_post_name('my-post-name'); ?>


text:
Q: What is the difference between scipy.interpolate.rbf and matplotlib.pyplot.contourf? I have 3 columns of data in a csv file with which I intend to create a contour map. These three columns are not grid data.
Initially, I created grid data using the following function:
def grid(x, y, z, resX=100, resY=100):
  xi = linspace(min(x), max(x), resX)
  yi = linspace(min(y), max(y), resY)
  Z = griddata(x, y, z, xi, yi, interp='linear')
  X, Y = meshgrid(xi, yi)
  return X, Y, Z

Then I imported the data, prepared it and passed it to the function.
X, Y, Z = grid(x, y, z)
contour = plt.contourf (X, Y, Z)

I got the following image Contour 1 using matplotlib.pyplot.contourf.
Now I tried creating a similar contour map using a code snippet I found online using scipy.interpolate.rbf and it looks like this Contour 2.
xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
xi, yi = np.meshgrid(xi, yi)

rbf = scipy.interpolate.Rbf(x, y, z, function='linear')
zi = rbf(xi, yi)

plt.imshow(zi)

What is the difference between the rbf function and contour function? For the same data, the rbf function is creating a fully occupied contour map whereas the contourf function is only plotting the data at (x,y) -> z.
I am looking to create a fully occupied plot like the one created by rbf but it doesn't work with large data as I get the following error
LinAlgError: Matrix is singular.


text:
Q: Error creating SQLite table after DROP I've got about 50 devices running my application. Some users expirience a strange error (not all):
android.database.sqlite.SQLiteException: no such table: points (code 1)
at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method)
at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:840)
at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:143)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:197)
at android.database.AbstractCursor.moveToNext(AbstractCursor.java:245)
at kgk_logic.Manager.reloadPoints(Manager.java:67)
at mobile.WorkActivity$WHandler.handleMessage(WorkActivity.java:544)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5124)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:783)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:550)
at dalvik.system.NativeStart.main(Native Method)

The logic is: once in 15 mins device checks its location and compares with remote bd data/ If device in specific radius - server returns a list of points (just coords). These points go to the SQLTable "points", but before that previus points table is dropped and new one created with new fresh data:
DB db = DB.getInstance(KGKMobile.getAppContext());
SQLiteDatabase wdb = db.getWritableDatabase();
wdb.execSQL(String.format("DROP TABLE %s", DB.POINTS_TABLE));
db.createPointsTable(wdb);

for (KGKPoint point : WorkActivity.getManager().getPoints()) {
    wdb.insert(DB.POINTS_TABLE, null, point.getCV());
}

Method createPointsTable() contains only one query:
execSQL(String.format("CREATE TABLE %s (id integer PRIMARY KEY NOT NULL, name TEXT NOT NULL, lat real NOT NULL, lng real NOT NULL, code TEXT )", "points"));

My bet - table dropped but not created properly. But i don't know why. Or maybe there is another reason?


text:
Q: Django Transaction managed block ended with pending COMMIT/ROLLBACK when checking perms I'm getting this error Transaction managed block ended with pending COMMIT/ROLLBACK whenever I try to check for permissions in the template whose corresponding view has a @transaction.commit_manually decorator.
template:
<!-- html stuff -->
{% if perms.myApp.add_table1 %}
    {# show html elements #}
{% endif %}

Once I remove the permissions condition, no errors are present. Non permissions related if conditions are okay, e.g. {% if user.is_superuser %}{% endif %}
UPDATE: even if the the permissions checking is not on the template that the view renders, but was extended from, it still has this error.
e.g. permission checking in nav_bar.html, and view renders expense.html which extends nav_bar.html would cause the same error.
view.py:
@transaction.commit_manually
def add_expense(request):
    # do stuff here

i've tried removing the decorator and there is no exceptions of any kind, everything works. But when I put the decorator on, error occurs
urls.py:
# other stuff omitted
(r'^myApp/expenses/add/$', add_expense),

UPDATE #2:
When the user is a superuser, there's no problem as well. I believe that is because it doesn't bother checking the permissions since the user is a superuser
Also I've included code
@login_required()
@transaction.commit_manually
def add_expense(request):

    request.session.set_expiry(1800)

    if request.method == 'POST':
        form_input = AddExpense(request.POST)

        if form_input.is_valid():
            try:
            # after validation data is cleaned
                cd = form_input.cleaned_data
                # cleaned data is a dictionary
                input_date = date.today()
                user = request.user.username

                new_record = table1.objects.create(
                    amount = cd['amount'],
                    date = cd['date_of_expense'],
                    username = user
                    )
                new_record.save()
                transaction.commit()
                return render_to_response('forms/add_expense_success.html', context_instance=RequestContext(request))
            except Exception, e:
                pass
                transaction.rollback()
                return HttpResponse(None)
        else:

            return render_to_response('forms/add_expense.html', {'form': form_input},
                              context_instance=RequestContext(request))
    else:
        # loading this gives error, not sure the top part
        form = AddExpense()
        return render_to_response('forms/add_expense.html', {'form': form, 'page_title': '新增支出'},
                      context_instance=RequestContext(request))

A: Just to confirm what the error message implies, you're on Postgres, right?
If so, one suggestion: in your # do stuff here block, above, I'll bet that you're not manually committing after reads even if you are after writes.
As of Django 1.3, transaction-managed reads are counted as dirty - not just writes - so you'll need to commit() after those, too.
See the release notes for more detail.

A: It cause by  context_instance=RequestContext(request),
see the solution down here by @Marcin
Django Transaction managed block ended with pending COMMIT/ROLLBACK

A: i get this error message while trying to reduce permissions for the accessing user.

*

*postgresql 9.1`

*python 2.7.3

*django 1.3.1

if running as superuser (admin role) no problem at all, if running as user (user role) the error comes up.
the user has all (even grant) rights on all django related tables and even on the database and schema too but it still gives the error.
what could cause this? so far i could debug this, its just superuser rights missing, else superuser and user have same rights.
code:
@login_required
@transaction.commit_manually
def sipuser_add(request, extension_id):
    member = members.objects.get(nickname=request.user.username)
    extension = extensions.objects.get(id=extension_id)
    nickname = request.user.username
    if extension.id_members.nickname == member.nickname:
        from django.db import connection
        cursor = connection.cursor()
        secret = pwgen()
        cursor.execute("SELECT func_create_sipuser('%s','%s',%s)" % (nickname, secret, extension_id) )
        ret = cursor.fetchone()
        logger.debug("created extension_id: %s - stored procedure 'func_create_sipuser' returned: %s" % (extension_id, ret) )
        pin = 1234
        timeout = 15
        cursor.execute("SELECT func_create_voicemail_from_phonenumberid(%s,'%s',%s)" % (extension_id, pin, timeout) )
        ret = cursor.fetchone()
        logger.debug("created voicemail for extension_id %s - stored procedure 'func_create_voicemail' returned: %s" % (extension_id, ret) )
        cursor.close() # is this needed and/or on the right position called?
        connection.commit()
    return HttpResponseRedirect('/extensions/')


text:
Q: geolocation game event on marker approach I need some information, I wan't to create a simple game with a geolocation API, I have looked at: Google Map API, MapBox.
I wan't to have the actual location of the user, he can see the map around him (like Pokemon GO), I can put a marker at 10 meters for example, when he approach the marker with his phone, I do an event, a popup appear, and he won a score is increased.
How can I do that ?

A: Mapbox SDK is versatile and allows for 'MapViews' inside of your own application's activity.
The have a great amount of information inside their docs. I'd say to start with their introduction apps and work your way up once you are familiar.
Ideas:

*

*You could customize the user location icon to be the player and use the proximity controls around the users fine location to reach goals/tasks.

*You could then have pins on the MapView that the user's location can interact with


text:
Q: Asp Net MySql Connection with Entity Framework In my project I had MySql.Data.Entity.6.10.8 with MySql.Data.8.0.13.
I saw this post: dbconnection-to
And uninstalled MySqlData.Entity.6.10.8 and installed mySql.Data.EntityFramework.
My project now is with all 8 versions :
<package id="MySql.Data" version="8.0.13" targetFramework="net46" />
  <package id="MySql.Data.EntityFramework" version="8.0.13" targetFramework="net46" />
  <package id="MySql.Data.EntityFrameworkCore" version="8.0.13" targetFramework="net46" />
  <package id="MySql.Data.EntityFrameworkCore.Design" version="8.0.13" targetFramework="net46" />

But, in web.config file I need a ef providers configuration and I got this from MySql:
    <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
        <provider invariantName="MySql.Data.MySqlClient"
            type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
        <provider invariantName="System.Data.SqlClient"
            type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>

And I got this error:
The Entity Framework provider type 'MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6' registered in the application config file for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient' could not be loaded.

How can I change this ef provider configuration? Or I need to install another package?
I tried to change to:
<provider invariantName="MySql.Data.MySqlClient"
            type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework"/>

And I received an error: "Unknow host"


text:
Q: Problem assigning output of a command to a variable I have written a script that uses the below to display the amount of characters in "$var1"
echo -n "$var1" | wc -c

This displays the numeric value without an issue. However rather than display the value I wish to assign it to a the variable $char in order to then apply various conditions.
char=$(-n "$var1" | wc -c)
echo $char

However this produces the following error.
-n: command not found


text:
Q: SQL Server T-SQL Rows to Columns I am not sure If I'm doing it correctly but my requirement was to create a view display rows into columns using TSQL. Column number is fixed. Rows will never exceed the number of columns.
Limit in Col2 is 3. No limit in Col 1.
Currently my SQL is using OFFSET AND FETCH but it seems its always returning a total of 1 row.
 SELECT Col1, Col2 FROM Table2 WHERE Col1 IN (SELECT Col FROM Table1) ORDER BY Col2 ASC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY

Table 1

A

B

C

D

Table 2 Col 1
Table 2 Col 2

A
A1

A
A2

A
A3

B
B1

Output Col 1
Output Col 1
Output Col 2
Output Col 3

A
A1
A2
A3

B
B1
NULL
NULL

C
NULL
NULL
NULL

D
NULL
NULL
NULL

Thanks you.

A: I would, personally, use conditional aggregation for this, which would look a little like this:
SELECT T1.[Table 1] AS [Output Col 1],
       MAX(CASE [Table 2 Col 2] WHEN T1.[Table 1] + '1' THEN [Table 2 Col 2] END) AS [Output Col 1],
       MAX(CASE [Table 2 Col 2] WHEN T1.[Table 1] + '2' THEN [Table 2 Col 2] END) AS [Output Col 2],
       MAX(CASE [Table 2 Col 2] WHEN T1.[Table 1] + '3' THEN [Table 2 Col 2] END) AS [Output Col 3]
FROM dbo.YourFirstTable T1
     LEFT JOIN dbo.YourSecondTable T2 ON T1.[Table 1] = T2.[Table 2 Col 1]
GROUP BY T1.[Table 1];

A: As response to Larnu's answer, [added Table 2 Col 3] that can be used on sorting. Sorry don't know it exists.
Also after using Larnu's answer I came up with the following SQL which is I think good enough for my requirement. Big thanks to Larnu's help.
SELECT
T1.[Table 1] AS [Output Col 1],
(SELECT [Table 2 Col 2] FROM  dbo.YourSecondTable WHERE  dbo.YourSecondTable.[Table 2 Col 1]=T1.[Table 1] ORDER BY dbo.YourSecondTable.[Table 2 Col 3] OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY) AS [Output Col 1],
(SELECT [Table 2 Col 2] FROM  dbo.YourSecondTable WHERE  dbo.YourSecondTable.[Table 2 Col 1]=T1.[Table 1] ORDER BY dbo.YourSecondTable.[Table 2 Col 3] OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY) AS [Output Col 2],
(SELECT [Table 2 Col 2] FROM  dbo.YourSecondTable WHERE  dbo.YourSecondTable.[Table 2 Col 1]=T1.[Table 1] ORDER BY dbo.YourSecondTable.[Table 2 Col 3] OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY) AS [Output Col 3]
FROM dbo.YourFirstTable T1
LEFT JOIN dbo.YourSecondTable T2 ON T1.[Table 1] = T2.[Table 2 Col 1]
GROUP BY T1.[Table 1];

A: since you have an unknown number of columns (I believe that SQL Server limits to columns is 1000) I would build a dynamic "pivot" using dynamic SQL somthing like this:
DROP TABLE IF EXISTS table_1
DROP TABLE IF EXISTS table_2
CREATE TABLE table_1([Col 1] VARCHAR(2) )
CREATE TABLE table_2([Col 1] VARCHAR(2) , [col 2] VARCHAR(2))

TRUNCATE TABLE Table_1
TRUNCATE TABLE Table_2
INSERT INTO TABLE_1([col 1])  VALUES ('A'),('B'),('C'),('D')
INSERT INTO TABLE_2([col 1], [col 2])
VALUES ('A','A1'),('A','A2'),('A','A3'),('B','B1')
DROP TABLE IF EXISTS #Dict

;WITH cte1 AS (
    SELECT DISTINCT [col 1] , [col 2]
    FROM table_2
), cte2 AS (
SELECT [col 1], [col 2], ROW_NUMBER() OVER (PARTITION BY [Col 1] ORDER BY [Col 1],[col 2]) ColId
FROM cte1
)
SELECT DISTINCT *
INTO #Dict
FROM cte2
WHERE ColId < 999
--select * from #Dict

DROP TABLE IF EXISTS #Pivot
DECLARE @SQLCmdCreate NVARCHAR(max) = 'CREATE TABLE #Pivot ([Table_1 Col 1] VARCHAR(2), '
DECLARE @SQLCmdInsert NVARCHAR(max) = 'INSERT INTO #Pivot ( [Table_1 Col 1], '
DECLARE @SQLCmdSelect NVARCHAR(max) = 'SELECT Table_1.[Col 1], '
DECLARE @SQLCmd       NVARCHAR(max)
DECLARE @q NCHAR(1) = ''''
DECLARE @crlf NCHAR(2) = CHAR(13)+ CHAR(10)
SELECT @SQLCmdCreate += STRING_AGG(CONCAT('[Output ', ColId, '] VARCHAR(2)'), ',')
     , @SQLCmdInsert += STRING_AGG(CONCAT('[Output ', ColId, ']'), ',')
     , @SQLCmdSelect += STRING_AGG(CONCAT(@crlf, 'MIN(CASE WHEN [ColId] = ', [ColId], ' THEN Dict.[Col 2] END) '), ',')
FROM (
    SELECT DISTINCT TOP 100 PERCENT ColId FROM #Dict ORDER BY ColId
) dict

SELECT @SQLCmdCreate+= ')'
   , @SQLCmdInsert += ')'
   , @SQLCmdSelect += @crlf + 'FROM Table_1 '
                    + 'left join #Dict dict '
                    + '    on  Dict.[Col 1] = Table_1.[Col 1]'
                    + @crlf + 'GROUP BY table_1.[Col 1]'

SELECT @SQLCmd = @SQLCmdCreate + @crlf  + @SQLCmdInsert +  @crlf + @SQLCmdSelect + @crlf + 'SELECT * FROM #Pivot ORDER BY [Table_1 Col 1]'
--print @SQLCmd
EXEC (@SQLCmd)


text:
Q: Ubuntu: Unable to mount NFS share I have an NFS share and an iSCSI target on my NAS. I'm trying to mount either of them on my Ubuntu 18.04 VM. I'm using Hyper-V for the hypervisor. I can connect to both the NFS and iSCSI on the Windows 10 host but cannot connect to either of them from Ubuntu. I keep getting timeouts. I've disabled the firewall and anti-virus software on the host machine with no progress.
The virtual machine is using a bridged connection and can ping internal IP's and external websites just fine. The VM can also ping the NAS but cannot SSH into it.
What steps should I try to troubleshoot this? The NAS is a QNAP T-431.


text:
Q: Current from different batteries in parallel This is a question in my schoolwork that I dont quite know how to approach, I appreciate the help!

simulate this circuit – Schematic created using CircuitLab
How can i show that ? A = 10 A?
Thanks!

A: This can be solved by simple inspection.

*

*You are given that V1 supplies 25A. Therefore the voltage drop over the battery internal resistance R1 is V=IR --> 0.1 * 25 --> 2.5V.

*The voltage across R3 is 13.5 - 2.5 = 11V

*The current through R2 is (13 - 11)/0.2 = 10A

*The value of R3 is R=V/I --> 11/(25 +10) = 0.314 Ohms

A: There are 5 parts with 1 unknown (R) and 4 given values.
There are 3 KVL Loops and 1 KCL Nodes with 1 of 3 branch currents known.
So there with 2 unknown currents and 1 unknown component value, there is sufficient info to compute 2 unknowns. R & I(R2)

*

*such that I(R1) will draw 25 A in the top branch and prove that I(R2) draws 10A.

Begin with KVL ,KCL and use reduction.
KVL:

*

*V load  = \$13.5~_V -25~_A*0.1~ _Ω=11  ~V \$

*V load  = \$ 13~_V-I_2*0.2~_Ω\$

*V load = \$I_3*R?\$
KCL:
\$25~A+I_2=I_3\$
Solve for I2 from 1. & 2. then 3.


text:
Q: Hard drive partitions destroyed by FileVault Short summary: User attempted to decrypt FileVault protection and got impatient; now can't get hard drive working at all. No file recovery needed (good backup, thank God), just need to get the hard drive to the point where I can actually work with it.
I have another system with a similar 1 TB drive, and used gpt to manually copy its partition scheme to the problem drive; it won't mount (from klanomoath's assistance to another user).
Also tried initializing the disk using Windows (NTFS); partially successful. It almost looks like FileVault somehow still has hold of the drive, even though everything, including the partition map, has been overwritten. Can't figure out how to just write enough of a format onto the drive so that Disk Utility has a place to start.
I just need to get this drive working, and don't care what data is destroyed. Can anyone tell me what I'm missing?

A: I would highly recommend using Disk Maker X to create a bootable USB disk to reinstall OS X/macOS. Here's what you'll need:

*

*Another Mac with access to the App Store (if the one you're trying to fix doesn't function enough to complete the following steps.

*A USB drive/stick with a capacity of at least 8 GB. Also be sure it has absolutely no data on it, since it will be formatted.

*An internet connection in order to download Disk Maker X.

First, download macOS Sierra on whichever Mac you're using by searching for it on the App Store, but don't install it! Next, download and install Disk Maker X on whichever Mac you're using. Then, open Disk Maker X and follow the steps listed. After that, make sure the Mac you're trying to fix is off. Plug in the USB Stick, then press Option and press the power key. Select the USB disk in the window that loads, follow the setup process, and you should be good to go! Let me know if you have any questions.

A: There's always the brute force method. This should clear anything and everything on the drive no matter what Filevault or anything else did to it.

*

*Connect the drive to a working machine. Mac or Linux, either will work here, but we'll continue as if on a mac. This should also work from inside the installer, as you can get to both Disk Utility and a terminal from there.

*Open Disk Utility, and note down which device the drive is using. On my personal system, this looks like:

And the device name is "disk0" as shown on the bottom right. Make sure you have the main drive, not anything else under it. (That is, the drive itself, not any partitions). In my image, that's the "Crucial LGT.." not "Macintosh HD"

*Open Terminal.

*In your Terminal, become root with sudo su - and entering a password

*Make sure you've closed disk utility - we're about to confuse it.

*Run: dd if=/dev/zero of=/dev/DEVICENAME bs=1M
For the love of all things holy, make sure you get the device name right.
This will take a long time, but should throughly zero out the contents of the drive to allow it to be used with anything else.
Once this process finishes, reboot the machine. The drive should now be usable.


text:
Q: Add New Record Button Access I have a form in Access where I'd like to create a button that adds a new record with information to the table.
I think part of the issue is the way I'd like the user to interact with the form.
From any given record I'd like the user to be able to use that record for data entry, but not overwrite the data in that record.
In record 47 out of 100 the current data is:
(private) ID: 47
Customer Name: John Smith
City: Las Vegas

I'd like the user to be able to alter the public data:
(private) ID: 47
Customer Name: Kate Doe
City: New York

then click the Add New Record Button
The desired result is a new record at the bottom of the table with the updated information and the record that was used for data entry remains the same.
So the table after the click should be
(private) ID: 47
Customer Name: John Smith
City: Las Vegas

...

(private) ID: 101
Customer Name: Kate Doe
City: New York

The button right now just uses
   DoCmd.GoToRecord , , acNewRec
This method overwrites the current data in the data entry record. As far as I can tell all the  AcRecord parameters don't solve this issue and I think I may need to generate a query?

A: this ends up being a duplicate of: MS Access: Copy/Paste selected record programmatically?
but I don't like the accepted answer as if you implement it you find you have to turn off error messages.  Easy enough to do but a good sign there is a better way.
Creating forms to help enter data faster is a common topic here is an example using a listbox:
MS Access 2016 - Multi column listbox to add values to multiple fields in a table
As June7 said create the new record and let the user edit the new record.  This is more natural and hence easier for the form user to understand.  Here is code that handles nulls and doesn't require turning error messages on and off.
Private Sub cmdAppend_Click()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("YourFormsTable")
rs.AddNew 'most declaritive way to add records
rs![Customer Name] = Nz(Me.[Customer Name], "unknown")
rs!City = Nz(Me.City, "unknown")
rs.Update
Me.Requery
Set rs = Nothing
'DoCmd.GoToRecord , , acLast
'Me.Refresh
End Sub

A: The way to this in Access, it to let your button copy the record to a new record, then let the user edit this as needed.
Here is the code to do that:
Copy a record from a button click
This is very fast and requires no requery of the form, and if the user wish to cancel, he/she can just delete the new record as the original record is left untouched.


text:
Q: calling excel worksheet function from excel cell I have a set of user defined vba functions that sit in an excel module, which are then called from an excel spreadsheet... everything has worked fine at this point.
I've been asked to move the vba from the module to the worksheet's code page.  When I did this, I've found I can't call any of the functions from cells on the worksheet... the names simply don't show as existing.  Is there a way to call worksheet functions from an excel cell?  Also, is there any problem calling a worksheet function from a user defined function in another module or worksheet code behind?

EDIT:
I've found if I call by the sheetname.functionname, it throws an error message that includes "The name conflicts with an Excel built-in name or the name of another object in the workbook"... where if I use sheetname.anythingelse it just resolves to #NAME?
Does this mean excel worksheet functions cannot be called from a sheet?

A: No. Functions in the worksheet object can't be called from the sheet as user-defined functions.
The Worksheet object is intended for responding to events that happen on a worksheet. You can't put user-defined functions there. User defined functions have to live in a Module.
If your user-defined function does live in a module, you won't have any problem calling it from code anywhere else... including in the worksheet "code-behind".

A: You have to put the code in a standard module.
Check this link.
http://www.cpearson.com/excel/writingfunctionsinvba.aspx


text:
Q: Pegar o valor do array PHP Tenho a seguinte situação após eu dar um print_r no "$restultado = array(json_encode($_POST, JSON_PRETTY_PRINT))";
Array
(
    [0] => {
    "nome_evento": "C\u00edrculo de Mulheres com Arte Biogr\u00e1fica",
    "group-a": [
        {
            "data_ini": "01\/01\/2017",
            "data_fim": "31\/12\/2017",
            "hora_inicio": "14:00",
            "hora_fim": "18:00",
            "somente_semana": "06"
        },
        {
            "data_ini": "01\/09\/2018",
            "data_fim": "30\/09\/2018",
            "hora_inicio": "08:00",
            "hora_fim": "18:00"
        }
    ],
    "data_ini": [
        "01\/01\/2017"
    ],
    "data_fim": [
        "31\/12\/2017"
    ],
    "hora_inicio": [
        "14:00"
    ],
    "hora_fim": [
        "18:00"
    ],
    "somente_semana": [
        "06"
    ],
    "publico_alvo": "Mulheres acima dos 42 anos",
    "ritmo": "12 encontros mensais",
    "realizacao": "",
    "investimento": "",
    "descricao": "Compartilhando o segundo setênio (7 a 14 anos). Mulheres que são capazes de atravessar a urdidura e a trama de suas vidas para descobrir quais fios que partem de lá até aqui. As fantasias, os irmãos e primos brincando na corredeira das águas da chuva, as festas religiosas, as tarefas de casa e os primeiros anos da escola.

Voltar ao cenário da infância nos ajuda a estabelecer um relacionamento adulto com essa pretensa realidade. Os fatos da vida da pessoa são bem menos importantes do que a maneira como nos lembramos deles, o modo como os interiorizamos e somos impulsionados por eles, ou como somos capazes de trabalhar com eles.",
    "resultados": "",
    "objetivos": "",
    "filesize": "",
    "filetype": "",
    "filedim": "",
    "w": "",
    "h": "",
    "salvar": "ok",
    "id_item_atu": "2",
    "x1": "",
    "y1": "",
    "x2": "",
    "y2": ""
}
)

Eu precisaria salvar os campos "data_ini", "data_fim", "hora_inicio", "hora_fim" e "somente_semana".
Tentei a tarde toda, mas o que consegui foi pegar a posição 0, com um "print_r($restultado[0])".
É possível fazer um foreach para pegar esses campos?
Esse resultado é do jQuery Repeater, e na documentação, eles pedem para usar um Json (json_encode($_POST, JSON_PRETTY_PRINT))


text:
Q: ARM How to invoke branching? Was looking through a code with regards to loop.
loopinner ....
          SUBS R2,R2,#1 ; j--
          BGT loopinner ;in this case, loop should continue when j>1

In this case, I am not sure how BGT branches to the loopinner again. Don't I need to specify what it is greater than? Since SUBS invoke the flags, let's say if j-- becomes the value of 1. How does the branch knows what value it is greater than?

A: From ARM conditionals you can readily find that the instruction examines the Z, N, and V status flags and branches when Z=0 & N=V. Since it examines the V status flag and not the C status flag, this is clearly intended as a signed test. (This means to me that this isn't useful for unsigned loop control -- FYI.)
I wrote this not so long ago, with enough information to understand what's going on. But I can summarize it here.
Let's use simpler 4-bit words where there are only 16 symbols:
Word     Signed     Subtrahend
0000         0         1111
0001         1         1110
0010         2         1101
0011         3         1100
0100         4         1011
0101         5         1010
0110         6         1001
0111         7         1000
1000        -8         0111
1001        -7         0110
1010        -6         0101
1011        -5         0100
1100        -4         0011
1101        -3         0010
1110        -2         0001
1111        -1         0000

Above, the third column is what the ALU actually uses when subtracting by that value. It simply inverts each bit before adding. (The ALU never subtracts anything. It doesn't even know how.) So, the SUB instruction actually performs addition, using the subtrahend form of the value when adding. (If you want to understand status bit semantics, it's pretty important that you master this concept as it will help you when you'd otherwise be confused.)
Stamp it onto your forehead --
A CPU ONLY ADDS. IT CANNOT SUBTRACT.
If you ever feel the temptation to go down the primrose path of believing that any kind of subtract instruction actually subtracts, and this includes all comparison instructions that set status bits but don't change register values, just kick yourself really hard, really fast. It doesn't happen.
A CPU ONLY ADDS. IT CANNOT SUBTRACT.
Everything has to be cast into addition semantics. Everything.
A SUBS R2, R2, #1, in this 4-bit universe I just created, would add 1110 plus a carry-in of 1, as well. There are only 16 possibilities:
Actual Operation    Operation Result    Operation      Comparison
 R2     SUBS OP        Z N V C ALU       Semantics      Semantics   Z=0 & N=V?
0000 + 1110 + 1        0 1 0 0 1111     0 - 1 = -1       0 > 1 ?    False
0001 + 1110 + 1        1 0 0 1 0000     1 - 1 =  0       1 > 1 ?    False
0010 + 1110 + 1        0 0 0 1 0001     2 - 1 =  1       2 > 1 ?    True
0011 + 1110 + 1        0 0 0 1 0010     3 - 1 =  2       3 > 1 ?    True
0100 + 1110 + 1        0 0 0 1 0011     4 - 1 =  3       4 > 1 ?    True
0101 + 1110 + 1        0 0 0 1 0100     5 - 1 =  4       5 > 1 ?    True
0110 + 1110 + 1        0 0 0 1 0101     6 - 1 =  5       6 > 1 ?    True
0111 + 1110 + 1        0 0 0 1 0110     7 - 1 =  6       7 > 1 ?    True
1000 + 1110 + 1        0 0 1 0 0111    -8 - 1 = -9 E    -8 > 1 ?    False
1001 + 1110 + 1        0 1 0 1 1000    -7 - 1 = -8      -7 > 1 ?    False
1010 + 1110 + 1        0 1 0 1 1001    -6 - 1 = -7      -6 > 1 ?    False
1011 + 1110 + 1        0 1 0 1 1010    -5 - 1 = -6      -5 > 1 ?    False
1100 + 1110 + 1        0 1 0 1 1011    -4 - 1 = -5      -4 > 1 ?    False
1101 + 1110 + 1        0 1 0 1 1100    -3 - 1 = -4      -3 > 1 ?    False
1110 + 1110 + 1        0 1 0 1 1101    -2 - 1 = -3      -2 > 1 ?    False
1111 + 1110 + 1        0 1 0 1 1110    -1 - 1 = -2      -1 > 1 ?    False

Under Operation Result I have a column for ALU. The ALU field is what goes back into R2 after the SUBS instruction completes. (The V status flag is generated by an XOR of the carry-out of the next-to-most significant bit during the operation and the carry bit itself.) Note also that there is a single case marked with E where a signed overflow occurred.
You can now easily see why the BGT instruction applies those particular status bits in exactly the way it does. Admittedly, this uses 4-bit words. But the exact same idea applies to much wider word sizes, without any change to it.
Looking back at the table, you can see that the condition is True if and only if R2 was 2 or greater before the subtraction, and not 1 or 0 or smaller.
Your question:

Don't I need to specify what it is greater than? Since SUBS invoke the
flags, let's say if j-- becomes the value of 1. How does the branch
knows what value it is greater than?

Let's start with the following table from the ARMv6-M Architecture Reference Manual, page A6-99:

The GT condition is described as "Signed greater than". The reason the documentation doesn't specify a constant is that this test occurs after some prior instruction. That prior instruction defines the context. But without having that context, all that can be said is a general signed >.
So, if the prior instruction were CMP:

Then the context would be the comparison of two signed values and the BGT instruction would then mean "branch when signed operand 1 is greater than signed operand 2."
But in your case, with "SUBS R2, R2, #1" the context changes and the BGT instruction would then mean "branch while signed R2 still remains greater than 0."
The conditional branch instruction itself doesn't actually know what the prior instruction was. It also doesn't even know what register(s) are involved. That knowledge is left to the individual (or compiler) that is generating the instruction stream. So the branch instruction doesn't actually have a fixed constant value, nor does it have a register with which to compare against. It depends entirely upon what earlier instructions did with the status bits. It just examines the resulting status and then does what it does. It's up to you to know the context and to use it, correctly.
(Speaking of which, the source code comment may be misleading or wrong.)
Note
Elliot takes issue (see discussion below) without evidence. He writes, "I could equivalently argue that a CPU can only subtract." He can make that argument, but it is only academic. The actual fact of the matter is that CPUs don't subtract. They add.
So while this is partly my response, providing clear, unequivocal evidence in support so that even Elliot can understand the situation on the ground, today, it's also an excellent segue, too. So I'm very glad for the opportunity Elliot affords me in expanding the discussion.
My first CPU was made from 7400 parts that I built and successfully completed in 1974. Newspaper reporters, to my surprise, showed up and wrote an article about it. That's my first experience. Since then, I professionally worked at Intel doing chipset testing for the BX chipset and, as a matter of relevance to teaching this subject, I've taught Computer Architecture classes as an adjunct professor at Portland State University in the 1990's, with class sizes of approximately 65-75 students. This is the largest 4-year university in the State of Oregon.
I feel equivocation (expressing ambivalence about how computations might be done) about how processors generate their status bits and how they compute only leads students into unnecessary uncertainty, confusion and difficulty that can take hours, weeks, months and sometimes even years to correct. Just as teaching group-theoretic abstract algebra before getting the basics across would confuse most first-year algebra students, so also would teaching academic abstractions about how computers could do things. More students would be damaged, than helped.
The simple truth is that instruction decoding emits an ADD, even when the instruction text (it's just text, after all -- it's not what is actually going on) says SUB. The decoding still issues an ADD. It just modifies some operand details along the way.
Similarly, as it must also be in the case of the ARM processor, the above theory is all you need to understand how things are actually done.
Please don't confuse yourself! Computers add. They don't subtract. They just fiddle around a bit to make it look like they subtract.
For good or bad, it's important to understand what a computer actually does in order to understand certain status bits; what they do and why they do it. There's no other way around it. The above theoretical model is the way things work in modern processors and it is how to work out and understand the status bits, correctly. There is a good reason why things are the way they are.
It's my hope that these details, above, and those I'll write below will be useful. Any failure to communicate here is mine and I'll gladly work to repair, amend, and improve this document where I may.
To continue, I'll be using the ARMv6-M Architecture Reference Manual as a reference.
Let's start on page A6-187 (register case):

Here, you can see that they clearly document this behavior:
AddWithCarry(R[n], NOT(shifted), '1')

This is an addition, with operand 2 (the subtrahend) inverted and the carry-in set to '1'. Just as I wrote happens, above. (It's just how it is done.)
In the case of multi-word extensions, go to page A6-173, and find SBCS:

Here note that they again use addition:
AddWithCarry(R[n], NOT(shifted), APSR.C)

Instead of the carry-in being a hard-coded '1', as it is for the SUBS instruction, it's now using the last-saved carry-out value. In this case, it's usually expected that this will be the carry-out from a prior SUBS (or SBCS) instruction.
For multi-word operations, one starts with SUBS (or ADDS) and then continues the process with subsequent SBCS (or ADCS), which use the carry-out of earlier instructions to support a multi-word operation.
In multi-word addition, this carry-out can be thought of just as a carry-out, which it is. A '1' indicates that a carry occurred and needs to be dealt with. A '0' indicates no carry occurred.
In the case of multi-word subtraction, this carry-out is better seen as an inverted borrow-from. A '1' indicates that there was no need to borrow from a higher-order word. A '0' indicates that there is a need to borrow. Since a SUBS instruction always sets this to '1', this means there's no borrow (the subtraction result requires an 'increment' in order to compensate for the inverted operand 2.) But for the SBCS instruction, if APSR.C is a '0', then no 'increment' takes place and this is the same as borrowing (since an increment is required, if there is no borrow.)
The ADCS instruction, found on page A6-106 but not displayed here, also uses the carry-out of prior instruction executions. It doesn't invert the carry-out value or otherwise do something weird or different, just because it is an ADCS instruction. It does exactly the same thing as the SBCS instruction except and only for one minor detail -- the SBCS instruction will invert operand 2 and ADCS won't. That's it.
This is one of the really cool aspects about the way these details work. Very little added logic is required to turn an addition into a subtraction and/or a multi-word addition into a multi-word subtraction.
And finally, to complete the story, see page A2-35:

Consistent with my descriptions of how things actually do work, above.
It's really a pleasure to see how all this works. It's worth some time playing with different signed and unsigned values and, by hand, setting and using status flags. It really deepens these ideas. And they are very good ones!
All of the above is about understanding the status bits and how they are generated and why they are generated in the way that they are. If you focus on what actually happens in a CPU, the rest just falls out as the necessary consequences and it's very easy to understand, then.
A CPU only adds. It cannot subtract.

A: In your code example the SUB instruction has an S suffix, this means that the sub instruction will set the condition flags, which the BGT will evaluate. For the branch to be taken, the Z flag must be 0, and the N flag must equal V

A: The arm documentation clearly states that GT is a signed greater than, it will branch when Z==0,N==V.
When r2 = 2.  Remember from grade school that x - y = x + (-y), and from day one (or shortly thereafter) in computer engineering/science/whatever twos complement negation is invert and add one so x - y = x + (~y) + 1.  This saves on logic and is how we do subtraction
      1  add one
   0010
 + 1110  invert
==========

four bits is more than enough to see what is going on, the result is the same as 32 bits.
   11101
    0010
  + 1110
 ==========
    0001

So N = 0 and Z = 0 from the result.  The carry in and carry out of the msbit are the same so V = 0 (xor of the carry in and carry out of the msbit, can also do it by inspection of the msbits of the operands and result).
We need Z == 0 and N == V to do the branch, and they are, so the branch happens.
You will find this is the case for positive numbers since this is a signed greater than, if you wanted unsigned greater than then use bcs/bhs, logic works the same it just optimizes to using the carry out only (can see this as well if you look at the table jonk generated or generate one yourself)
When r2 = 1
   11111
    0001
 +  1110
 ==========
    0000

Z = 1, N = 0, V = 0
N == V but Z != 0 so the branch does not happen.


text:
Q: Unit Test: How to mock document.getElementById() in react? I want to test following code with jest.
Does anynoe know how to mock document.getElementById()?
if (document.getElementById('estateList')) {
    render(
        <Provider store={store}>
            <EstateList />
        </Provider>,
        window.document.getElementById('estateList')
    );
}

if (document.getElementById('articleList')) {
    render(
        <Provider store={store}>
            <ArticleList />
        </Provider>,
        window.document.getElementById('articleList')
    );
}

if (document.getElementById('articleDetail')) {
    render(
        <Provider store={store}>
            <ArticleDetail />
        </Provider>,
        window.document.getElementById('articleDetail')
    );
}

I think I can put render inside a function, like:
function estateList() {
    render(
        <Provider store={store}>
            <EstateList />
        </Provider>,
        window.document.getElementById('estateList')

    );
}

Then simply test estateList(), without mocking document.getElementById(), but is there anyway to mock document.getElementById()?

A: Using jest.fn(implementation) create mocked getElementById method and replace the method on document.
E.g.
index.tsx:
import React from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import { createStore } from 'redux';

export const store = createStore(() => 0);

export const EstateList = () =>
EstateList
;
export const ArticleList = () =>
ArticleList
;
export const ArticleDetail = () =>
ArticleDetail
;

function bootstrap() {
  if (document.getElementById('estateList')) {
    render(
      <Provider store={store}>
        <EstateList />
      </Provider>,
      window.document.getElementById('estateList'),
    );
  }

  if (document.getElementById('articleList')) {
    render(
      <Provider store={store}>
        <ArticleList />
      </Provider>,
      window.document.getElementById('articleList'),
    );
  }

  if (document.getElementById('articleDetail')) {
    render(
      <Provider store={store}>
        <ArticleDetail />
      </Provider>,
      window.document.getElementById('articleDetail'),
    );
  }
}

export { bootstrap };

index.test.tsx:
import React from 'react';
import { render } from 'react-dom';
import { bootstrap, store, EstateList, ArticleList, ArticleDetail } from './';
import { Provider } from 'react-redux';

jest.mock('react-dom');
const mockedRender = render as jest.Mocked<typeof render>;

describe('49146453', () => {
  let oGetElementById;
  beforeAll(() => {
    oGetElementById = document.getElementById;
  });
  afterAll(() => {
    document.getElementById = oGetElementById;
  });
  it('should render estatelist', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'estateList' ? 'estateList-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <EstateList />
      </Provider>,
      'estateList-dom',
    );
  });

  it('should render articleList', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'articleList' ? 'articleList-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <ArticleList />
      </Provider>,
      'articleList-dom',
    );
  });

  it('should render articleDetail', () => {
    document.getElementById = jest.fn().mockImplementation((id) => (id === 'articleDetail' ? 'articleDetail-dom' : null));
    bootstrap();
    expect(mockedRender).toBeCalledWith(
      <Provider store={store}>
        <ArticleDetail />
      </Provider>,
      'articleDetail-dom',
    );
  });
});

unit test result with coverage report:
 PASS  src/stackoverflow/49146453/index.test.tsx
  49146453
    ✓ should render estatelist (6ms)
    ✓ should render articleList (1ms)
    ✓ should render articleDetail (1ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    84.21 |      100 |       40 |      100 |                   |
 index.tsx |    84.21 |      100 |       40 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        5.618s, estimated 11s

The version about jest.js and related packages, check source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/49146453


text:
Q: Convert Uint32 into an array of 4 bytes How can I convert a Uint32 number into its 4 bytes (as a Uint8List or similar).
Context: I am using the image package, and calling getPixel(x,y) function, which returns a Uint32. I want to separate it out into the rgba color channels.

A: Turns out the way to do so is to convert it into a Uint32List, then retrieve the byte buffer and convert it to the type you want.
int pixel = image.getPixel(x, y);
Uint32List list = new Uint32List.fromList([pixel]);
Uint8List byte_data = list.buffer.asUint8List();


text:
Q: Insert ContentVersion without VisualForce I've got a CSV file stored on the user's hard drive and I want to store it in Salesforce.  The code I have uses Visualforce and Apex to, I think, open up the file and place the contents on a hidden field on the VF page, then it calls the Apex code to grab that and pass it as a string to the code listed below.
I would really like to just get the name of the file from the user and call some method to create the ContentVersion record - I would like to get Visualforce out of the loop basically.  Any Apex samples to show how to do this would be appreciated.
private void attachUploadFileToFirstAccount(String filename, String firstAccount, String blobString) {
    System.debug('==> blobString: ' + blobString);
    ContentVersion cv = new ContentVersion(
            Title = filename.substringBefore('.'),
            Description = 'Uploaded on ' + Date.today(),
            FirstPublishLocationId = firstAccount,
            PathOnClient = filename,
            VersionData = EncodingUtil.Base64Decode(blobString),
            ContentLocation = 'S',
            Origin = 'H'
    );
    insert cv;
    System.debug('==> ContentVersion: [' + cv.Id + ']' + cv + '\n');
}


text:
Q: Sync two div using javascript In my fiddle , you can see two parent div and child div in each parent !
The child div from First parent div can drag and resize ( Using JQueryUI ).
  I have dragEnd and resizeEnd event for this div .
What I want to do is , after dragEnd , to set the location of child div of Second Parent div , same as first's child div .
And also , after resizeEnd ,  to set the size of child div of Second Parent div , same as first's child div .
Want to synchronize two child div.
Thanks !
html

    This is text Line 1

Second

    This is text Line 1

JavaScript
   var DEF_HEIGHT = 100; // the #resizable default height
$( "#resizable" ).resizable({
    containment: 'parent',handles: "se",stop:resizeStop,

  aspectRatio: true,
  resize: function( event, ui ) {
    var curHeight = (ui.size.height/ DEF_HEIGHT) * 100;

    $(this).css('font-size', curHeight + '%');
  }
}).draggable({containment: 'parent'

             });

 $( "#resizable" ).draggable({
start: function() {

},
drag: function() {

},
stop: function() {
alert("Drag End");
}
});

$("#resizable").resizable({
    stop: function(event, ui) {
    alert('Resize End');
    }
});

function dragStop(event, ui){
}

function resizeStop(event, ui){
}

A: You can do it like this:
$("#resizable").resizable({
    ...
    stop: function (event, ui) {
        $preview.css({width: this.style.width, height: this.style.height});
    }
})
.draggable({
    ...
    stop: function (e, ui) {
        $preview.css($(this).position());
    }
});

Demo: http://jsfiddle.net/YxcS8/6/


text:
Q: Formatted Pdf word to html I need to convert formatted pdf and word document to html. This conversion is for show the document into web browsers. Into web browser you can also select text. I don't know if it is better to do at backend side (with Java for example) or with maybe php, or there is a jquery/javascript plugin?
My target is to show these documents in a web browser like iPaper.
Thanks for the help

A: You can use pdftohtml and run it server-side automatically, or batch process your pdfs with it.

A: Here's a PowerShell solution I'm working on refining:
https://github.com/suzumakes/ReplaceIT
If the problem you're having is that Word spits out ridiculous amounts of garbage and claims it's an HMTL file, this should help a lot. There's a reason that iPaper has such a large team though, and that's because you're looking to build a webpage out of a document, print to web with the click of a button, and it turns out that's pretty difficult.


text:
Q: Show listed images in Panel when a node is clicked in UITree Matlab? I am working in Matlab. I want to show Images in a given Panel one by one when user mouse click on a file name in tree list.  Can anyone please help me?

Code for tree:
src = strcat(pwd,'\Result\');
[mtree, container] = uitree('v0', 'Root',src,۔۔۔
'Position',[10 10 290 370],'Parent', imageListPanel2); % Parent is ignored
 set(container, 'Parent', imageListPanel2);  % fix the uitree Parent

Function to Display Image in panel:
function refreshDisplay(varargin)
    imgDisplayed = imshow(tmp,'parent',workingAx);
end %refreshDisplay

I just need to know how to call function refreshDisplay() from my tree. Again remember I want to call function from Tree Elements(files) not from node(sub directory).
Regards.

A: Below is a quick but complete example. Code is commented and easy to follow:
function MyImageViewer
    % prepare GUI
    hFig = figure('Menubar','none', 'Name','Image Viewer');
    hPan(1) = uipanel('Parent',hFig, 'Position',[0 0 0.3 1]);
    hPan(2) = uipanel('Parent',hFig, 'Position',[0.3 0 0.7 1]);

    ax = axes('Parent',hPan(2), 'Units','normalized', 'Position',[0 0 1 1]);
    axis(ax, 'off', 'image')

    [jtree,htree] = uitree('v0', 'Parent',hFig, ...
        'Root','C:\Users\Amro\Pictures\', 'SelectionChangeFcn',@changeFcn);
    set(htree, 'Parent',hPan(1), 'Units','normalized', 'Position',[0 0 1 1]);
    jtree.expand(jtree.getRoot);    % expand root node

    % list of supported image extensions
    fmt = imformats;
    imgExt = lower([fmt.ext]);

    function changeFcn(~,~)
        % get selected node
        nodes = jtree.getSelectedNodes;
        if isempty(nodes), return; end
        n = nodes(1);

        % only consider a leaf node (skip folders)
        if ~n.isLeaf, return; end

        % get complete node path (absolute filename)
        p = arrayfun(@(nd) char(nd.getName), n.getPath, 'Uniform',false);
        p = strjoin(p(:).', filesep);

        % check for supported image types, and show image
        [~,~,ext] = fileparts(p);
        if any(strcmpi(ext(2:end),imgExt))
            imshow(p, 'Parent',ax)
        end
    end
end

A: Note that everything in the tree are nodes, both the folders and the images. You need to implement a check inside the selection callback to test whether the selected node is a folder.
Quoting UndocumentedMatlab:

The currently-selected node(s) can be accessed using mtree.getSelectedNodes. Node selection
  callbacks often require knowledge of the currently selected rows:

%// Tree set up
mtree = uitree(..., 'SelectionChangeFcn',@mySelectFcn);
set(mtree, 'SelectionChangeFcn',@mySelectFcn); % an alternative

%// The tree-node selection callback
function nodes = mySelectFcn(tree, value)
    selectedNodes = tree.getSelectedNodes;
    %// Use this to see which information is available about the node:
    %//   methods(selectedNodes(1),'-full')
    %// And the node array:
    %//   methods(selectedNodes,'-full')
    if ~isempty(selectedNodes) || max(selectedNodes.size)>1
       %// Obtain path from selected node; Source: link1 below
       nodePath = selectedNodes(1).getPath.cell;
       subPathStrs = cellfun(@(p) [p.getName.char,filesep],nodePath,'un',0);
       pathStr = strrep([subPathStrs{:}], [filesep,filesep],filesep);
       %// Also, don't forget a drive letter here ^ if required
        if ~isdir(pathStr) %// check that the selection isn't a directory
            %// this is where you need to call your refresh function
        end
    end
end  %// mySelectFcn

link1

You can get some other ideas in this answer, which shows how to implement a mouse tracking callback, in case you want the refresh to execute on a mouse-over...


text:
Q: Scoping issue with for-loops in Javascript i realise this is probably classed as a duplicate however I've read this question and the replies in detail but still can't get my head around it.
I have this code, but within the 'focus' function, 'i' is always 2, (the pageSearchInput.length value), and I want it to be 0,1 respectively on each loop.
I understand that this is a scoping issue but I can't work out how to fix this without simply using 'let'.
If someone could explain how this works i'd be very grateful.
for (i = 0; i < pageSearchInput.length; i++) {

    pageSearchInput[i].addEventListener("focus", function(){

        pageSearchContainer[i].style.outline = "4px solid #ffcc33";
        pageSearchButton[i].style.backgroundColor = "#008920";
        pageSearchButton[i].style.border = "1px solid #008920";

    });

}

A: Just make i a parameter to the function and pass it, and return the function that handles the event:
for (i = 0; i < pageSearchInput.length; i++) {

    pageSearchInput[i].addEventListener("focus", (function(i){
      return function() {
        pageSearchContainer[i].style.outline = "4px solid #ffcc33";
        pageSearchButton[i].style.backgroundColor = "#008920";
        pageSearchButton[i].style.border = "1px solid #008920";
      };
    })(i));

}

A: If you don't want to use let you should create a wrapping function.
for (i = 0; i < pageSearchInput.length; i++) {

    pageSearchInput[i].addEventListener("focus", function(){
        return (function(i) {
            pageSearchContainer[i].style.outline = "4px solid #ffcc33";
            pageSearchButton[i].style.backgroundColor = "#008920";
            pageSearchButton[i].style.border = "1px solid #008920";
        })(i);
    });

}

A: You can use IIFE (Immediately Invoked Function Expression)
(function () {
  statements
})();

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.

With IIFE your code should be:
for (i = 0; i < pageSearchInput.length; i++) {
  (function(i){
     pageSearchInput[i].addEventListener("focus", function(){

       pageSearchContainer[i].style.outline = "4px solid #ffcc33";
       pageSearchButton[i].style.backgroundColor = "#008920";
       pageSearchButton[i].style.border = "1px solid #008920";

    });
  })(i);
}

A: You have to use let keyword in order to preserve the value of i in the for loop scope.
for (let i = 0; i < pageSearchInput.length; i++) {

Another method is to use Immediately-invoked function expression
(function(i){
   pageSearchInput[i].addEventListener("focus", function(){

   });
})(i);

A: You can try to use IIFE to get your problem fixed related to scope.
for (i = 0; i < pageSearchInput.length; i++) {
   (function(j){
    return pageSearchInput[j].addEventListener("focus", function(){

        pageSearchContainer[j].style.outline = "4px solid #ffcc33";
        pageSearchButton[j].style.backgroundColor = "#008920";
        pageSearchButton[j].style.border = "1px solid #008920";

    })
  }(i))

}

For details find the explanation in this post
http://learnwebtechs.com/2018/05/11/understanding-javascript-closures-with-example


text:
Q: Map/Reduce over sharded data with RavenDB I'm having trouble getting a map reduce sample to work when the data is sharded across two nodes.  I'm storing documents that relate to application errors being logged on two local ravenDB nodes, the error documents look like:
Example of document on node 1, there are 6 total
errors/1/6
{
  "UniqueId": "c62c7e30-8ec7-45af-88e4-da023d796727",
  "ApplicationName": "MyAppName"
}

Example of document on node 2, there are 7 total
errors/2/6  --Error stored on shard node 2
{
  "UniqueId": "7e0b0f87-9d75-4e70-9fa0-d64a18bc88dc",
  "ApplicationName": "MyAppName"
}

when I run this query:
public class ApplicationNames : AbstractIndexCreationTask<ErrorDocument, Application>
{
    public ApplicationNames()
    {
         Map = errors => from error in errors
                        select new { error.ApplicationName, Count = 1 };

        Reduce = results => from error in results
                            group error by new { error.ApplicationName, error.Count } into g
                            select new { g.Key.ApplicationName, Count = g.Sum(x=> x.Count) };
    }
}

I'm getting back 2 results; one with a Count of 6, the second with a Count of 7.  I was expecting that the two results from each shard would be combined into one result with a count of 13.  Not sure if I'm doing something wrong or if that's not how its supposed to work.  I followed the example at http://ravendb.net/documentation/docs-sharding to set up the sharding strategy.

A: Grant,
RavenDB currently doesn't handle reduce over multiple nodes.
You can do that yourself using:
session.Query<Application, ApplicationNames>()
   .ToList()
   .Select(new ApplicationNames().Reduce)
   .ToList();


text:
Q: Trying to store a command in a shell variable but it errors out I have a string which will be used as command. Also before running that command I need to replace  a string pattern with a variable value..
But is upon assigning I am getting command not found for all of the output lines.
I have tried putting the escape chars but not helping.

role-command="aws sts assume-role --role-arn  arn:aws:iam::<acct_id>:role/AWS-Role --role-session-name temp-aws-rolesession --output text --duration-seconds 3600 --query 'Credentials.[[join(`=`,[`AWS_ACCESS_KEY_ID`, AccessKeyId])],[join(`=`,[`AWS_SECRET_ACCESS_KEY`, SecretAccessKey])],[join(`=`,[`AWS_SESSION_TOKEN`, SessionToken])]]'"

bash: =: command not found
bash: AWS_ACCESS_KEY_ID: command not found
bash: =: command not found
bash: AWS_SECRET_ACCESS_KEY: command not found
bash: =: command not found
bash: AWS_SESSION_TOKEN: command not found
bash: role-command=aws sts assume-role --role-arn  arn:aws:iam::<acct_id>:role/AWS-Role --role-session-name temp-aws-rolesession --output text --duration-seconds 3600 --query 'Credentials.[[join(,[, AccessKeyId])],[join(,[, SecretAccessKey])],[join(,[, SessionToken])]]': No such file or directory
And the I was suppose to do sed -i s/<acct_id>/97476414123/g ${role-command}
How can I achieve this?
I have tried even below:

role-command="aws sts assume-role --role-arn  arn:aws:iam::<acct_id>:role/AWS-Role --role-session-name temp-aws-rolesession --output text --duration-seconds 3600 --query 'Credentials.[[join(\`=\`,[\`AWS_ACCESS_KEY_ID\`, AccessKeyId])],[join(\`=\`,[\`AWS_SECRET_ACCESS_KEY\`, SecretAccessKey])],[join(\`=\`,[\`AWS_SESSION_TOKEN\`, SessionToken])]]'"

Getting below:

bash: role-command=aws sts assume-role --role-arn  arn:aws:iam::<acct_id>:role/AWS-Role --role-session-name temp-aws-rolesession --output text --duration-seconds 3600 --query 'Credentials.[[join(`=`,[`AWS_ACCESS_KEY_ID`, AccessKeyId])],[join(`=`,[`AWS_SECRET_ACCESS_KEY`, SecretAccessKey])],[join(`=`,[`AWS_SESSION_TOKEN`, SessionToken])]]': No such file or directory

Regards,
SA

A: I have got this right. I can confirm its done now

y="$(echo "aws sts assume-role --role-arn arn:aws:iam::<acct_id>:role/AWS-Role --role-session-name role-session --output text --duration-seconds 3600 --query 'Credentials.[[join(`=`,[`AWS_ACCESS_KEY_ID`, AccessKeyId])],[join(`=`,[`AWS_SECRET_ACCESS_KEY`, SecretAccessKey])],[join(`=`,[`AWS_SESSION_TOKEN`, SessionToken])]]'" |sed 's/<acct_id>/56787654567/g')"


text:
Q: GTK apps no longer render text I am using virt-manager on Debian Jessie. A few weeks ago, it was working fine for me; however now when I run it, the text does not render correctly.

I have tried reinstalling all of the dejavu fonts, liberation fonts, run fc-cache, rebooted the system, even reinstalled libvirt and virt-manager. No dice.
This issue is present both when using Xming via putty/ssh, and when doing ssh -Y from another linux box. The only thing I can remember doing that might have affected fonts is installing updates from apt.
Ideas welcome, need help here!
[EDIT] further research has shown that this is in fact a GTK problem; running non GTK x11 apps such as xfontsel works fine; running GTK stuff such as this code does not. I still don't know how to solve it but hopefully this helps get somewhere!

A: Ok, for some weird reason, libgtk seems to have become uninstalled. The issue has been fixed, by doing apt-get install libgtk-3-0. What on earth it was that caused it to become uninstalled, I know not. It seems bizarre to me that a GTK based application would even launch if libgtk was not installed - but there you go. We are back to working, hurrah!


text:
Q: Improving a tikz plot I have drawn the following picture with tikz:

Code for MWE:
\documentclass[a4paper,12pt,notitlepage,oneside,reqno]{scrbook}
\usepackage[T1]{fontenc}
\usepackage{kpfonts}
\usepackage{libertine}
\usepackage[scaled=0.85]{beramono}
\usepackage[left=1in,right=1in,top=1.45in,bottom=1.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{textcomp}
\DeclareMathOperator{\PSL}{L}
\DeclareMathOperator{\PSU}{U}
\DeclareMathOperator{\M}{M}

\begin{document}

\begin{figure}
\centering
\begin{tikzpicture}
\begin{axis}[
ymin=0,
height=9.27cm,
width=15cm,
ymajorgrids,
ylabel near ticks,
xlabel near ticks,
xlabel={},
ytick={0.05,0.10,0.15,0.20,0.25},
yticklabels={0.05,0.10,0.15,0.20,0.25},
xtick={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16},
xticklabels={$A_5$,$\PSL_2(7)$,$A_6$,$\PSL_2(8)$,$\PSL_2(11)$,$\PSL_2(13)$,$\PSL_2(17)$,$A_7$,$\PSL_2(19)$,$\PSL_2(16)$,$\PSL_3(3)$,$\PSU_3(3)$,$\PSL_2(23)$,$\PSL_2(25)$,$\M_{11}$,$\PSL_2(27)$},
ylabel=$\mathfrak{p}$,
]

\addplot+[]
coordinates {
(1,0.247343)
(2,0.189913)
(3,0.0833901)
(4,0.0613976)
(5,0.05859)
(6,0.0290478)
(7,0.0173417)
(8,0.0279725)
(9,0.0137492)
(10,0.0176165)
(11,0.0304418)
(12,0.0155998)
(13,0.00976193)
(14,0.00851869)
(15,0.0119328)
(16,0.00731549)

};
\end{axis}
\end{tikzpicture}
\caption{The subgroup permutability degree of all finite simple groups of small order. The $x$-axis lists the groups in increasing order.}
\end{figure}
\end{document}

I am primarily interested in hearing suggestions what to do with the overlapping labels of the $x$-axis, but I'd also appreciate input on how to improve the overall aesthetics of the picture, if anyone cares to share his/her opinion.

A: You could reduce the size and/or rotate the labels:
\documentclass[a4paper,12pt,notitlepage,oneside,reqno]{scrbook}
\usepackage[T1]{fontenc}
\usepackage{kpfonts}
\usepackage{libertine}
\usepackage[scaled=0.85]{beramono}
\usepackage[left=1in,right=1in,top=1.45in,bottom=1.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{textcomp}
\DeclareMathOperator{\PSL}{L}
\DeclareMathOperator{\PSU}{U}
\DeclareMathOperator{\M}{M}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
ymin=0,
height=9.27cm,
width=15cm,
ymajorgrids,
ylabel near ticks,
xlabel near ticks,
xlabel={},
ytick={0.05,0.10,0.15,0.20,0.25},
yticklabels={0.05,0.10,0.15,0.20,0.25},
xticklabel style={font=\tiny},
xtick={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16},
xticklabels={$A_5$,$\PSL_2(7)$,$A_6$,$\PSL_2(8)$,$\PSL_2(11)$,$\PSL_2(13)$,$\PSL_2(17)$,$A_7$,$\PSL_2(19)$,$\PSL_2(16)$,$\PSL_3(3)$,$\PSU_3(3)$,$\PSL_2(23)$,$\PSL_2(25)$,$\M_{11}$,$\PSL_2(27)$},
ylabel=$\mathfrak{p}$,
]

\addplot+[]
coordinates {
(1,0.247343)
(2,0.189913)
(3,0.0833901)
(4,0.0613976)
(5,0.05859)
(6,0.0290478)
(7,0.0173417)
(8,0.0279725)
(9,0.0137492)
(10,0.0176165)
(11,0.0304418)
(12,0.0155998)
(13,0.00976193)
(14,0.00851869)
(15,0.0119328)
(16,0.00731549)

};
\end{axis}
\end{tikzpicture}\par\bigskip

\begin{tikzpicture}
\begin{axis}[
ymin=0,
height=9.27cm,
width=15cm,
ymajorgrids,
ylabel near ticks,
xlabel near ticks,
xlabel={},
ytick={0.05,0.10,0.15,0.20,0.25},
yticklabels={0.05,0.10,0.15,0.20,0.25},
xticklabel style={rotate=90,font=\footnotesize},
xtick={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16},
xticklabels={$A_5$,$\PSL_2(7)$,$A_6$,$\PSL_2(8)$,$\PSL_2(11)$,$\PSL_2(13)$,$\PSL_2(17)$,$A_7$,$\PSL_2(19)$,$\PSL_2(16)$,$\PSL_3(3)$,$\PSU_3(3)$,$\PSL_2(23)$,$\PSL_2(25)$,$\M_{11}$,$\PSL_2(27)$},
ylabel=$\mathfrak{p}$,
]

\addplot+[]
coordinates {
(1,0.247343)
(2,0.189913)
(3,0.0833901)
(4,0.0613976)
(5,0.05859)
(6,0.0290478)
(7,0.0173417)
(8,0.0279725)
(9,0.0137492)
(10,0.0176165)
(11,0.0304418)
(12,0.0155998)
(13,0.00976193)
(14,0.00851869)
(15,0.0119328)
(16,0.00731549)

};
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Can't figure out why it isn't working. javascript calling data-key I'm working on a little project since I am a Javascript beginner. I have spent some hours on the same problem, and I just can't figure why it doesn't work. I would have rather find the problem myself, but I guess it is time to ask for help.
window.addEventListener('keydown', function (e) {
    console.log(e);
    const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
    console.log(audio);

    /* audio.currentTime = 0;
    if(!audio) return;
    audio.play(); */
});

So I just can't figure out why I doesn't select the data key in my HTML, the console log say the audio is null.
Here is my HTML code:
  <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

Press D for Dogs

Press C for Cats

Press P for Pigs

Press F for Frogs

Press E for Elephants

Press G for Goats

    <audio data-key="68" src="sounds/dog_x.wav"></audio>
    <audio data-key="67" src="sounds/cat_y.wav"></audio>
    <audio data-key="18" src="sounds/pig.wav"></audio>
    <audio data-key="70" src="sounds/frog.wav"></audio>
    <audio data-key="69" src="sounds/elephant.wav"></audio>
    <audio data-key="71" src="sounds/goat.wav"></audio>

Thanks in advance.

A: Your query needs editing:
document.querySelector('audio[data-key="${e.keyCode}"]');

There is no such thing as parameter expansion in strings enclosed in single quote marks ('').
Either concatenate the correct string like this
document.querySelector('audio[data-key="' + e.keyCode + '"]');

or use a template string (MDN)
document.querySelector(`audio[data-key="${e.keyCode}"]`);


text:
Q: How to manipulate an array of structure containing 2D array Using C++, I am implementing an array of structure HiddenLayer defined as
    struct HiddenLayer
    {
        int prev;     ///Number of Rows in node
        int next;     ///Number of Columns in node

        float **node; ///2D array pointer
    };

The array of structure is initialized in the main routine and node is the pointer to the 2D array inside the structure. I am initializing this array as
    int main()
    {
        struct HiddenLayer HLayer[1];

        HLayer[0].prev = 1;  //Num of rows
        HLayer[0].next = 3;  //num of col

        HLayer[0].node = (float *) malloc((HLayer[0].prev) * sizeof(float *));

        for(int i=0;i<HLayer[0].prev;i++)
            HLayer[0].node[i] = malloc(HLayer[0].next * sizeof(float));

        return 0;
    }

But I get this error:
In function 'int main()':
main.cpp:22:73: error: cannot convert 'float*' to 'float**' in assignment
     HLayer[0].node = (float *) malloc((HLayer[0].prev) * sizeof(float *));
                                                                         ^

>main.cpp:25:35: error: invalid conversion from 'void*' to 'float*' [-fpermissive]
         HLayer[0].node[i] = malloc(HLayer[0].next * sizeof(float));

I followed the answers given Here and Here
What wrong am I doing?

A: The error messages are self-explanatory: you mixed up the types.
HLayer[0].node = (float *) malloc((HLayer[0].prev) * sizeof(float *));

should be
HLayer[0].node = (float **) malloc((HLayer[0].prev) * sizeof(float *));

and
HLayer[0].node[i] = malloc(HLayer[0].next * sizeof(float));

should be
HLayer[0].node[i] = (float *) malloc(HLayer[0].next * sizeof(float));

But that said, why'd you want to use malloc() and family in C++?


text:
Q: How to write mathematical combination formula coding in python I have a data set as the following:
input file:
id  addr
301 1
301 2
301 3
301 4
302 6
302 7
302 8
302 9
302 1
303 14
303 15
303 2
304 16
304 17
304 1

and I need Python code to print out all the possible pair combinations of addr values with common id.  There are millions of id and corresponding addr value records in the main test file. So, the code should be able to read columns from a text file.The output will be as follows (only showing for 301 and 302, the rest will continue the pattern):
1   2
1   3
1   4
2   3
2   4
3   4
6   7
6   8
6   9
7   8
7   9
8   9
1   6
1   7
1   8
1   9
2   6
2   7
2   8
2   9
3   6
3   7
3   8
3   9
4   6
4   7
4   8
4   9
1   15
2   15
3   15
......
1   16
2   16
......
15  16

So far I have done the following, but I do not have any idea how to code the pair combination part. I am new in Python, so will appreciate if someone can help me do the coding with a little bit of explanation.
# coding: utf-8

# sample tested in python 3.6

import sys
from pip._vendor.pyparsing import empty

if len(sys.argv) < 2:
    sys.stderr.write("Usage: {0} filename\n".format(sys.argv[0]))
    sys.exit()

fn = sys.argv[1]
sys.stderr.write("reading " + fn + "...\n")

# Initialize empty set
s = {}
line= 0
fin = open(fn,"r")
for line in fin:
    line = line.rstrip()
    f = line.split("\t")
    line +=1
    if line is 1:
        txid_prev = line
        addr = line
        s= addr
        continue
    txid=line
    txid_prev=line
    if txid is txid_prev:
        s.push(addr)
    else:
        # connect all pairs in s
        # print all pairs as edges
        s=addr
    txid_prev=txid
if s is not empty:
    # connect and print all edges

A: How about something like this:
import pandas as pd
import io
import itertools

file="""id addr
301 1
301 2
301 3
301 4
302 6
302 7
302 8
302 9
302 1"""

df= pd.read_csv(io.StringIO(file), sep=" ")

for key,value in df.set_index("addr").groupby("id").groups.items():
    print(key)
    for item in list(itertools.combinations(value.values, 2)):
        print("{} {}".format(*item))

Prints:
301
1 2
1 3
1 4
2 3
2 4
3 4
302
6 7
6 8
6 9
6 1
7 8
7 9
7 1
8 9
8 1
9 1

Alternatively we can put the values in a Dictionary:
a = {}

for id_,addr in df.values.tolist():
    a.setdefault(str(id_),[]).append(addr)

output = {key:list(itertools.combinations(value, 2)) for key,value in a.items()}

def return_combos(dict_, keys):
    values = []
    for i in keys:
        values.append(a[i])
    values = list(set([i for item in values for i in item]))
    return {','.join(keys):list(itertools.combinations(values, 2))}

output2 = return_combos(a, ["301","302"])

output prints:
{'301': [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)],
 '302': [(6, 7),
  (6, 8),
  (6, 9),
  (6, 1),
  (7, 8),
  (7, 9),
  (7, 1),
  (8, 9),
  (8, 1),
  (9, 1)]}

meanwhile output2 outputs:
{'301,302': [(1, 2),
  (1, 3),
  (1, 4),
  (1, 6),
  (1, 7),
  (1, 8),
  (1, 9),
  (2, 3),
  (2, 4),
  (2, 6),
  (2, 7),
  (2, 8),
  (2, 9),
  (3, 4),
  (3, 6),
  (3, 7),
  (3, 8),
  (3, 9),
  (4, 6),
  (4, 7),
  (4, 8),
  (4, 9),
  (6, 7),
  (6, 8),
  (6, 9),
  (7, 8),
  (7, 9),
  (8, 9)]}

update2 or 3: Is this the desired output??
import pandas as pd
import io
import itertools
from collections import OrderedDict

file="""id addr
301 1
301 2
301 3
301 4
302 6
302 7
302 8
302 9
302 1
303 14
303 12"""

df= pd.read_csv(io.StringIO(file), sep=" ")

b = OrderedDict()

for id_,addr in df.values.tolist():
    b.setdefault(str(id_),[]).append((id_,addr))

pairs = [(list(b.keys())[i],list(b.keys())[i+1]) for i in range(len(list(b.keys()))-1)]

output = {}
for pair in pairs:
    output[pair] = [[(i[0][0],i[1][0]),i[0][1],i[1][1]] for i in list(itertools.combinations(b[pair[0]]+b[pair[1]], 2))]

output

{('301', '302'): [[(301, 301), 1, 2],
  [(301, 301), 1, 3],
  [(301, 301), 1, 4],
  [(301, 302), 1, 6],
  [(301, 302), 1, 7],
  [(301, 302), 1, 8],
  [(301, 302), 1, 9],
  [(301, 302), 1, 1],
  [(301, 301), 2, 3],
  [(301, 301), 2, 4],
  [(301, 302), 2, 6],
  [(301, 302), 2, 7],
  [(301, 302), 2, 8],
  [(301, 302), 2, 9],
  [(301, 302), 2, 1],
  [(301, 301), 3, 4],
  [(301, 302), 3, 6],
  [(301, 302), 3, 7],
  [(301, 302), 3, 8],
  [(301, 302), 3, 9],
  [(301, 302), 3, 1],
  [(301, 302), 4, 6],
  [(301, 302), 4, 7],
  [(301, 302), 4, 8],
  [(301, 302), 4, 9],
  [(301, 302), 4, 1],
  [(302, 302), 6, 7],
  [(302, 302), 6, 8],
  [(302, 302), 6, 9],
  [(302, 302), 6, 1],
  [(302, 302), 7, 8],
  [(302, 302), 7, 9],
  [(302, 302), 7, 1],
  [(302, 302), 8, 9],
  [(302, 302), 8, 1],
  [(302, 302), 9, 1]],
 ('302', '303'): [[(302, 302), 6, 7],
  [(302, 302), 6, 8],
  [(302, 302), 6, 9],
  [(302, 302), 6, 1],
  [(302, 303), 6, 14],
  [(302, 303), 6, 12],
  [(302, 302), 7, 8],
  [(302, 302), 7, 9],
  [(302, 302), 7, 1],
  [(302, 303), 7, 14],
  [(302, 303), 7, 12],
  [(302, 302), 8, 9],
  [(302, 302), 8, 1],
  [(302, 303), 8, 14],
  [(302, 303), 8, 12],
  [(302, 302), 9, 1],
  [(302, 303), 9, 14],
  [(302, 303), 9, 12],
  [(302, 303), 1, 14],
  [(302, 303), 1, 12],
  [(303, 303), 14, 12]]}

A: How about this (if you don't care about duplicates)? [Live Demo]
import io
import pandas as pd

data =  io.StringIO("""id addr\n301 1\n301 2\n301 3\n301 4\n302 6\n302 7\n302 8\n302 9\n302 1\n303 14\n303 15\n303 2\n304 16\n304 17\n304 1""")

df = pd.read_table(data, sep=' ', index_col=0)
print(df.join(df, rsuffix="_2"))

Output:
     addr  addr_2
id
301     1       1
301     1       2
301     1       3
301     1       4
301     2       1
301     2       2
301     2       3
301     2       4
301     3       1
...

A: This problem can be split up into two parts. First, construct a dictionary that maps identifiers to lists of addresses. Second, generate the length-2 combinations of each of these lists.
from collections import defaultdict
from itertools import combinations

# get lines from your file
f = open('input_file.txt')
lines = f.readlines()
f.close()

# build mapping from file
iden_mapping = defaultdict(list)
for row in lines[1:]:
    iden, addr = row.split()
    iden_mapping[iden].append(addr)

# generate combination from address lists
for iden in sorted(iden_mapping):
    for c in combinations(iden_mapping[iden], 2):
        print(c)