text:
Q: Ansible use current hosts for task as a variable I have the following code that connects to the logger service haproxies and drains the first logger VM.
Then in a separate task connects to the logger lists of hosts, where the first host is drained and does a service reload.
- name: Haproxy Warmup
  hosts: role_max_logger_lb
  tasks:
    - name: analytics-backend 8300 range
      haproxy: 'state=disabled host=maxlog-rwva1-{{ env }}-1.example.com backend=analytics-backend socket=/var/run/admin.sock'
      become: true
      when: warmup is defined and buildnum is defined
    - name: logger-backend 8200
      haproxy: 'state=disabled host=maxlog-rwva1-prod-1.example.com :8200 backend=logger-backend socket=/var/run/admin.sock'
      become: true
      when: warmup is defined and buildnum is defined

- name: Warmup Deploy
  hosts: "role_max_logger"
  serial: 1
  tasks:
    - shell: pm2 gracefulReload max-logger
      when: warmup is defined and buildnum is defined
    - pause: prompt="First host has been deployed to. Please verify the logs before continuing. Ctrl-c to exit, Enter to continue deployment."
      when: warmup is defined and buildnum is defined

This code is pretty bad and doesn't work when I try to expand it to do a rolling restart for several services with several haproxies. I'd need to somehow drain 33% of all the app VMs from the haproxy backend and then connect to a different list and do the 33% reboot process there. Then resume at 34-66% of the draining list and then resume at 34% and 66% on the reboot list.
- name: 33% at a time drain
  hosts: "role_max_logger_lb"
  serial: "33%"
  tasks:
    - name: analytics-backend 8300 range
      haproxy: 'state=disabled host=maxlog-rwva1-prod-1.example.com
      backend=analytics-backend socket=/var/run/admin.sock'
      become: true
      when: warmup is defined and buildnum is defined
    - name: logger-backend 8200
      haproxy: 'state=disabled host=maxlog-rwva1-prod-1.example.com:8200 backend=logger-backend socket=/var/run/admin.sock'
      become: true
      when: buildnum is defined and service is defined

- name: 33% at a time deploy
  hosts: "role_max_logger"
  serial: "33%"
  tasks:
    - shell: pm2 gracefulReload {{ service }}
      when: buildnum is defined and service is defined
    - pause: prompt="One third of machines in the pool have been deployed to. Enter to continue"

I could do this much easier in Chef, just query the chef server for all nodes registered in a given role and do all my logic in real ruby. If it matters the host lists I'm calling here are actually ripped from my Chef server and fed in as json.
I don't know what the proper Ansible way of doing this without being able to drop into arbitrary scripting to do all the dirty work.
I was thinking maybe I could do something super hacky like this inside of the of a shell command in Ansible under the deploy, which might work if there is a way of pulling the current host that is being processed out of the host list, like an Ansible equivalent of node['fqdn'] in Chef.
ssh maxlog-lb-rwva1-food-1.example.com 'echo "disable server logger-backend/maxlog-rwva1-food-1.example.com:8200" | socat stdio /run/admin.sock'

Or maybe there is a way I can wrap my entire thing in a serial 33% and include sub-plays that do things. Sort of like this, but again I don't know how to properly pass around a thirded list of my app servers within the sub-plays
- name: Deployer
 hosts: role_max_logger
 serial: "33%"
   - include: drain.yml
   - include: reboot.yml

Basically I don't know what I'm doing, I can think of a bunch of ways of trying to do this but they all seem terrible and overly obtuse. If I were to go down these hacky roads I would probably be better off just writing a big shell script or actual ruby to do this.
Reading lots of official Ansible documentation for this has overly simplified examples that don't really map to my situation.
Particularly here where the load balancer is on the same host as the app server.
- hosts: webservers
  serial: 5
  tasks:
  - name: take out of load balancer pool
    command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
    delegate_to: 127.0.0.1

http://docs.ansible.com/ansible/playbooks_delegation.html
I guess my questions are:

*

*Is there an Ansible equivalent of Chef's node['fqdn'] to use the currently being processed host as a variable

*Am I just completely off the rails for how I'm trying to do this?

A:
Is there an Ansible equivalent of Chef's node['fqdn'] to use the currently being processed host as a variable

ansible_hostname, ansible_fqdn (both taken from the actual machine settings) or inventory_hostname (defined in the inventory file) depending which you want to use.

A: As you correctly noted, you need to use delegation for this task.
Here is some pseudocode for you to start with:
- name: 33% at a time deploy
  hosts: role_max_logger
  serial: 33%
  tasks:
    - name: take out of lb
      shell: take_out_host.sh --name={{ inventory_hostname }}
      delegate_to: "{{ item }}"
      with_items: "{{ groups['role_max_logger_lb'] }}"
    - name: reload backend
      shell: reload_service.sh
    - name: add back to lb
      shell: add_host.sh --name={{ inventory_hostname }}
      delegate_to: "{{ item }}"
      with_items: "{{ groups['role_max_logger_lb'] }}"

I assume that group role_max_logger defines servers with backend services to be reloaded and group role_max_logger_lb defines servers with load balancers.
This play take all hosts from role_max_logger, splits them into 33% batches; then for each host in the batch it executes take_out_host.sh on each of load balancers passing current backend hostname as parameter; after all hosts from current batch are disabled on load balancers, backend services are reloaded; after that, hosts are added back to LB as in the first task. This operation is then repeated for every batch.


text:
Q: How do I enable the SSE3/SSE4.1 instruction set in Visual Studio 2008? I tried to follow:
Project > Properties > Configuration Properties > C/C++ > Code Generation > Enable Enhanced Instruction Set
But the only options I got were - SSE or SSE2.
Thanks.

A: If you're serious about using SSE then ditch the Microsoft compiler and use a decent compiler. Intel's ICC is probably the best bet. It has full support for SSE3, SSSE3, SSE4.1, SSE4.2 and generates much better code.

A: Let me google that for you
First two links seem to answer your question. SSE3 and SSE4 are not going to be added. if you want to use then you can use intrinsic functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: netCDF incorrect format for lat long I am trying to display a netCDF file that I obtained from NOAA in ArcMap. However, it keeps crashing ArcMap. I have used precipitation netCDFs from NWS before with no issues.
The netCDF is just a sample they sent me of many netCDF files they will start making available as part of a new lightning data release. So I would like to write a script that corrects the netCDF files.
They told me there are "some issues with data formatting (e.g., unsigned integers for event lat and lon) and that it won't be fixed for some time."
I used the following code to open the netCDF to look at the data. I only included the coordinates output and not the data variables and attributes.
xr.open_dataset('C:\\lightning\\sample.nc'

<xarray.Dataset>
Dimensions:                                 (number_of_events: 5879,
number_of_field_of_view_bounds: 2, number_of_flashes: 687, number_of_groups:
3454, number_of_time_bounds: 2, number_of_wavelength_bounds: 2)
Coordinates:
    event_id                                (number_of_events) int32 -940849349 ...
    event_time_offset                       (number_of_events) datetime64[ns] 2017-09-08T19:30:19.917000 ...
    event_lat                               (number_of_events) float64 -1.687 ...
    event_lon                               (number_of_events) float64 -188.5 ...
    event_parent_group_id                   (number_of_events) int32 1324574251 ...
    group_id                                (number_of_groups) int32 1324574251 ...
    group_time_offset                       (number_of_groups) datetime64[ns] 2017-09-08T19:30:19.834000 ...
    group_lat                               (number_of_groups) float32 -1.68695 ...
    group_lon                               (number_of_groups) float32 -55.3391 ...
    group_parent_flash_id                   (number_of_groups) int16 12590 ...
    flash_id                                (number_of_flashes) int16 12590 ...
    flash_time_offset_of_first_event        (number_of_flashes) datetime64[ns] 2017-09-08T19:30:19.834000 ...
    flash_time_offset_of_last_event         (number_of_flashes) datetime64[ns] 2017-09-08T19:30:19.834000 ...
    flash_lat                               (number_of_flashes) float32 -1.68695 ...
    flash_lon                               (number_of_flashes) float32 -55.3391 ...
    product_time                            datetime64[ns] 2017-09-08T19:30:20
    lightning_wavelength                    float32 777.4
    group_time_threshold                    float32 0.0
    flash_time_threshold                    float32 3.33
    lat_field_of_view                       float32 0.0
    lon_field_of_view                       float32 -89.5

I then used np.savetxt to save event_lat, event_lon, group_lat, and group_lon to CSV files so I could ananlyze the coordinates.
What I found was that group_lat values ranged from 42 to -51 and group_lon values range from -44 to -142. These are correct because the file is supposed to display data from North and South America and parts of adjacent oceans.
But, event_lat values ranged from -0.03 to -133 and event_lon values ranged from -90.2 to -222.29. Looking at event_lat CSV, there is a chunk of data that ranged from -.03 to -51 (this should be data for southern hemisphere) and a chunk of data ranging from -90.5 to -132 (this should be the northern hemisphere data). However, that range should actually be 0.5 to 42 latitude.
I'm not sure what's going on with the event_lon data. -90 to -142 coordinates look similar between event_lon and group_lon, so I think that is fine. However, event_lon also has data ranging from -177 to -222 and no data greater than -90. The group_lon data ranges from -44 to -142.5.
Is there a way I can fix these files with python?


text:
Q: How to read file sequentially but repeat any position of pointer So I have a file (around 1mb) and I want to read it word by word. I also want to mark certain pointer positions and want to go back later on to one of those positions and read the file starting from there again. I looked into RandomAccessFile with which I would get the pointer position and later seek to that location but I am not sure if I can read word by word. The readUTF going on till it reaches the end of stream so I cannot stop where ever I want to either.
I looked into scanner as well but couldn't find a functionality that would let me mark positions of pointer. Is there a better way to do this?
Here is an example:
This is a test, foo bar.

I want to read this file word by word, mark the position of is and stop reading when I come to foo, go back to the position of is and start from the next word, i.e a.

A: The BufferedReader has a method called mark which marks an area in the text to which you can go back to using reset.
Example
Example code where I read the file matrix.txt and put a mark at the 10th character which I then read again.
BufferedReader r = new BufferedReader(new FileReader(new File("matrix.txt")));

int x = 0;
char[] array = new char[1];
while (r.read(array) > 0) {
    if (x++ == 10)
        r.mark(10000);
    System.out.print(array[0]);
}
r.reset();
System.out.println();
while (r.read(array) > 0)
    System.out.print(array[0]);

matrix.txt
[[a, b, c], [d, e, f], [g, h, i]]

Output
[[a, b, c], [d, e, f], [g, h, i]]
 [d, e, f], [g, h, i]]

A: If the file is only 1 MB, it might be easiest just to load the entire file into memory. Even though it'll take a few MB of RAM (due to UTF-16 chars and String/ArrayList overhead), it is still negligible on modern platforms.
ArrayList<String> words = new ArrayList<String>();

Scanner in = new Scanner(new File("words.txt"));
in.useDelimiter("\\W+"); // one or more non-word characters

while(in.hasNext()) {
    words.add(in.next());
}
in.close();

At this point you can easily iterate over the ArrayList and remember the index of certain words.
Additionally, because this approach reads from the file only once, it should also improve the running time of your program.


text:
Q: How to wait for a function execution in NodeJS , I recently started programming in NodeJS, so I am a beginner. I'm using Sequelize. When I call the function sequelize.sync(), it creates the tables (that I defined) into my database. Anyway, if I perform a query immediately next the sequelize.sync() function, I obtain an error. I think that the problem is that the query is executed before the end of sequelize.sync(), so I would need to wait for the end of the execution of sequelize.sync(). The code is simply this:
sequelize.sync({force: true});
Users.create({name: "A", surname: "B", number: 1});

The error is:
(node:2561) UnhandledPromiseRejectionWarning: Error
    at Query.run (/mnt/c/Users/raffa/Desktop/simple_app/node_modules/sequelize/lib/dialects/postgres/query.js:50:25)
    at retry (/mnt/c/Users/raffa/Desktop/simple_app/node_modules/sequelize/lib/sequelize.js:313:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:2561) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

How can I solve this problem? Thank you!

A: To wait for an asynchronous function that returns a Promise, like sequelize.sync(), you simply add the await keyword.
await sequelize.sync({force: true});
Users.create({name: "A", surname: "B", number: 1});

Don't forget to await the Users.create as well if you want to do something after. It's generally best practice to always await asynchronous functions.
Note: Top-level await is only available with ESModules. Otherwise you have to wrap the entire code in an async IIFE


text:
Q: LoadLibrary on jvm.dll fails with error code 183 I'm trying to use JNI in C++ to call a method from Java.
I have tried this on a console application and it worked, but when I switch to a DLL that is loaded in any application, it fails with error "ERROR_ALREADY_EXISTS"
    HMODULE jvmDLL = LoadLibrary("C:\\Program Files\\Java\\jre1.8.0_191\\bin\\server\\jvm.dll");
    if (!jvmDLL) {
        int error = GetLastError(); // this returns 183
    }

This works perfectly fine on anything but a DLL injected into any application. It shouldn't be null.

A: Try this instead:
HMODULE jvmDLL = LoadLibrary("C:\\Program Files\\Java\\jre1.8.0_191\\bin\\server\\jvm.dll");
if (!jvmDLL)
   jvmDLL = GetModuleHandle("jvm.dll");
}


text:
Q: Rank of the character group of a maximal $K$-torus for semisimple and adjoint algebraic groups I've been trying to understand some of the idiosyncrasies associated to algebraic groups over non-algebraically closed fields $K$ of characteristic $p > 0$.
Let $G$ is a connected almost absolutely simple adjoint algebraic group over $K$ and $\widetilde{G}$ is the simply connected cover of $G$ also defined over $K$ with central isogeny $\pi : \widetilde{G} \rightarrow G$.  Let $\widetilde{T} \subseteq \widetilde{G}$ be a maximal $K$-torus and let $T= \pi(\widetilde{T}) \subseteq G$.
Is it possible for the $\mathbb{Z}$-rank of the $K$-defined character groups $X_K(\widetilde{T})$ and $X_K(T)$ to be different?  In other words, is the $K$-split part of $\widetilde{T}$ always the same rank as the $K$-split part of $T$?

A: The map $\widetilde{T} \rightarrow T$ is an isogeny, and an isogeny between tori over any field $K$ induces a finite-index inclusion between the associated geometric character groups as ${\rm{Gal}}(K_s/K)$-lattices, hence an isomorphism on associated rational vector space, so same dimension for spaces of Galois-invariants; i.e., same rank for $K$-rational character groups.  However, this is a central isogeny, and that is really the key to the good behavior.
For isogenies $f:G \rightarrow G'$ between connected semisimple $K$-groups such that $\ker f$ is not central in $G$ (which can only occur in positive characteristic $p$, such as Frobenius isogenies $F_{G/K}:G \rightarrow G^{(p)}$) it can happen that $G'$ has larger $K$-rank than $G$. This might sound paradoxical if you are not familiar with it, since you might reason that if $T' \subset G'$ is a maximal $K$-torus (say containing a maximal split $K$-torus of $G'$) then the identity component of the underlying reduced scheme of $f^{-1}(T')$ seems to be a smooth $K$-subgroup scheme of $G$, hence a torus mapping onto $T'$ via an isogeny, so it has the same $K$-rank as $T'$ by the first paragraph above.  That reasoning is valid provided that $f^{-1}(T')_{\rm{red}}$ really is a smooth $K$-subgroup scheme of $G$.  For perfect $K$ such conditions hold (since the underlying reduced scheme of a finite type $K$-group scheme is a smooth $K$-subgroup scheme for such $K$).  But it can fail when $K$ is imperfect.
For example, if $K$ is a local function field of characteristic $p$ and $A$ is a central division algebra of dimension $p^2$ over $K$ then $G := {\rm{SL}}_1(A)$ is a $K$-anisotropic form of ${\rm{SL}}_p$ but $G^{(p)}$ is $K$-split since $A^{(p)}$ is $K$-split (by local class field theory).  So $F_{G/K}:G \rightarrow G^{(p)}$ is an isogeny from a $K$-anisotropic absolutely simple semisimple $K$-group onto a $K$-split one. And of course this is a non-central isogeny. I suspect that this is the kind of phenomenon you were trying to find when formulating the OP.
[EDIT: I should probably have explained why in the case of central isogenies there are no surprises. That is, if $f:G \rightarrow G'$ is a central isogeny between connected reductive $K$-groups for a field $K$ (i.e., the scheme-theoretic kernel $\ker f$ centralizes $G$ in the functorial sense) and if $T' \subset G'$ is a maximal $K$-torus then the scheme-theoretic preimage $T := f^{-1}(T')$ is a maximal $K$-torus of $G$ (in particular, smooth and connected, even if $f$ is inseparable or has disconnected kernel).  The reason is that to prove the $K$-group scheme $T$ is a maximal $K$-torus it suffices to do so after a ground field extension, since by Grothendieck's theorem on the "geometric maximality" of maximal tori over the ground field in a smooth connected affine $K$-group we do not lose the maximality hypothesis on $T'$ after a ground field extension.  Hence, we may assume $K$ is algebraically closed.
With $K = \overline{K}$, all choices of $T'$ are $G'(K)$-conjugate and the map $G(K) \rightarrow G'(K)$ is surjective, so it suffices to treat the case of a single $T'$.  Ah, but then we simply choose a maximal $K$-torus $S$ in $G$, so $T' := f(S)$ is a maximal $K$-torus in $G' = f(G)$, and thus the problem is to show that the inclusion $S \subset f^{-1}(f(S))$ of $K$-group schemes is an equality.  Since $f$ is necessarily faithfully flat, so $G' = G/(\ker f)$ as fppf group sheaves, it suffices to show that $\ker f \subset S$ as subfunctors of $G$.  Since $\ker f$ is central in $G$ by hypothesis, so it centralizes $S$, and hence it suffices to show that the scheme-theoretic centralizer $Z_G(S)$ of $S$ is equal to $S$.  We know equality on $K$-points by the classical theory, so one just has to show that the group scheme $Z_G(S)$ is smooth, which is to say that it has the "expected" tangent space (i.e., that of $S$).  This is a problem on dual numbers, and is proved in section 9 of Chapter III of Borel's textbook in a more classical language.]

A: Since the question is formulated in the language of the papers by Borel-Tits, I'd recommend $\S 22$ of Borel's GTM 126 Linear Algebraic Groups (on central isogenies) as a reasonable reference.   See especially 22.6-22.7.    Borel and Tits developed their language for a connected reductive group defined over an arbitrary field, avoiding the greqter generality of scheme theory but also being well aware of the advantages which scheme language can provide when the field of definition is imperfect.   (SGA3 and the more recent writings by Milne, Conrad-Gabber-Prasad, provide an alternative route into the complexities of working over function fields or over more general rings.)
As long as your isogeny is central, there is not much difficulty in comparing an adjoint group with any covering group.    Otherwise, as pointed out by user36938, life is more complciated.    It's certainly essential to make appropriate choices of language and source materials when dealing with these kinds of questions.     In any case, the basic facts have been written down pretty clearly a long time ago.   Applying these facts to groups over function fields and the like remains a challenge.


text:
Q: How to build RegExp from strings I have a string and a matching pattern like this :
var string = 'stackoverflow Javascript Regex Help';
var pattern=/(^stackoverflow Javascript)/;

I'm looking for a way to reuse my previous pattern without having to rewrite it again. Shortly, I want to add an additional option at the end of my previous pattern (matching a space before splitting)
var newString=string.split(pattern+/(.\S*)/);
alert(newString); //Regex Help

But this doesn't work.
Is there a way I can accomplish this ?
Thank you for your hep.

A: You can use RegExp to build a regular expression from a string:
var common_pattern = "(^stackoverflow Javascript)";
var extra_pattern = "(.\\S*)"; // need to escape the escape character because the pattern is now a string
var regexp = new RegExp(common_pattern + extra_pattern);

var newString = string.split(regexp);

A: If you truly want to reuse the pattern it could be done with RegExp's toString.
Se example at JSFiddle here.
This example first splits the string using the digit 1. Then adds the digit 2 to the patter to split at 12.
Snip:
var newPattern = new RegExp(pattern.toString().slice(1,-1) + '2');

Regards
Edit:
Updated example to properly handle modifiers.


text:
Q: Text code decoding I am an English/Spanish Spanish/English translator. I have been given a job where I have to translate Spanish text messages sent from cell phones. Some of them are in code. I assume each set of figures represents a letter. Is there any website where I can find information on how to decipher the code?
For instance, the first message says:
'0x69 ox61 0x6e 0x70 0x72 0x2e 0x6e 0x65 0x74 0x2f 0x3f 0x64 0x34 0x39 0x31 0x66 0x30 0x37 0x38 0x35 0x35 0x32 0x39 0x62 0x36 0x31 0x31 0x00
Thank you for any help you provide.
Diana

A: Here's a Hex-to-ASCII decoder that can take your input format without modification (paste into the "0x... notation" box and press Convert).
BTW, in order to help you understand: those "sets of figures" each represent a byte, written as a hexadecimal number (base 16). The 0x prefix is how hexadecimal numbers are written in the C programming language (and many others). So now you have a series of bytes. Those then need to be interpreted as characters, through a set of rules known as "character encoding". This has to happen everywhere computers display text. Unfortunately, there are many different incompatible character encodings. Most of them agree on how to interpret the first 128 values a byte can take (the US-ASCII encoding). But if you deal with Spanish text, you'll quickly encounter characters that are not representable in ASCII. Then it becomes important to choose the correct encoding; I doubt there is an online tool for converting Hex notation that allows you to choose the encoding.

A: It's a hex-encoded URL, according to this translator:
ianpr.net/?d491f0785529b611

A: That looks like Ascii code to me.
See http://en.wikipedia.org/wiki/ASCII - look at the hex coding. For example 0x69 would be an i.

A: Something like 'ianpr.net/?d491f0785529b611\x00'
:)
Decoding in Python:
a = "0x69 0x61 0x6e 0x70 0x72 0x2e 0x6e 0x65 0x74 0x2f 0x3f 0x64 0x34 0x39 0x31 0x66 0x30 0x37 0x38 0x35 0x35 0x32 0x39 0x62 0x36 0x31 0x31 0x00"
b = ""
for  i in a.split():
  b = b + chr(int(i[2]+i[3], 16))
print b

A: Careful, if it is text messages then it is GSM-7, not ascii

A: Well it looks like hex values, and if it's just ASCII text in hex, you can use a converter to see what the message is.
http://www.dolcevie.com/js/converter.html


text:
Q: Symfony2 Many To Many not saving on merge in a fixture I developed some Fixtures in Symfony2 to work like crons that will be launch every 5-10 minutes. Thats becuase me application depends on a external api that is continuosly changing.
On the other hand, the api have a complete unrelated and no sense json responses and i cant trust all the data is comming in every call, so i have many nullable fiedls than can be updated on next cron "maybe". I want to treat it and store in a related database:
I have:
class Hero
{
  /**
   * @ORM\ManyToMany(targetEntity="Role", inversedBy="heroes")
   * @ORM\JoinTable(name="heroes_roles")
   **/
  private $roles;
}

class Role
{
  /**
   * @ORM\ManyToMany(targetEntity="Hero", mappedBy="roles")
   **/
  private $heroes;
}

And in me fixture, after connect with the api and get data from json:
// Roles
$rolesRepository = $manager->getRepository('ProjectStoreBundle:Role');
$rolesIndexedByName = $rolesRepository->getIndexedBy('name');

// Json con info de los heroes
$heroesInfo = json_decode(file_get_contents($this->kernel->locateResource('@ProjectStoreBundle/Resources/doc/heroes_info.json')));

foreach ($array_response['result']['heroes'] as $apiHero) {
   $hero = new Hero();
   $hero->setId($apiHero['id']);
   $hero->setName($apiHero['name']);
   ...// more normal sets

   // Update it if exists
   $manager->merge($hero);

   // Add his roles
   foreach ($heroesInfo->$apiHero['name']->roles as $role) {
        if (!empty($rolesIndexedByName[$role])) {
           $hero->addRole($rolesIndexedByName[$role]);
        }
   }
}
$manager->flush();

Things i tried:

*

*Change the order, first add roles, then merge

*Add inverse on $hero->addRole

*Put cascasde {persist}

Option 2:
public function addRole(Role $roles)
{
    $roles->addHero($this); // cascade error
    $this->roles[] = $roles;

    return $this;
}

I maybe forgive something, im learning symfony2 at time i develop the application.
Thanks in advice.
UPDATE
If i change merge for persists, the many to many relations are saved, but i cant use same script to update then.
Someone can explain me why merge is not creating relationships?

A: I found the solution days ago, forgive to answer the question:
I change just this piece of code:
// Update it if exists
$manager->merge($hero);

// Add his roles
foreach ($heroesInfo->$apiHero['name']->roles as $role) {
    if (!empty($rolesIndexedByName[$role])) {
       $hero->addRole($rolesIndexedByName[$role]);
    }
}

To this:
// Update it if exists
$mergedHero = $manager->merge($hero);

// Add his roles
foreach ($heroesInfo->$apiHero['name']->roles as $role) {
    if (!empty($rolesIndexedByName[$role])) {
       $mergedHero->addRole($rolesIndexedByName[$role]);
    }
}

And it flush all the data correctly.
Hope it helps someone.


text:
Q: Is there a standard name or implementation of the "purely applicative Either"? I frequently find use for what I call the "purely applicative Either", i.e. Either with the Applicative instance available so long as we don't implement a Monad instance as well.
newtype AEither e a = AEither { unAEither :: Either e a }
  deriving Functor

-- technically we only need Semigroup
instance Monoid e => Applicative (AEither e) where
  pure a = AEither (pure a)
  AEither e1 <*> AEither e2 = AEither (combine e1 e2) where
    combine (Right f) (Right a) = Right (f a)
    combine (Left m1) (Left m2) = Left (m1 <> m2)
    combine (Left m ) _         = Left m
    combine _         (Left m ) = Left m

It's a really useful Applicative as it provides a more powerful notion of "summarization of error" than Either's Monad instance can do. To that end, I find myself implementing it over-and-over again.
Is there a standard instance somewhere? Is there even a standard name?

A: This looks pretty similar to the AccValidation type in the validation package: http://hackage.haskell.org/package/validation-0.3.1/docs/Data-Validation.html
Edit:
In particular the following instance declaration:
instance Semigroup err => Apply (AccValidation err) where
  AccFailure e1 <.> AccFailure e2 =
    AccFailure (e1 <> e2)
  AccFailure e1 <.> AccSuccess _  =
    AccFailure e1
  AccSuccess _  <.> AccFailure e2 =
    AccFailure e2
  AccSuccess f  <.> AccSuccess a  =
    AccSuccess (f a)


text:
Q: Multiplying columns of a list of matrices I have the following list of matrices
data= {{{23,3,4,5,20.5},{24,3,1,0,20.5},{25,3,7,8,20.5},{26,6,5,4,20.5}},{{23,4,5,3,20.4},{24,4,3,5,20.4},{26,4,3,2,20.4},{27,4,5,7,20.4},{28,4,3,2,20.4}},{{23,4,5,3,20.3},{24,4,3,5,20.3},{26,4,3,2,20.3},{27,4,5,7,20.3},{28,4,3,2,20.3},{29,0,0,2,20.3}},{{23,4,5,3,20.2},{24,4,3,5,20.2},{26,4,3,2,20.2},{30,4,5,7,20.2},{29,0,0,2,20.2}}}

I want to multiply the 2nd,3rd and 4th element of each row by its 5th element,
eg: the first row would be {{{23,61.5,82,102.5,20.5},{24,61.5,20.5,0,20.5} and so on...
I know how to multiply these columns
data[[All,All,{2,3,4}]]*data[[All,All,5]]

but this generates
{{{61.5, 82., 102.5}, {61.5, 20.5, 0.}, {61.5, 143.5, 164.}, {123.,
   102.5, 82.}}, {{81.6, 102., 61.2}, {81.6, 61.2, 102.}, {81.6, 61.2,
    40.8}, {81.6, 102., 142.8}, {81.6, 61.2, 40.8}}, {{81.2, 101.5,
   60.9}, {81.2, 60.9, 101.5}, {81.2, 60.9, 40.6}, {81.2, 101.5,
   142.1}, {81.2, 60.9, 40.6}, {0., 0., 40.6}}, {{80.8, 101.,
   60.6}, {80.8, 60.6, 101.}, {80.8, 60.6, 40.4}, {80.8, 101.,
   141.4}, {0., 0., 40.4}}}
how do I put this back into data ?

A: You were one character away from the solution:
data[[All, All, {2, 3, 4}]] *= data[[All, All, 5]];

data

{{{23, 61.5, 82., 102.5, 20.5}, {24, 61.5, 20.5, 0., 20.5}, . . .

See documentation for TimesBy and Elegant operations on matrix rows and columns.

A: A couple of approaches:
f[x_] := {x[[1]], Sequence @@ (x[[-1]] # & /@ x[[2 ;; -2]]), x[[-1]]};
g = {#1, #2 #5, #3 #5, #4 #5, #5} &;
Map[f, data, {2}]
g @@@ # & /@ data


text:
Q: Console.log is printing while <%= is not I am having this Code the problem is that the line which has <%= propOfProp%> does't print anything while if I replaced it with console.log(propOfProp), it will work
<%  for (var x in data){ %>
    <%  if(data.hasOwnProperty(x)){ %>
    <%  var obj = data[x]; %>
    <%  for( var prop in obj){ %>
    <%  if(obj.hasOwnProperty(prop)){ %>
    <%  if(isNaN(prop)){ %>
    <%  findName([prop],function(err,data){ %>
    <%  for(var h in data[0]) {%>
    <%  var obj2 = data[0][h];  %>
    <%  for (propOfProp in obj2) { %>
    <%  if(isNaN(propOfProp)){ %>
    <%= propOfProp%>
    <% } }%>
    <% } %>
    <%  }); %>

    <%  } %>
    <%  } %>
    <%  } %>
    <%  } } %>

A: What <%= %> in ejs means is to interpolate and escape it (see https://github.com/tj/ejs) and not just print out a js var, you may want to do  <%- %> (see Render a variable as HTML in EJS)...
so a fix would be
<%  for (var x in data){ %>
    <%  if(data.hasOwnProperty(x)){ %>
    <%  var obj = data[x]; %>
    <%  for( var prop in obj){ %>
    <%  if(obj.hasOwnProperty(prop)){ %>
    <%  if(isNaN(prop)){ %>
    <%  findName([prop],function(err,data){ %>
    <%  for(var h in data[0]) {%>
    <%  var obj2 = data[0][h];  %>
    <%  for (propOfProp in obj2) { %>
    <%  if(isNaN(propOfProp)){ %>
    <%- propOfProp%>
    <% } }%>
    <% } %>
    <%  }); %>

    <%  } %>
    <%  } %>
    <%  } %>
    <%  } } %>

However, in the near future you may want to rethink doing all that code in the front end, since you end up calling the server either way . The idea of EJS is to render the code on the server and have all the data already there, and then you can loop through it. If possible put it into  tags on the bottom or do it on the controller (if this is MVC). Also, you don't need to loop through the properties and then hasOwnProperties, it'll only loop through the properties already present.


text:
Q: Javascript strip decimal from numeric I'm using Math.random to generate a random string passed in an ajax call.   The problem is that the string generated contains a decimal, and the server interprets this as a file.ext (which of course doesn't exist).
Ex from http.log:
File does not exist: /path/to/site/foo.php&arg=123&randval=0.5678719817071954, referer: http://site/bar.php?arg=123

Ajax used to generate link:
$(document).ready(function()
{
    $(\"#placeholder\").load(\"/foo.php?arg=123\");
    var refreshId = setInterval(function()
    {
        $(\"#placeholder\").load('/foo.php?arg=123&randval='+ Math.random());
    }, 5000);
    $.ajaxSetup({ cache: false });
});

What I'd like to end up with is:
foo.php&arg=123&randval=05678719817071954

The argument randval is not used other than to ensure I don't wind up with a cached version of the page.  It may not be needed, but this is from an example I used to set up the jquery ajax call.

A: I'd suggest, in place of Math.random(), using:
(Math.random() + '').replace('.','');

A: Math.random() returns a value between 0 and 1, to get numbers between 0 and max you need to multiply it by max. This should do:
Math.floor(Math.random() * 1e16) // 1e16 == 10000000000000000

A: Maybe easier and more common ... if you don't need to use Math.random()
 + (new Date()).getTime();

A: why not use new Date().getTime() and avoid all the hassle

A: The other answers are right on - but I overlooked an obvious type-o in my code.  The link I was writing:
foo.php&arg=123

Should be
foo.php?arg=123
enter code here

Once I updated, the file not found error was resolved.
Thanks for the suggestions on fixing the Math/decimal issue - not needed now, but useful to know.


text:
Q: Twitter Favorites and more than 20 Im using curl to fetch my Twitter favorites:
<?php
$username = "bob";
$password = "password";
$twitterHost = "http://twitter.com/favorites.xml";
$curl;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_URL, $twitterHost);
$result = curl_exec($curl);
curl_close($curl);
header('Content-Type: application/xml; charset=ISO-8859-1');
print $result;
?>

However this only fetches the last 20 favorites, not all of them.
If i amend this line:
$twitterHost = "http://twitter.com/favorites.xml";

And change it to:
$twitterHost = "http://twitter.com/favorites.xml?page=2";

I can get the next set of 20 favorites.
There doesnt appear to be anyway, using the Twitter API, to find out how many pages of favorites there are.
As such can anyone suggest the best way to get all favorites?
Or if this is not possible, get all the Tweets for a date range?

A: You should be able to call this API function:
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2%A0show
This API call "users/show" returns an attribute "favourites_count" which has this information. For example, go to this page to see, replacing "bob" with your username:
http://api.twitter.com/1/users/show/bob.xml


text:
Q: How to send a message to a Channel on all Servers I would like to send a message to all channels that are in all servers that are called "labycheck-shop" at 12 midnight.
I have already tried this but it did not work:
cron.schedule('0 0 * * *', () => {
  const channel = client.channels.cache.find(ch => ch.name === 'labycheck-shop');
  channel.send('test')
})```

// (cron is node-cron)

A: *

*This feature can turn out to be spammy on the Discord API, so you might want to keep that in mind

*I believe that you might be wanting to use <Collection>.filter instead of <Collection>.find.
The find function in the Discord.js Collections works pretty much like <Array>.find, which returns the first result it gets true for.
So what you'll want to do is, use <Collection>.filter to filter the guilds of that name, and then Loop through the array and send the message.
So kinda like this
cron.schedule('0 0 * * *', () => {
    client.channels.cache.filter((ch) => ch.name === "labycheck-shop").forEach((channel) => channel.send("Ding dong it's 12 AM"));
});

That's how it should work out, I also checked the cron expression, and that looks fine as well


text:
Q: What's the mistake in the integration of $\int \sqrt{1+4t^2}\,dt $? I am trying to solve the following irrational integral
$I=\int \sqrt{1+4t^2}\,dt $
Doing the change: $ t=\frac{1}{2}\sinh(x)$ , $dt= \frac{1}{2}\cosh(x)$
$I=\int \sqrt{1+\sinh^2x}(\frac{1}{2}\cosh x)\,dx =\int \sqrt{\cosh^2x}(\frac{1} {2}\cosh x)\,dx = \frac{1}{2}\int{\cosh^2x}\,dx$
Doing $\cosh x=\frac{e^x+e^{-x}}{2}$
$I=\frac{1}{2}\int{ (\frac{e^x+e^{-x}}{2}})^2 \,dx$$=\frac{1}{8}\int{ (e^{2x}+e^{-2x}+2}) \,dx$
$=\frac{1}{16} (e^{2x}-e^{-2x}+4x)$
from $ t=\frac{1}{2}\sinh(x)$ ->  $x= arcsinh(2t)$ and $4t=e^x-e^{-x}$ so $16t^2 +2=e^{2x}-e^{-2x}$
then
$I=\frac{1}{16} (e^{2x}-e^{-2x}+4x)=\frac{1}{16} (16t^2 +2+4arcsinh(2t))$$
I saw this solved somewhere else using another method, so I know the $16t^2 +2 $ part of the answer  is wrong, However I can't spot my mistake. Can you spot it?


text:
Q: WCF Service Works Locally but Returns 404 on Remote Server I have created the most simple of WCF services to try and learn the very basics.  When I run it on my localhost, it is working fine.  But when I deploy it to a remote server, it returns a 404.
Config:
<system.serviceModel>
  <services>
    <service name="MarathonInfo.MarathonInfoService">
      <endpoint address="http://localhost:10298/MarathonInfoService.svc"
                binding="webHttpBinding"
                contract="MarathonInfo.IMarathonInfo"
                behaviorConfiguration="Web"/>
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="Web">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="false" />
</system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

service file:
namespace MarathonInfo
{
    public class MarathonInfoService : IMarathonInfo
    {
        public String GetData()
        {
            return "Hello World";
        }
    }
}

And in the interface:
namespace MarathonInfo
{
    [ServiceContract]
    public interface IMarathonInfo
    {

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/GetData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        String GetData();
    }
}

Based on what I've found via Google I'm pretty sure I need to add a new endpoint, but I have not been able to do that with any success.  My remote URL looks like this:
http://www.mydomain.com/service/MarathonInfoService.svc

Any ideas how to fix?
Thanks!

A: The problem is with the following line:
address="http://localhost:10298/MarathonInfoService.svc"

replace it with the appropriate url when you deploy it on the server.


text: Q: Does powerAutomate generate a code and if yes is it accessible? Usually, GUI-Tools produces a code in the background. This is useful if you want to reuse the script with minor changes. If this is the case which programming language does powerAutomate generate and how can I access the code?


text:
Q: Fixing alignment of search bar using bootstrap 5.0 How can I change the alignment of the search bar and the button to the left continuously after the navbar-brand element? I tried adding justify-content-start bootstrap, text-left bootstrap classes, but none of them worked. The code snippet is given here:

    <form class="d-flex">
      <input class="form-control me-2" type="text" />
      <button class="btn btn-outline-info" type="submit">Search</button>
    </form>

A: Flex is applied to the children.  You are correct in the justify-content-start assumption - just need to add it to the parent container.  Like so:

    <form class="d-flex">
      <input class="form-control me-2" type="text" />
      <button class="btn btn-outline-info" type="submit">Search</button>
    </form>


text:
Q: Understanding the proof of the Lebesgue Covering Lemma. Here is the statement of the lemma and its proof (from Royden "Real Analysis 4th edition on pg.201 & 202").

But I do not understand how the author applied the triangle inequality, specifically I do not understand the last paragraph, why we were in need of an index $k$? why we take $1/n_{k} < (r_{0}/2).$ Could anyone explain this to me, please?

A: For $x\in B(x_{n_k}, \frac{1}{n_k})$
$$d(x, x_0)\le d(x, x_{n_k} ) + d(x_{n_k}, x_0)\le  \frac{1}{n_k} + \frac{r_0}{2} < r_0$$
That's the application of the triangle inequality.
So  $x\in B(x_0, r_0)$, and consequently, $ B(x_{n_k}, \frac{1}{n_k}) \subset B(x_0, r_0)$


text:
Q: Issue with Merging dataframes I've read through the pandas documentation on merging but am still quite confused on how to apply them to my case. I have 2 dataframes that I'd like to merge - I'd like to merge on the common column 'Town', and also merge on the 'values' in a column which are the 'column names' in the 2nd df.
The first df summarizes the top 5 most common venues in each town:

The second df summarizes the frequencies of all the venue categories in each town:

The output I want:
Ang Mo Kio | Food Court | Coffee Shop | Dessert Shop | Chinese Restaurant | Japanese Restaurant | Freq of Food Court | Freq of Coffee Shop |...
What I've tried with merge:
newdf = pd.merge(sg_onehot_grouped, sg_venues_sorted, left_on=['Town'], right_on=['1st Most Common Venue'])

#only trying the 1st column because wanted to scale down my code

but I got an empty dataframe with the column names as all the columns from both dataframes.
Appreciate any help. Thanks.


text:
Q: Object.defineProperty called on non-object With Nuxt3 and Vuelidate package.json
{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "nuxt": "3.0.0-rc.8"
  },
  "dependencies": {
    "@vuelidate/core": "^2.0.0-alpha.44",
    "@vuelidate/validators": "^2.0.0-alpha.31",
    "sass": "^1.51.0",
    "vuelidate": "^0.7.7",
    "vuetify": "^3.0.0-beta.1"
  }
}

nuxt.config.js
import {defineNuxtConfig} from 'nuxt'

export default defineNuxtConfig({
    css: [
        'vuetify/lib/styles/main.sass'
    ],
    build: {
        transpile: ['vuelidate', 'vuetify']
    }
})

error:

[nuxt] [request error] [unhandled] [500] Object.defineProperty called
on non-object   at Function.defineProperty ()     at
$id_wZFjrS4KDu (./.nuxt/dist/server/server.mjs:5133:8)     at
instantiateModule (./.nuxt/dist/server/server.mjs:39873:9)     at ssrLoadModule (./.nuxt/dist/server/server.mjs:39811:25)     at ssrImport (./.nuxt/dist/server/server.mjs:39836:13)     at
$id_2nr4xYa2an (./.nuxt/dist/server/server.mjs:5114:37)     at async
instantiateModule (./.nuxt/dist/server/server.mjs:39873:3)

I am trying to add vuelidate module to nuxt3 project. I couldn't find similar solution for Vuelidate module.


text:
Q: What is the meaning of the phrase "brain of size of Wisconsin"? I was watching Breaking Bad. In the Pilot episode Hank Schrader says this to Walter White :

"You got a brain the size of Wisconsin, but we're not gonna hold that against you."

What is the meaning of this sentence? Why did he compare his brain to a state in the US?

A: To say someone has a brain the size of a state (other than the notably small states, such as Rhode Island or Delaware) is to suggest that they are smart, and even overly smart.
The speaker is a working class sort of fellow who prides himself on his common man ways. The person he is addressing is a very nerdy science teacher.
He is in effect saying

You are an egghead and we are regular people, but we will tolerate you anyway.


text:
Q: MySQL - How to change value in column? I have a OpenCart store with more than 23000 products and I need to change one option (Requeres Shipping) for all of my products. I need to change that option in my database. I have a table n0v_product with with column shipping with value 0. I need to change shipping value to 1 for all products. How to update the value in the column with phpMyAdmin?

A: You can use a UPDATE command to change all values on column shipping to 1 on n0v_product:
UPDATE `n0v_product` SET `shipping` = 1

If you only want to set the value if shipping is 0 you can use the following:
UPDATE `n0v_product` SET `shipping` = 1 WHERE `shipping` = 0

You should check the rows before UPDATE to make sure you really want to UPDATE these rows:
-- all rows of table n0v_product
SELECT `shipping`, * FROM `n0v_product`

-- only rows with shipping = 0
SELECT `shipping`, * FROM `n0v_product` WHERE `shipping` = 0

A: Run this in a test database before running it on production but this should do the job.
UPDATE n0v_product
SET shipping = '1'
WHERE shipping = '0'


text:
Q: Azure MSAL node ClientAuthError I am trying to use @azure/msal-node on a node backend server.
I follow the tutorial on their Github page and when I try to call acquireTokenByCode i get this error:
[Tue, 30 Aug 2022 08:23:34 GMT] : @azure/msal-node@1.12.1 : Info - getAuthCodeUrl called
[Tue, 30 Aug 2022 08:23:34 GMT] : @azure/msal-node@1.12.1 : Verbose - initializeRequestScopes called
[Tue, 30 Aug 2022 08:23:34 GMT] :  : @azure/msal-node@1.12.1 : Verbose - buildOauthClientConfiguration called
[Tue, 30 Aug 2022 08:23:34 GMT] :  : @azure/msal-node@1.12.1 : Verbose - building oauth client configuration with the authority: https://login.microsoftonline.com/common/
[Tue, 30 Aug 2022 08:23:34 GMT] :  : @azure/msal-node@1.12.1 : Verbose - createAuthority called
[Tue, 30 Aug 2022 08:23:34 GMT] :  : @azure/msal-node@1.12.1 : Verbose - Auth code client created
[Tue, 30 Aug 2022 08:23:35 GMT] : @azure/msal-node@1.12.1 : Info - acquireTokenByCode called
[Tue, 30 Aug 2022 08:23:35 GMT] : @azure/msal-node@1.12.1 : Verbose - initializeRequestScopes called
[Tue, 30 Aug 2022 08:23:35 GMT] :  : @azure/msal-node@1.12.1 : Verbose - buildOauthClientConfiguration called
[Tue, 30 Aug 2022 08:23:35 GMT] :  : @azure/msal-node@1.12.1 : Verbose - building oauth client configuration with the authority: https://login.microsoftonline.com/common/
[Tue, 30 Aug 2022 08:23:35 GMT] :  : @azure/msal-node@1.12.1 : Verbose - createAuthority called
[Tue, 30 Aug 2022 08:23:35 GMT] :  : @azure/msal-node@1.12.1 : Verbose - Auth code client created
[Tue, 30 Aug 2022 08:23:35 GMT] :  : @azure/msal-common@7.3.0 : Info - in acquireToken call
ClientAuthError: network_error: Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 401 | Attempted to reach: https://login.microsoftonline.com/common/oauth2/v2.0/token
    at ClientAuthError.AuthError [as constructor] (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:500:24)
    at new ClientAuthError (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:802:28)
    at Function.ClientAuthError.createNetworkError (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:845:16)
    at NetworkManager.<anonymous> (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:3418:51)
    at step (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:79:23)
    at Object.throw (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:60:53)
    at rejected (C:\Users\user\project\node_modules\@azure\msal-common\dist\index.cjs.js:51:65)
    at processTicksAndRejections (internal/process/task_queues.js:94:5) {
  errorCode: 'network_error',
  errorMessage: 'Network request failed. Please check network trace to determine root cause. | Fetch client threw: Error: HTTP status code 401 | Attempted to reach: https://login.microsoftonline.com/common/oauth2/v2.0/token',
  subError: '',
  name: 'ClientAuthError'
}

My code:

const loggerOptions = {
  loggerCallback(loglevel, message, containsPii) {
    console.log(message);
  },
  piiLoggingEnabled: false,
  logLevel: msal.LogLevel.Verbose,
}
const clientConfig = {
  auth: {
    clientId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
    authority: "https://login.microsoftonline.com/common/",
  },
  system: {
    loggerOptions: loggerOptions
  }
};
publicMicrosoftClient = new msal.PublicClientApplication(clientConfig);

app.get('/connect', function (req, res) {
  const authCodeUrlParameters = {
    scopes: ['https://outlook.office.com/IMAP.AccessAsUser.All', 'https://outlook.office.com/SMTP.Send', 'offline_access', 'openid', 'profile', 'Mail.ReadWrite', 'Mail.Send', 'MailboxSettings.Read', 'MailboxSettings.ReadWrite', 'IMAP.AccessAsUser.All'],
    redirectUri: "http://localhost:4220/redirect",
  };
  client.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
    res.json(response);
  }).catch((error) => console.log(JSON.stringify(error)));
});

app.get('/redirect', function (req, res) {
  const tokenRequest = {
    redirectUri: "http://localhost:4220/redirect",
    scopes: ['https://outlook.office.com/IMAP.AccessAsUser.All', 'https://outlook.office.com/SMTP.Send', 'offline_access', 'openid', 'profile', 'Mail.ReadWrite', 'Mail.Send', 'MailboxSettings.Read', 'MailboxSettings.ReadWrite', 'IMAP.AccessAsUser.All'],
    code: req.query.code
  };
  const authCodeResponse = { code: req.query.code }
  client.acquireTokenByCode(tokenRequest, authCodeResponse).then((response) => {
    console.log("Successfully acquired token using Authorization Code.");
    res.sendStatus(200);
  }).catch((error) => {
    console.log(error);
    res.status(500).send(error);
  });
});

The first request works fine. I can connect with the link and I am well redirected on /redirect
If anyone has an idea what's going on?
Node version: 12.14.0
@azure/msal-node version: 1.12.1

A: Please check ,it can be issue when DNS is not resolved  .Try to replace localhost with the IP address of your machine.

*

*For native and mobile apps, use one of the following: https://login.microsoftonline.com/common/oauth2/nativeclient for apps using embedded browsers or with http://localhost for apps using system browsers.

*As you have given openid offline_access, profile permissions, please check the same api permissions are given in azure ad portal and been granted admin consent from portal or while authentication.

*In  authorization code flow , the client initially directs the user to the /authorize endpoint and requests scopes like the openid, offline_access, and https://graph.microsoft.com/mail.read permissions from the user.

Reference: Microsoft identity platform and OAuth 2.0 authorization code flow - Microsoft Entra | Microsoft Docs


text:
Q: Best practice for storing enums and user defined values I am in situation where I need to store a payment type enumeration value in the database for record keeping.
The problem is that I would like to add the ability for end user define their own value types.
I understand that I can use a negative range in my enumeration for my own values since user defined types will have an id greater than 0 but would that be a correct approach?
Or maybe I should have a second column like CustomPaymentType and referenced to PaymentType table for a data consistency?

A: Don't use an enumeration.
Enumerations are only useful for things that are constant by their nature, like days of the week.
Instead use a reference table in the data base like CustomPaymentType (Id,PaymentTypeName)
then you can use a class that looks like:
public class CustomPaymentType
{
    public string paymentTypeName { get; private set; }
    public int Id { get; private set; }

    // if you need "Constant payment types usable in code, just add something like:
    public static CustomPaymentType CashPayment
    {
        get { return new CustomPaymentType() { Id = 7, paymentTypeName= "CashPayment" } }
    }

    public static CustomPaymentType CreditPayment
    {
        get { return new CustomPaymentType() { Id = 7,paymentTypeName= "CreditPayment" } }
    }
}

This approach is pretty good, because you have both the ease of coding about well known specific instances that you may need while coding, and its also very extendable.


text:
Q: Return malloc struct gets freed from memory So I compiled this code both at the terminal with MinGW and it was originally compiled in Visual Studio both not showing any sign of wrong-doing.
It is a code for Dynamic Arrays and after hours of debugging in VS I found that when I malloc another structure and array, copy all the integers and then point the old array to the new one it won't remain in the memory. Also the size and threshold are not pointers, but shouldn't they not be freed from memory just like the structure? The code is as follows. I also have it available (a bit changed) at my GitHub here
I'm probably doing something really stupid, but I've burned my mind into this and can't get to any conclusions. I resisted asking it at stackoverflow (because most of my mistakes are really dumb) but after hours of debugging I gave up.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct DArray {
    int *array;     // Array of integers
    int size;       // Actual Size
    int maxSize;    // Maximum size.
    bool threshold; // maxSize / 2
} DArray;

DArray * getDArray(int maxSize);
int pushValueDArray(DArray *array, int value);
int popValueDArray(DArray *array);
int displayDArray(DArray *array);
int checkSize(DArray *array);

DArray * getDArray(int maxSize)
{
    if (maxSize < 0) {
        printf("\nFATAL ERROR\n");
        return NULL;
    }
    DArray *newArr = (DArray *)malloc(sizeof(DArray));
    newArr->size = 0;
    newArr->maxSize = maxSize;
    newArr->threshold = false;
    newArr->array = (int *)malloc(sizeof(int) * maxSize);
    return newArr;
}

int pushValueDArray(DArray *array, int value)
{
    checkSize(array);
    array->array[array->size] = value;
    (array->size)++;
    return 0;
}

int popValueDArray(DArray *array)
{
    checkSize(array);
    array->array[array->size] = 0;
    (array->size)--;
    return 0;
}

int displayDArray(DArray *array)
{
    int i;
    if (array->size == 0) {
        printf("\n[ Empty ] \n");
        return 1;
    }
    printf("\n[ ");
    for (i = 0; i < array->size; i++) {
        printf("%d, ", array->array[i]);
    }
    printf("nil ]\n");
    return 0;
}

int checkSize(DArray *array)
{
    int i;
    if (array->size > array->maxSize / 2) array->threshold = true;
    if (array->size >= array->maxSize - 1) {
        // Grow
        DArray *nArray = getDArray(array->maxSize * 2);
        DArray *kill = array;
        for (i = 0; i < array->size; i++) {
            nArray->array[i] = array->array[i];
        }
        nArray->size = array->size;
        nArray->threshold = false;
        array = nArray;
        free(kill);
        return 0; // OK
    }
    else if (array->threshold && array->size < array->maxSize / 2) {
        // Shrink
        DArray *nArray = getDArray(array->maxSize / 2 + 1);
        DArray *kill = array;
        for (i = 0; i < array->size; i++) {
            nArray->array[i] = array->array[i];
        }
        nArray->size = array->size;
        nArray->threshold = false;
        array = nArray;
        free(kill);
        return 0; // OK
    }
    else {
        // OK
        return 0;
    }
}

int main(int argc, char const *argv[])
{
    DArray *array = getDArray(100);
    int i;
    for (i = 0; i < 2000; i++) {
        pushValueDArray(array, i);
    }
    for (i = 0; i < 2000; i++) {
        popValueDArray(array);
    }
    displayDArray(array);

    printf("\nsize %d", array->size);
    return 0;
}


text:
Q: How to select only rows that are not in another table without getting data of the other table - PLSQL Im trying to SELECT all rows from one table with a specific condition. Im using Oracle PLSQL.
I have two tables:
Books

*

*id

*name

Page

*

*id

*words

*book_id

One book can have multiple pages.
I want to find all books that don't have any page with 50 words.
The only solution I've found is to make a Left Outer Join and then filter by nulls.
Select * from Books b
LEFT OUTER JOIN Page p on b.id = p.book_id and p.words = 50
where p.words is null

I think its not a good solution, but it works, do you know any other way to do that?
I don't want to take any information about Pages. If I make a normal join and then I apply the condition I get N rows for a Book, and I only want to get 1 row for each Book
Thanks.

A: You could adjust your select so it is only b.*.
Possibly a more common alternative is not exists:
select b.*
from Books b
where not exists (select 1
                  from Page p
                  where b.id = p.book_id and p.words = 50
                 );

The two methods should have similar performance characteristics.


text:
Q: How to publish and connect to my own WCF endpoint without Admin rights I have a WCF REST API implemented in a C# class library.  Ultimately I would like the service to be able to be hosted in my own process, or as a Windows service, depending on the user's choice.  So it needs to support both inproc and HTTP bindings.
The following works as admin, but not as a regular user (says it doesn't have rights to open up the HTTP port).
What's my next step?  Should I be using a different protocol for in-proc?  So long as I retain the ability to have it cross-machine on the HTTP binding, I'm satisfied.
        WebServiceHost host = new WebServiceHost(typeof(SapphireServiceLib.SapphireService), new Uri("http://localhost:8080/") );
        try
        {
            ServiceEndpoint ep = host.AddServiceEndpoint(typeof(SapphireServiceLib.ISapphireService), new WebHttpBinding(), "");
            host.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to start Sapphire Service Host: " + ex.Message);
            return;
        }

        // Next, connect to the endpoint for our own use

        try
        {
            // Set the max msg large, otherwise max size would be 64K and we couldn't fetch all the logs.
            // REVIEW I suppose this might expose it to a Denial of Service attack if public

            var binding = new WebHttpBinding() { MaxReceivedMessageSize = Int32.MaxValue };

            ChannelFactory<ISapphireService> cf = new ChannelFactory<ISapphireService>(binding, "http://localhost:8080");
            cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
            SapphireService = cf.CreateChannel();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to connect to service endpoint: " + ex.Message);
            return;
        }

A: If you want to keep the http binding you have to use the netsh http add urlacl url=http://+80/YourService command to allow a process without admin rights to use it.
Another option is to switch to netTcpBinding for instance.


text:
Q: User Data Storage Using MVC in Java I'm still new to MVC programming in Java. My question is, in what part of the program is it best practice so store user information? I have a login form and I handle the login in one of my models. What's the best way to make the user data available to the entire application? I was thinking about adding field variables to my model and simply storing the data there, but since I have several models I wouldn't be able to retrieve the data from other models. Is it a good idea to create an object that stores the user data and calling that object from all models? Or is there a better approach? Thanks!

A: First of your question is too generic an is risking its closure.
Your gut feeling to not mix data is right. Keep whatever user data together. Maybe for now it's just a username but this kind of data tend to grow over time and you want this flexibility later.
Think about where you need that data most. User data is needed for authentication, authorization and tracking.
If you think of the relation of user data and user generated data, or the interaction between content and user data, how would you structure such relations?
If you think about performance, which subset of the user data is at least necessary to fullfil your requirements?
I know I am wage but your question is wage itself.
Try to step back from your code and think more about the architecture of your software.


text:
Q: Can I create power BI report from my dot net web application? Can I create power BI report from my dot net web application ? I mean I don't want to create report from power BI desktop or online power BI service. I want to create power BI report from my web application.

A: No, at minimum you need to be able to reference this service for the Power BI API's. Reference: Power BI for Developers and Power BI Developer Portal


text:
Q: How to prepare Windows 10 so that it can survive a complete change of motherboard and chipset without reinstall? I recently got a chance for a cheap upgrade to the aging PCs of my wife and myself. We both had Phenom II X2 CPUs with 10 year old motherboards and the new hardware has Gen 7 intel CPUs with respective motherboards. Not exactly new, but way better than what we have anyway.
I first tried upgrading my PC (just swapped out the MB/CPU/RAM but left everything else), however that didn't go so well. Windows couldn't boot with the error message INACCESSIBLE BOOT DEVICE. I couldn't even get into Safe Mode! Interestingly the recovery Command Prompt did work and I could see my hard drive just fine. After spending several fruitless hours I finally caved in and reinstalled Windows.
But now I need to do the same on my wife's computer. I'm wondering - perhaps there are some preparations that will allow me to avoid a complete reinstall?
Preemptive comment: If anyone's worried about Windows activation, it's all good - we got Retail versions of Windows precisely because we knew we'd want to upgrade someday.


text:
Q: Standar Users and wifi connection I just can´t find the way to make that the system doesn´t ask for Admin pass when an standard users want to change their wifi connection.

A: The default Ubuntu network-manager has two types of connections - system connections and user connections. System connections get saved in /etc/NetworkManager/system-connections with mode 600 (i.e. -rw-------) and do require administrator privileges to create or edit.
Non-privileged users should be able to create new user-connections, however there is a wrinkle in the UI which appears to make it impossible - when the Add dialog is instantiated, it has the Available to all users checkbox pre-checked and grayed-out - this identifies the connection as a system-connection, and the non-privileged user can't save it as such - and apparently can't deselect the box to make it a (saveable) user-connection:

However, once anything is typed into the SSID box (even a space) the 'Available to all users' box becomes editable:

Once that box is unchecked, it should be possible for an unprivileged user to edit and save the connection properties.


text:
Q: Python Recording points on graph Still new to python, so I a little help would be appreciated.
I have two series of data like shown in the image below, one with x axis of age and one is depth, and different y axis too. Which have troughs and peaks that look offset to each other. Which is true but, that offset changes throughout time. My aim is to calibrate these two graphs on a common timescale by manually taking the coordinates of the peaks which match. And then working out dx1/dx2 over a selected range, i.e between the first two clicks and then the same between the next two set of manually selected clicks. And from that I can transpose to the same graph both as an age.
My issue through, is how to seperate the clicking and recording points on the figure as two separate datasets. I think the best way is to have two figures on top of each other, but I don't know how to edit the function so.
Many thanks in advance
Image of dataset
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import trapz
import sys

date_record="Date.csv"  #The record that you have a timescale for and a value
depth_record="Depth.csv"
date_record=pd.read_csv(date_record)
depth_record=pd.read_csv(depth_record)

date=date_record[[0]]
print(date)
del_18O=date_record[[1]]

depth=depth_record[[0]]
Corg=depth_record[[1]]

x=date
y=del_18O

x1=depth
y1=Corg

fig,ax = plt.subplots()
ax.plot(x,y)

ax2 = ax.twinx().twiny()
ax2.plot(x1,y1,color="green")

ax = plt.gca()
ax.set_ylim(ax.get_ylim()[::-1])

ax2 = plt.gca()
ax2.set_ylim(ax.get_ylim()[::-1])

coords = []

def onclick(event):
    global ix, iy
    ix, iy = event.xdata, event.ydata
    print ('x =',ix , 'y =',iy)

    global coords
    coords.append((ix, iy))
    ax2.plot(ix,iy,color="red",markersize=5,marker=".",linestyle="")

    if len(coords) == 5:
        fig.canvas.mpl_disconnect(cid)
        #print(coords)
        #ax2.plot(coords,color="red",markersize=5,marker=".",linestyle="")
        #print(coords)
        sys.exit

    return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)
print("adding")
print(coords)


text:
Q: Display plots based on tabPanel() selection in a shiny app I have the shiny app below I have a tabPanel() with to subpanels. I want by default both plots to be displayed. Then if the user press SUBTAB 1 only the left plot to be displayed. If he presses SUBTAB 1 again both will be displayed again. The same logic for SUBTAB 2 and right plot.
library(shiny)

ui <- fluidPage(

  titlePanel("Explore Data"),

  tabsetPanel(
    tabPanel("tabPanel 1",
             tabsetPanel(
               tabPanel("SUBTAB 1",
                        fluidRow(
                          column(width = 6,
                                 plotOutput("Plot1", height = "350px")
                          )
                        )
               ),

               tabPanel("SUBTAB 2",
                        fluidRow(
                          column(width = 6,
                                 plotOutput("Plot2", height = "350px")
                          )
                        )
               )
             ) #Close inner tabsetPanel
    )

  ) #Close outer tabsetPanel
) #Close FluidPage

server <- function(input, output) {

  output$Plot1 <- renderPlot({
    plot(seq(0,10), seq(100, 110), col = "red")
  })

  output$Plot2 <- renderPlot({
    plot(seq(0,10), seq(0, 10)^2, type = "b")
  })
}

# Run the application
shinyApp(ui = ui, server = server)


text:
Q: not able to show tool tip items for image button when we are hovering I am trying to do two things at one time when i hover the image button, I need to show another image and i need to show tool tip as well
I am successfully achieved  first one (i.e) showing another image when i do hovering on the image button, but not able to show the tool tip for that image button.
 and this is my jquery code...
BUTTON :1  (Search Button)
 $(function () {
    $("#Search").mouseover(function () {
        var hoverimg = $(this).attr("src").match(/[^\.]+/) + "_hover.png";
        var orgimg = $(this).attr("src");
        $(this).attr("src", hoverimg);
        $(this).attr("title", orgimg);
    })
        .mouseout(function () {
            $(this).attr("src", $(this).attr("title"));
        });
});

Button 2 :Reset Button
$(function () {
    $("#Reset").mouseover(function () {
        var hoverimg = $(this).attr("src").match(/[^\.]+/) + "_Hover.png";
        var orgimg = $(this).attr("src");
        //var tarr = orgimg.split('/');
        //var file = tarr[tarr.length - 1];
        //var data = file.split('.')[0];
        //alert(data);
        $(this).attr("src", hoverimg);
        $(this).attr("title", orgimg);
       // $(this).attr("title", data);

    })
    .mouseout(function () {
         $(this).attr("src", $(this).attr("title"));
      });
});

for both image buttons i need to do same thing in second button if i execute the commented Out lines  (i am getting tool tip item having the name (Reset)  but when i mouse out from that button , i am losing the button image ...
For search button i need to show tool tip name like Search and  for reset button i need to show the tooltip item like Reset
and this is the HTML mark up for those two buttons

would any one pls help on this , any suggestions and any ideas that would be very grateful to me ...
Many thanks in advance.....

A: Try this HTML for the purpose
var orgimg
var orgimg2
$(function () {
    $("#Search").mouseover(function () {
        var hoverimg = $(this).attr("src").match(/[^\.]+/) + "_hover.png";
        orgimg = $(this).attr("src");
        $(this).attr("src", hoverimg);

    })
    .mouseout(function () {
        $(this).attr("src", orgimg);
    });
});

$(function () {
    $("#Reset").mouseover(function () {
        var hoverimg = $(this).attr("src").match(/[^\.]+/) + "_Hover.png";
        orgimg2 = $(this).attr("src");
        //var tarr = orgimg.split('/');
        //var file = tarr[tarr.length - 1];
        //var data = file.split('.')[0];
        //alert(data);
        $(this).attr("src", hoverimg);

       // $(this).attr("title", data);

    })
.mouseout(function () {
     $(this).attr("src", orgimg2);
  });
});

HTML :

Thanks

A: For Search button
$(function () {
    var orgimg = $("#Search").attr("src");
    var tooltip = $("#Search").attr("id");
    $("#Search").mouseover(function () {
        var hoverimg = $(this).attr("src").match(/[^\.]+/) + "_hover.png";

        $(this).attr("src", hoverimg);
        $(this).attr("title", tooltip);
    })
        .mouseout(function () {
            $(this).attr("src", orgimg);
        });
});

Follow similar approach for Reset button. Since you don't have title in mark up I'm using id as the title (tooltip)
Fiddle


text:
Q: Handling errors using angular $q.all I have an angular app that displays an editable grid to the user. The user is allowed to edit multiple rows in the grid, then save all those changes at once. When they do this, I am using $q.all to send out all the update calls to an API in parallel.
I want to be able to display an error to the user for each call that fails with some of the information about the object that wasn't saved correctly, but I can't figure out how to get that information out of the error handler.
var ops = []

_.each($scope.items, function (item) {
    if(item.Modified)
        ops.push(dataService.update(item.itemID, item.otherField))
})

$q.all(ops)
.then(function (repsonse) {
    //success
},
function (response) {
    //in here I want to output the itemID and otherField values for the item(s) that failed
})

Each item that is being sent out on the API call has a few properties on it (itemID and otherField). I want those values to be include in the error message to the user.
Is this possible using q.all or do I have to use another method?

A: $q.all will trigger the error callback if any of the operations fail at any time, but in your case you just want to record which ones (if any) failed without triggering any additional error.  I would use return a promise from .catch:
ops.push(dataService.update(item.itemID, item.otherField))
.catch(function () {
    return {
        status: "failed",
        id: item.itemID
    };
});

Then in $q.all's callback you can iterate over the responses and check for .status == "failed" and check those IDs.


text:
Q: How can my app allocate more heap memory in Android 4.0? (Not enough memory for my app) I'm desesperate with my app. I'm developing an app for a dedicated barcode scanner Android based device. It's like an old phone (CPU Cortex-A8 OMAP 1Ghz, 512MB RAM), with Android 4.0. I can't root the system, nor update it, i've talked with the manufacturer.
The problem is that can't finish a simple (JSON) login. It tries to allocate more memory, but it can't.

Here is the same activity and the same process in the same network, but in an LG G2 (it tooks about 5s doing the login and the sync, as expected)

In the barcode scanner device, I removed or hibernated ALL of the apps I can, I've installed Zend Launcher (which has a very little memory footprint), but I'm out of ideas now. I've tried android:largeHeap on manifest, without success.
Somebody has an idea for me? Thanks in advance
PS: The app must run in that barcode scanner, working on LG G2 is only for test and comparative purposes.
EDIT: I don't care about other apps in background, because this device will basically use this app, and nothing else.

A: It was my fault. The peaks on the memory was lead by a graphical resource in the loading screen, not an OOM. And the log-in proccess took tooo much.


text:
Q: Return Statement JsonResult inside WcfCall How can I return the Json for the ActionResult while using a WCF call?
The below works if I was using EF and a using block for the db call.
But it is showing me the errors I commented out.
public JsonResult GetNames(string name)
{
    WcfWebProxy.Using(delegate(IMyWebService client)
    {
        var names = client.GetAllNames().Select(f => new {Text = f.NewNames});
        return Json(names.ToList(), JsonRequestBehavior.AllowGet);
        //Return Type Is Void
    });
}
//Return Statement Missing

A: You could use a closure:
public ActionResult GetNames(string name)
{
    ActionResult res = null;

    WcfWebProxy.Using(client =>
    {
        var names = client.GetAllNames().Select(f => new
        {
            Text = f.NewNames
        });
        res = Json(names.ToList(), JsonRequestBehavior.AllowGet);
    });

   return res;
}

Of course if the WcfWebProxy.Using method is asynchronous you should use asynchronous controllers as illustrated in this MSDN article: http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx
And by the way that's definitely something you should consider if you are dealing with I/O intensive operations such as calling WCF services. And with .NET 4.5 and the async/await pattern your code might even be readable.


text:
Q: Load DTD (Document Type Definition) XML I work with XML load. but i have problem with DTD XML Load.
My XML Load code is (in C#) -
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version='1.0' encoding='utf-8'?>
<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<soap:Body>
<ProcessTGJob xmlns='http://dpi.careerbuilder.com/WebServices/RealTimeJobPost'>
<Batch>
<Header>
<Field name='CBVendorID' value='ED3H3MG5WM50GQP729GL' />
</Header>
<Job>
<Field name='CBDescription' value='Test Description' />
</Job>
</Batch>
</ProcessTGJob></soap:Body>
</soap:Envelope>");

Response.ClearHeaders();
Response.ContentType = "text/xml;charset=UTF-8";
string xmlString = soapEnvelopeXml.InnerXml;
Response.Write(xmlString);
Response.End();

when execute code it's always give an error is an unexpected token.
I can't understand what is the problem in code. please help me .
Thanks for your help.

A: Change the content-type as text/xml or application/xml;


text:
Q: Transparent Backgrounds for Screens in React Navigation 5.x I'm trying to use the same background for every screen in an ios/android app, without having it move when the screens transition. In React Navigation 4 there was this solution: How to set background image with react native and react navigation?:
const AppNavigator = createAppContainer(
  createStackNavigator(
    {
      Home: {screen: Home},
      Vocabulary: {screen: Vocabulary},
      AddWord: {screen: AddWord},
    },
    {
      initialRouteName: 'Home',
      headerMode: 'none',
      cardStyle: {backgroundColor: 'transparent', shadowColor:'transparent'},
      transparentCard: true,
      transitionConfig: () => ({
        containerStyle: {
          backgroundColor: 'transparent',
        },
      }),
    },
 ),
);

But now in version 5 things have changed! You can do this:
<Stack.Screen
  name="Screen2"
  component={Screen2}
  options={{
    cardStyle: {
      backgroundColor: 'transparent',
    },
    cardStyleInterpolator: CardStyleInterpolators.forVerticalIOS
  }}
/>

You have to do it on every screen (which is fine, although awkward), but then when you navigate to a new screen, the previous screen just moves over about 25% underneath, so it's still visible, although it's off to the side a bit. It looks really awkward:

So then I thought about using a cardStyleInterpolator function (as described here: https://reactnavigation.org/docs/en/stack-navigator.html#navigationoptions-used-by-stacknavigator), however it only lets you return styles for these elements:
containerStyle - Style for the container view wrapping the card.
cardStyle - Style for the view representing the card.
overlayStyle - Style for the view representing the semi-transparent overlay below
shadowStyle - Style for the view representing the card shadow.

and not for the previous card.
How do I make it just slide away and make room for the new elements, while keeping the background stable?

A: I managed to do this by modifying the forSlide example in the cardStyleInterpolator examples from the documentation.
The modified interpolator looks like this:
const forSlide = ({ current, next, inverted, layouts: { screen } }) => {
  const progress = Animated.add(
    current.progress.interpolate({
      inputRange: [0, 1],
      outputRange: [0, 1],
      extrapolate: 'clamp',
    }),
    next
      ? next.progress.interpolate({
          inputRange: [0, 1],
          outputRange: [0, 1],
          extrapolate: 'clamp',
        })
      : 0
  );

  return {
    cardStyle: {
      transform: [
        {
          translateX: Animated.multiply(
            progress.interpolate({
              inputRange: [0, 1, 2],
              outputRange: [
                screen.width,
                0,
                screen.width * -1, // change the coefficient here
              ],
              extrapolate: 'clamp',
            }),
            inverted
          ),
        },
      ],
    },
  };
};

What this does is that instead of moving the previous screen only 30% to the left, it moves it one full screen width to the left.
Then I just passed the forSlide function as a cardStyleInterpolator field inside of the screenOptions prop of the Stack.Navigator.
<Stack.Navigator
    {...otherNavigatorProps}
    screenOptions={{
        headerShown: false,
        cardStyle: {
            backgroundColor: 'transparent',
        },
        cardStyleInterpolator: forSlide,
    }}
>

A: I wanted a linear gradient on every page but you could do the same with an image just make an component image.
Initially I tried to put this in the parent component and make the background transparent on the Drawer Navigation using card styles. this did not work for me.
I found cardOverlay in the doc and added a component in that and sent it back using zIndex behind everything and did some css to make it appear on the background.
I applied this to the Drawer Navigation
// screenOptions
  cardOverlayEnabled: true,
  cardOverlay: () => (
    <LinearGradient
      // Background Linear Gradient
      colors={['red', 'blue']}
      style={styles.background}
    />
  ),
  cardStyle: {
    backgroundColor: 'transparent',
    opacity: 1,
  },

// styles
const styles = StyleSheet.create({
  background: {
    position: 'absolute',
    left: -100,
    right: 0,
    top: 0,
    bottom: 0,
    height: 700,
    zIndex: -10,
  },
})


text:
Q: Programatically creating a view controller view using an external class I'm trying to create a class that will allow me to easily implement tutorial screen "overlays" within any view controller.  I'm using the following as a reference:
http://highoncoding.com/Articles/824_Creating_Pulse_Application_Like_Tutorial_Overlay.aspx
So, my hope would be I could create a class ( i.e. TutorialOverlay.h / TutorialOverlay.m ), and then inside a  given view controller (i.e. VievController.h / ViewController.m ) I could instantiate an instance of that class and create a tutorial screen overlay by doing something like this:
@property (nonatomic,strong) TutorialOverlay *tutorialScreen;
@synthesize tutorialScreen = _tutorialScreen;
self.tutorialScreen = [[TutorialOverlay alloc] initWithValues:@"specialscreen.png"];
[self.tutorialScreen showScreen];
Where I'm stuck is this:  Since I squirreled all the code from the highoncoding.com example into this external class ( i.e. TutorialOverlay.h / TutorialOverlay.m ), that code can't do the last [self.view addSubview:topView] because the external class can't see/use the view in the view controller that called it.
I'm not sure whaere to go to make this work - delegates?  Make TutorialOverlay.h / TutorialOverlay.m a subclass of UIView?
Any help and guidance appreciated - it would be nice to be able to whip these type of tutorial screens out at easily and add extra logic that would make them only run the first time an app runs, etc. rather than re-code the methods in every view controller!


text:
Q: windows batch, redirect cmd start, capture both stdout and error In need to start some command and capture both it's stdout and stderr in a log file.
start cmd /c myprogram.exe ^> log.txt 2>&1

But in log.txt are not printed stderr, instead they goes to the newly started shell.
In addition, the how can I print something in the new shell like "Please wait..."
Thanks very much

A: If your complex command is not quoted, then all special characters must be escaped.
start cmd /c echo blabla ^& echo test ^& my_command ^> log.txt 2^>^&1"

A: If you would like to display please wait it would be written as:
    echo Please Wait...

A: Ok, I found'it, sorry for such dumb question. At least on XP multiple commands must be quoted.
Log working too now for both err + out.
start cmd /c "echo blabla & echo test & my_command > log.txt 2>&1"


text:
Q: J2K read in Tomcat doesn't work I am facing the problem with loading J2K image files (jp2, jp2000) in my java application. What is strange is the fact, that the application runs correctly (the file is successfully read from disk) when it runs as standalone java application (or in tests).
After deployment on Tomcat application server the ImageIO.read(..) method returns null every time.
Any help is appriciated.
Shimon

A: Update: After reviewing comment from @haraldK - the solution is well described on page https://github.com/haraldk/TwelveMonkeys (section Deploying the plugins in a web app).
You need to define listener in your web.xml:
<web-app ...>

...

    <listener>
        <display-name>ImageIO service provider loader/unloader</display-name>
        <listener-class>com.twelvemonkeys.servlet.image.IIOProviderContextListener</listener-class>
    </listener>

...

</web-app>

You also need to add this Maven dependency to your project:
<dependency>
   <groupId>com.twelvemonkeys.servlet</groupId>
   <artifactId>servlet</artifactId>
   <version>3.0.2</version>
</dependency>

Other, less prefered solution is (this was my first solution mentioned here):
After doing some googling I have found this page - https://blog.idrsolutions.com/2013/03/getting-jai-jpeg2000-to-run-on-glassfish-server-without-a-npe/ which discribes problem of resolution of J2K imageio service provider, when using application server such as glassfish or tomcat.
According to this article, the solution is simple. Just use the reader directly:
public BufferedImage getJPEG2000Image(byte[] data){

ImageInputStream iis = null;
BufferedImage image=null;
  try {
    iis = ImageIO.createImageInputStream(new ByteArrayInputStream(data));
    com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi j2kImageReaderSpi = new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi();
    com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReader j2kReader = new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReader(j2kImageReaderSpi);
    j2kReader.setInput(iis, true);
    image = j2kReader.read(0, new com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam());
  }
  catch (Exception e){
      e.printStackTrace();
  }
  return image;
}

This Maven dependency is needed as well:
<dependency>
   <groupId>com.sun.media</groupId>
   <artifactId>jai_imageio</artifactId>
   <version>1.1</version>
</dependency>


text:
Q: Send Row and Section through Tag in Button Swift I have this inside cellForRowAtIndexPath
   cell.plusBut.tag = indexPath.row
   cell.plusBut.addTarget(self, action: "plusHit:", forControlEvents: UIControlEvents.TouchUpInside)

and this function outside:
func plusHit(sender: UIButton!){
    buildings[sender.tag].something = somethingElse
}

Is it possible to send the indexPath.row and indexPath.section, or some alternative??
Thanks!
EDIT
I approached it like this:
My Custom Button
class MyButton: UIButton{

    var myRow: Int = 0
    var mySection: Int = 0

}

My Custom Cell
class NewsCell: UITableViewCell{

    @IBOutlet weak var greenLike: MyButton!

In CellForRowAtIndexPath
    cell.greenLike.myRow = indexPath.row

I get an error on this line.

A: You can create a subclass of UIButton and create an extra property section in it. And then you can use that class for cell button. You can do the same for row.
Here are few possible ways after subclassing UIButton
cell.plusBut.tag = indexPath.row
cell.plusBut.section = indexPath.section

Or
cell.plusBut.row = indexPath.row
cell.plusBut.section = indexPath.section

Or
cell.plusBut.indexPath = indexPath

Choose whatever suits you.

A: Here's a really easy solution I use:
in CellForRow:
button.tag = indexPath.row
cell.contentView.superview?.tag = indexPath.section

in the function retrieve it like this:
func buttonTapped(_ sender: Any) {
    let button = sender as! UIButton
    let row = button.tag
    let sec = button.superview?.tag

    //retrieve item like self.array[sec][row]
    //do the rest of your stuff here
}

A:
Is it possible to send the indexPath.row and indexPath.section, or some alternative??

If you impose a limit on the number of possible rows in a section, you can combine the two into a single number. For example, if you're willing to say that there will always be fewer than 1000 rows in a given section, you can use:
cell.plusBut.tag = (indexPath.section * 1000) + indexPath.row

and then use mod and division operators to recover:
row = sender.tag % 1000
section = sender.tag / 1000

Another possibility is to check the button's superview (and it's superview, etc.) until you find the cell. Once you have the cell, you can get the index path for that cell from the table.
A third option, perhaps the best one, is to have the button target the cell rather than some other object. The cell can then trigger an action in the view controller or other object using itself as sender.

A: Swift 2.x - Extension with Associated Objects
private struct AssociatedKeys {
static var section = "section"
static var row = "row"
}

extension UIButton {
var section : Int {
    get {
        guard let number = objc_getAssociatedObject(self,   &AssociatedKeys.section) as? Int else {
            return -1
        }
        return number
    }

    set(value) {
        objc_setAssociatedObject(self,&AssociatedKeys.section,Int(value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}
var row : Int {
    get {
        guard let number = objc_getAssociatedObject(self, &AssociatedKeys.row) as? Int else {
            return -1
        }
        return number
    }

    set(value) {
        objc_setAssociatedObject(self,&AssociatedKeys.row,Int(value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}
}

usage:
//set
cell.contextMenuBtn.section = indexPath.section
cell.contextMenuBtn.row = indexPath.row
//read
func showContextMenu (sender:UIButton) {
    let track = dictionarySongs[sender.section][sender.row]
    ...
}

A: Send Row and Section through in Button you can use tag and accessibilityIdentifier, take a look:
Set value
 button.tag = indexPath.row
 button.accessibilityIdentifier = "\(indexPath.section)"

Get Value
let indexRow = button.tag
let indexSection = Int(button.accessibilityIdentifier!)

A: I suggest another approach. I don't like the subclass solution, I don't think the button should know its position.
Why not use a dictionary to translate the button into the IndexPath
// First initialize the lookup table
var buttonPositions = [UIButton: NSIndexPath]()

// add each button to the lookup table
let b = UIButton()
let path = NSIndexPath(forItem: 1, inSection: 1)

buttonPositions[b] = path

// Looking it up works like this
buttonPostions[activeButton]?.row

A: You can assign a custom tag for a UIButton via extension, take a look:
extension UIButton {

private struct ButtonTag {

    static var tagKey = "key"

}

var myTag : (Int , Int)? {

    set  {
        if let value = newValue {
            objc_setAssociatedObject(self, &ButtonTag.tagKey, value as! AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    get {
        return objc_getAssociatedObject(self, &ButtonTag.tagKey) as? (Int , Int)
    }
  }
}


text:
Q: How do I escape quotes for JSON conversion in Bash I have a file which I need to convert to a JSON string and it needs to be done via bash.
My test file looks like
1
2
'
3
4

Here is what's happening
$ LOG=$(cat file)
$ printf '{"log": "%q"}\n' "$LOG"
{"log": "$'1\n2\n\'\n3\n4'"}

Things seem ok like it's handling the newlines and the ', but it's adding a $' at the start and a ' at the end.

A: The single quote does not need special handling to be included in a JSON value.  Double quotes, newlines, tabs, etc. will need to be escaped or encoded though.  It is easiest to use a JSON-aware tool for doing this.  I'm mentioning jo and jq below.

jo log=@file

This uses jo to create a JSON document with a single key, log, whose value will be a JSON-encoded string consisting of the contents of the file file.
Output given the data in the question:
{"log":"1\n2\n'\n3\n4"}

You could also get the data base64-encoded by using
jo log=%file

(I'm only mentioning this because it's a neat feature of jo).
Output:
{"log":"MQoyCicKMwo0Cg=="}

Using jq:
jq -c -Rs '{ log: . }' file

This reads the raw input from file and converts it into a single string.  This string is used as the value for a log key in an object which gets outputted.
The output, given the data in the question:
{"log":"1\n2\n'\n3\n4\n"}

(Notice that the final newline is preserved here, but not in the jo output).
To get base64-encoded data (would you want to):
jq -c -Rs '{ log: (.|@base64) }' file

A: The simplest is to use three consecutive printf, the main one with %s instead of %q:
$ printf '{"log": "'; printf '%s\\n' $(<file); printf '"}\n'
{"log": "1\n2\n'\n3\n4\n"}


text:
Q: Finding generators for a non-normal group How would I find the generators for a non-normal index 3-subgroup of the free group $\langle a,b| - \rangle$ ?. I know that a finitely generated free group can be realised as the fundamental group of a wedge of circles, so it seems I should be looking at the covering space of this bouquet. If I consider $G = S_{3}$ and $H = \{(1),(12)\}$ I know that is not-normal of index 3, but then what?
Thanks

A: Some ideas:
Define a set map $${a,b}\to S_3\;,\;\;a\mapsto (12)\;,\;\;b\mapsto (123)\;$$ and extend it to a group homomorphism $\;\pi:F(a,b)\to S_3\;$ using the universal property of free groups. If the homomorphism's kernel is $\;N\;$ , then you have
$$F(a,b)/N\cong S_3.$$
Well, by the correspondence theorem, what you want is $\;K:=\pi^{-1}(H)\le F(a,b)\;$ ...
This doesn't seem to help much about the generators of $\;K\;$, though you know there is a finite number of them, but now translating all the above to topology can help with that.