text:
Q: Using multiple JS files in an Electron project I am making a basic Electron app but I'm stuck on how to use multiple JavaScript files in my project. I have window.js to render my window, but I want to have scripts.js to do everything else. I could use a <script> tag, but I want to have Node functions in it, so that wouldn't work. How would I do this?

A: You can have Node functions in the renderer process! You'll need to make sure nodeIntegration is enabled when setting up the BrowserWindow:
let mainWindow = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true
    },
    center: true
})

Check the BrowserWindow documentation for further info.

A: Node js is for server side using. Its syntactic  might use on front too  but with using additional libraries or package builders like web pack  or angular minifier.
There is example with using Node.js and electron:
https://electronjs.org/docs/tutorial/first-app
Could you provides details about your goals?


text:
Q: Nodejs : The array is changed without reference to change. Why? Sorry I'm new to node js. If you look at the ListComp array it has changed after the while loop. Could someone explain what is wrong with this code?
function FormGrp() {
 var ListOne = [];
 var ListTwo = [];
 var count = 0;
 var Control;
 var graph = [];
 var ListComp = [[59],[73,41],[52,40,9],[26,53,6,34],[10,51,87,86,81]];

 Control = 4;
 console.log(ListComp);

 while(Control != 0){
       ListOne = ListComp[count];
       ListTwo = ListComp[count+1];
       for(var i=0; i<ListOne.length; i++){
            for(var j=0; j<ListTwo.length; j++){
              if(j === 2){
                  ListTwo.shift();
                  break;
                }
                graph.push([ListOne[i],ListTwo[j]]);
            }
       }
       count++;
       Control--;
 }
    console.log('\n',ListComp);
}

In the two console outputs the values were different, but I did not use any mocking method in the ListComp array, how could it have been changed?

A: It changes because objects are copied by reference, and in Javascript an Array is an object. So, if you change the copy the original one is going to be affected as well.
Take into account that ListComp is an array of arrays, which means that if you copy one of those arrays in ListComp you are copying them by reference. For example in this line:
ListOne = ListComp[count]

In the first iteration you are copying the array [59] by reference to the array ListOne.
Let's see an example with just a simple array:

const arr = [1, 2, 3];
const arrCopy = arr;
arrCopy.push(4)
console.log(arr); // [1, 2, 3, 4]
console.log(arrCopy); // [1, 2, 3, 4]

A fast way to solve it is using, for example, Array#slice() to clone the arrays:
 ListOne = ListComp[count].slice();
 ListTwo = ListComp[count+1].slice();

But maybe structuring your code in a way you don't need to create clones could be better though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use AWS Elastic Trancoder to encode multiple formats in one job? I'm a video noob, and I have to encode a bunch of videos for streaming to an iPhone app - so I need to produce multiple screen sizes and bandwidths (for iphone, ipad etc and for wireless data, cell data, etc). I'm using AWS Elastic Transcoder.
I can only see how to do one resolution and one format per job. Does that mean I have to set up a whole bunch of jobs for each combination of screen size and bandwidth? Or is there some way to get them all into one job?
In particular, I understand that all the different streams need to be described in one .m3u8 file, so an auxiliary question is how to get the Elastic Transcoder to combine multiple streams into one description in one .m3u8 file. Maybe I have to concatenate all the different .m3u8 files from different jobs?

A: Yes. One job can generate multiple outputs, including multiple MP4 files at different resolutions/bitrates, and/or HLS or smooth format that has multiple streams and a playlist.

*

*If you go to the console (UI), you will see that you can click the "+ Add Another Output" link to be able to define additional outputs (different MP4, or an additional HLS profile)

*if you generate a HLS or Smooth output, you should also (in the same job) click the "add playlist" button. you than define all the outputs that you want the playlist to included.
When the job is complete, all outputs and playlist(s) are generated to the specified location.


text:
Q: Read, encrypting and writing a block of bytes
*

*read 16 bytes from a file;

*encrypt this 16 bytes;

*write encrypted bytes to another file;

*do the above things again until end of file;
If the last call is < 16 bytes i fill the buffer with 0.
Is this a correct way to do it?

FILE *fp = fopen("name", "r+");
FILE *fpout = fopen("name", "w+");
char plain_text[16];
fseek(fp, 0, SEEK_SET);

while(!feof(fp)){
  memset(plain_text, 0, sizeof(plain_text);
  read_bytes = fread(plain_text, 1, 16, fp);
  if(read_bytes < 16){
    i = read__bytes;
    read_bytes += 1;
    for(i, i<16, i++) plain_text[read_bytes] = 0;
  }
  encrypt-this-part-of-file
  fwrite(encBuffer, 1, 16, fpout);
}

A: no, this would be correct...
if(read_bytes < 16)
{
    for(i = read_bytes; i<16; i++)
    {
        plain_text[i] = 0;
    }
}

...if you'd actually needed it.
But you don't need to zero the remaining part of the array as you have already cleared it with...
memset(plain_text, 0, sizeof(plain_text));

...that you're calling before each invokation of fread.


text:
Q: Rendering a list of items breaks the order I am trying to load a list of ordered items from the server and then render them using my template (and http://sammyjs.org/docs/tutorials/json_store_1 for guidance):
questions_container = $('.questions_container').first()

@sammy = Sammy '#foo', ->
  @use 'Template'

  @get '#/', (context) ->
    context.log 'Loading questions...'
    @load('questions.json')
      .then (items) ->
        $.each items, (i, item) ->
          context.log item.id
          context.render('assets/question.template', {item: item})
            .appendTo(questions_container)

I observe interesting effect that in the firebug console all items are logged in the order returned by the server (ordered by id), however in the DOM they tend to be mixed up.
Is this happening because of render() parallel logic? How can I make sure that order of items is preserved in DOM? Thanks!

A: Used renderEach as Aaron Quint (author of Sammy) suggested on Google group:
questions_container = $('.questions_container').first()

@sammy = Sammy '#foo', ->
  @use 'Template'

  @get '#/', (context) ->
    context.log 'Loading questions...'
    @load('questions.json')
      .then (items) ->
        context.renderEach('assets/question.template', items)
          .appendTo(questions_container)


text:
Q: installing "ia32-libs" problem - Ubuntu 12.10 x64 I'm trying to install ia32-libs and i tried nearly all commands to install this package but always i got an error. Here is what i've tried so far;
sudo apt-get install ia32libs
orkun@ubuntu:~$ sudo apt-get install ia32libs
[sudo] password for orkun:
Reading package lists... Done
Building dependency tree
Reading state information... Done
N: Ignoring file 'ferramroberto-java-quantal.list.save' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extension
N: Ignoring file 'ferramroberto-java-quantal.list.save' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extension
N: Ignoring file 'ferramroberto-java-quantal.list.save' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extension
E: Unable to locate package ia32libs

.
sudo apt-get install package-name:i386
orkun@ubuntu:~$ sudo apt-get install package-name:i386
Reading package lists... Done
Building dependency tree
Reading state information... Done
N: Ignoring file 'ferramroberto-java-quantal.list.save' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extension
N: Ignoring file 'ferramroberto-java-quantal.list.save' in directory '/etc/apt/sources.list.d/' as it has an invalid filename extension
E: Unable to locate package package-name

.
Downloading this package and trying these commands;
sudo dpkg -i «package name>
orkun@ubuntu:~/İndirilenler$ sudo dpkg -i ia32-libs_20090808ubuntu36_amd64.deb
(Reading database ... 151309 files and directories currently installed.)
Preparing to replace ia32-libs 20090808ubuntu36 (using ia32-libs_20090808ubuntu36_amd64.deb) ...
Unpacking replacement ia32-libs ...
dpkg: dependency problems prevent configuration of ia32-libs:
 ia32-libs depends on ia32-libs-multiarch; however:
  Package ia32-libs-multiarch is not installed.

dpkg: error processing ia32-libs (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 ia32-libs

A: Sounds like your APT doesn't have an i386 foreign architecture. I have no idea why this happens to people...
Try:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install ia32-libs

A: Complete novice here, so I suspect that this has not been overlooked, but it looks like you're missing a "-" in your first line of code.
sudo apt-get install ia32-libs

I just installed  "ia32-libs" on Ubuntu 12.10 x86 as above for a JDK7u9 and NetBeans IDE 7.2.1 installation (apparently there is no 64-bit bundle).

A: I had the same problem at first. Then I tried a few methods to solve it. The one that worked is like the following:

*

*Make sure the server you selected in the "Software Sources" is the "Main Server".

*Search for all packages starting with "lib32" with apt-cache search lib32.

*Install every package that's in the list and without any "-dbg" or "-dev" suffixes.

*Then you can try to install the "ia32-libs" again.

This worked for me. Hope it helps.

A: *

*Download and install https://packages.debian.org/wheezy/amd64/libc6-i386/download

sudo apt-get -f install

*Then execute the following commands :

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install ia32-libs


text:
Q: How to float elements to the center in CSS? Edit: I cannot modify the HTML page at all or else I will automatically get a 0.
My professor just gave us this assignment where we add CSS to an HTML page. We have to follow screenshots, using the right margin, padding, borders, widths, and heights.
For multiple columns, he wants us to use float, which is all fine and dandy, but 3 columns need to be floated to the left and then centered in the page.
So while the screenshot looks like this:

My actual project looks like this:

How am I supposed to float these columns, and keep them centered?
I have set text-align for section#featured, but that only centered the text, not the elements. I can't use the display property, or I'll get points taken off. In the other screenshots he does not specify any margin or padding for the columns, so they are what they are.
They are div elements floated to the left, by the way, so their default display is block. Setting an auto margin does nothing.
Any ideas? Should I just stick it to him and use display instead of float? Because that actually works.

A: Look at the diagram.
Create a container to represent the dark blue/purple outline. Give it a size. Centre it.
Arrange the three side-by-side elements inside that container.

A: You can place your elements in a div and center it using css like
#my_div {
    display: table;
    margin: 0 auto;
}


text:
Q: Hoops in The Book of All Skies I'm confused about Greg Egan's "The Book of All Skies".
I am pretty sure about the following:

*

*The worlds form a looping sequence. You can go from world 2 to world 1 or world 3. Just two neighbors for each world. This is supported by the cover art and by Sadema and Celema being the two ends of the known space. (At the start.)

*There are two Hoops on each world. They are two vertical disks some distance apart. This is supported, among others, by this description in chapter 25:

"And it's coming up to the ideal time to enter through the western Hoop: any earlier, and we'd have to cool our heels waiting for sunset to reach the eastern Hoop; any later and we'd risk stepping out into sunshine. Go now, and we can drive from Hoop to Hoop at an ordinary pace, with no delays – but even if we get held up for some reason, it's only the way back that will be blocked. The way out will stay open for half a year."

*Each Hoop has two sides. They are described as vertical disks. Both sides are generally accessible.
With two Hoops and two sides per Hoop, we have four portals in each world. But they lead to only two neighboring worlds. How is that?

*

*Do both sides of each Hoop lead to the same world? If so, how can Del chase Orsino on foot through multiple worlds via the "ring road"? It goes in a circle around a hill. I read it as going to the other side of the same Hoop.

*Do the two sides of each Hoop lead to different worlds? If so, why do they sometimes travel from one Hoop to the other?
Sometimes they travel around the same Hoop multiple times and also switch to the other Hoop in a complicated pattern, as in chapter 9:

They were in the sixth circuit of their second traversal of the western Hoop when Del noticed the world finally growing smaller. [...] The eastern Hoop had also stood at a similar angle, for the five circuits they'd completed before coming west again.

Going just repeatedly around the same Hoop is considered ridiculous. From chapter 6:

"If we stayed at this edge, and just circled it until we hit the nub ... ?" she joked.
"We could try the same measurements," Montano conceded. "And see if the gap was small enough to bridge. But that would be a lot of work, for no reward."

How is that a joke? Why not just circle the edge? And how does that answer help? Circling the same edge seems way less work than going criss-cross! And "no reward"? Why?
The accompanying material on Greg Egan's website doesn't clear up this matter. It says:

If we ignore one of the Hoops and just consider the effects of a single one, the multiply connected space it gives access to comprises a certain number N of copies of ordinary space, numbered 1, 2, 3, ..., N, which have been spliced together as follows: if you pass through the Hoop in space i in one direction, you emerge from the Hoop in space i+1, and if you pass through the Hoop in space i in the other direction, you emerge from the Hoop in space i–1. Whenever this recipe suggests you would go higher than space N or lower than space 1, you simply wrap around to space 1 or space N respectively.

How is that different from the setup in the novel? What does the second Hoop do?

A: My first "fact" is wrong. Each world has 4 neighbors. In the book we only hear about one "nub", Celema, and its counterpart on the other side. But Greg Egan says:

Yes, there are many other pairs of nubs.

The cover is also misleading. Greg Egan says:

Yes! The actual space is more complicated, of course, being 3D, but that captures a sense of how the view of the sky behaves locally.

Other than being 4-regular and 2-connected (at least), it's hard to say more about the graph of connected worlds. Sadema appears to be unique. From chapter 3:

"And since Sadema was the only land whose terrain appeared to render one of the Hoops impassable, where else could the crucial path lie, but through those formidable mountains?"

So why did Montano pick Celema and not a nub that's easier to reach. Like the one Del "jokes" about. Would the path through that nub not lead to the other side of Sadema?
Looks like Montano expects that a "straight line" will form a loop.

Del frowned. "So you travel to the nub at Celema, and then keep going – somehow – through the void. In the hope that, eventually ... you end up where you began?"
Montano said, "Not literally, though – not if you began somewhere like Thena. We need to imagine a traveler who does nothing but go round and round the same part of the same Hoop."

If you go through the same Hoop repeatedly from Sadema until you reach a nub, that nub is Celema!


text:
Q: Aperiodic graphs The concepts of being non-periodic and aperiodic for tilings have obvious versions for connected graphs with a countable set of vertices and a finite number of edges meeting at each vertex. A graph $G$ of this class is non-periodic when its group of graph isomorphisms is trivial (this is the group of isometries if the graph is considered as a metric space in the usual way). $G$ is aperiodic if its hull consists of non-periodic graphs. Here, the hull of $G$ consists of all graphs of this class that can be expressed as an increasing union of balls with the same center and increasing radius, each of them isometric to some ball in $G$ (using the metric structure). The same definitions have direct versions for graphs with decorations, where a decoration of $G$ is a map assigning a natural number to each vertex of $G$, and the isometries are required to preserve the decorations. Finally, $G$ is said to be of bounded geometry when there is a uniform upper bound on the number of edges that meet at every vertex. Now, the question is the following: If $G$ is of bounded geometry, is there a decoration $\alpha$ of $G$ with finite image such that $(G,\alpha)$ is aperiodic?

A: [Sorry, can't post this as a comment, not enough rep].
Do you want to answer this claim for every graph $G$? That seems like it could be tricky.
It is easy to consider some simple cases in isolation, though. For $\mathbb{Z}$ one may construct decorations for which the hull will contain all periodic, all non-periodic as well as a mix of periodic and non-periodic. Clearly for a periodic decoration every decorated graph in the hull will also be periodic. For an example of all non-periodic, one could label the vertices using two colours so that the result is a Fibonacci tiling of the line (an example of a Sturmian sequence). All decorated graphs in the hull will correspond to Fibonacci tilings, so will be aperiodic. For a mixture of periodic and non-periodic, just label the central vertex with a different colour to the rest.
Similar examples will work for $\mathbb{Z}^d$ for any $d \in \mathbb{N}$. You could consider more interesting graphs for which the result is aperiodic without any decoration. For example, consider the graph of a Penrose kite and dart tiling and then "split up" the edges depending on their "types" in the tiling (e.g., as a meeting of kites, darts or of a kite and a dart) [edit: one would need to add further decorations if the original tiling had 5-fold symmetry]. This conjures a thought: in principle one may colour edges (as well as vertices) by, instead of assigning decorations, modifying the underlying graph.

A: This only solves the problem for $\mathbb Z$ but the proof was too long for a comment.
The hull of $\mathbb Z$ has only one graph, $\mathbb Z$, so only the decorations are different for the elements of the hull of a decorated $\mathbb Z$, $G$. The automorphisms of $\mathbb Z$ are just shifts with a possible reflection. Suppose that there is a periodic graph $H$ in the hull for some decoration. If there is a non-zero shift in the automorphsim of $H$, after a while the balls forming $H$ will be larger than the size of the shift, so the periodicity appears in them. Therefore, for some sequence $s$ it is true that for every $t$ there is an interval whose decoration is $t$ times $s$ concatenated, $s^t$. But by recursion it is easy to show that there is a decoration such that every sequence is repeated only a bounded number of times, and no interval longer than four is symmetric.
In fact, now after writing this up, it seems to me that a similar argument should work for any bounded degree graph.
Just for every sequence we have to make sure that it won't appear many times under the automorphism of large enough balls.
Update 03.09. Here I describe a construction in more detail for $\mathbb Z$ (the same method works for every graph).
We use only two numbers, $0$ and $1$.
For every sequence $s$ we make sure that it does not occur more than $t(s)$ times where $t(s)$ are some large numbers.
From the above discussion, this is sufficient if no interval longer than four is symmetric.
(Imo, this is the main part of the proof and the rest is standard methods.)
Using König's lemma, it is enough to give a construction for every finite interval $[1,n]$.
Image the possible $2^n$ decorations of this interval as a complete binary tree of depth $n$.
When we forbid $00$, the repetition of $0$ twice, then that is equivalent to suitably trimming this tree.
After the trimming, we can contract the new degree $2$ vertices into an edge, this way we obtain a new (not complete) binary tree.
We can cut down its lower vertices to obtain a new, still quite deep binary tree.
Then we repeat the trimming with the next sequence, with a suitable $t(s)$ that does not transform the whole tree after trimming into a path, and so on.
Oh, and to make sure that no long intervals are symmetric, first we start trimming the parts that correspond to a repetition.

A: I couldn't post this as a comment either.
I think one can prove the following weaker property using your ideas: Any countable connected graph of bounded geometry has a finite valued decoration so that any isomorphism of any decorated graph in its hull has some fixed point.
To prove it, let me clarify the following terms for a subset $A$ of a metric space $M$, say (the vertex set of) a graph: $A$ is $C$-separated when $d(x,y)\ge C$ if $x\ne y$ in $A$, and $A$ is a $C$-net when $d(x,A)\le C$ for all $x\in M$. By Zorn's lemma, there exists a $C$-separated $C$-net for all $C>0$. Then we can construct a sequence $M=A_0\supset A_1\supset A_2\supset\cdots$ such that each each $A_n$ is an $2(n+1)$-separated $2(n+1)$-net in $A_{n-1}$, and $\bigcap_nA_n=\emptyset$. Thus $A_n$ is an $(n+1)(n+2)$-net in $M$. Write $A_n=\{x_{n,m}\}$. Let $B_{n,m}$ be the closed ball of center $x_{n,m}$ and radius $n+1$. For each $n\ge1$, the sets $B_{n,m}$ are disjoint. Now take a partition of $\mathbb Z_+$ into sets $I_{n,m}$ such that each $I_{n,m}$ is an interval of $n$ integers $t_{n,m,1}<\dots<t_{n,m,n}$ let $\beta:M\to\{0,1,2,3\}$ be the  decoration limit of the decorations $\beta_n$ constructed as follows. Define $\beta_1=3$ on $M\setminus\bigcup_mB_{1,m}$, $\beta_1(x_{1,m})=4$, and $\beta_1(x)=\alpha(t_{1,m,d(x,x_{1,m})})$ if $x\in B_{1,m}\setminus\{x_{1,m}\}$. We follow by induction on $n$. For $n\ge 2$, define $\beta_n=\beta_{n-1}$ on $M\setminus\bigcup_mB_{n,m}$, and $\beta_n(x)=\alpha(t_{n,m,d(x,x_{n,m})})$ if $x\in B_{n,m}\setminus\{x_{n,m}\}$. I think that it is easy to see that, for any decorated graph $(N,\gamma)$ in the hull of $(M,\beta)$, and any isomorphism of $(N,\gamma)$ must fix some point where $\gamma=4$.


text:
Q: sails.hooks.views.render local is undefined When using
    AppointmentService.getAppointmentObject(req.params.id)
        .then((response) => {
            sails.hooks.views.render('report', { appointment: response }, (err, html) => {
                if (err) return res.send(500, err);
                return res.send(200, html);
            })
        })
        .catch(err => res.status(err.status || 500).send(err.message));

My html renders, and appointment is undefined.

When using
    AppointmentService.getAppointmentObject(req.params.id)
        .then((appointment) => {
            res.view('report', {
                appointment,
            });
        })
        .catch(err => res.status(err.status || 500).send(err.message));

My html renders, and everything works as expected.

I've read through the hooks source code, it should expose my options (thus my appointment) as locals.
I've tried the following too:
sails.hooks.views.render('report', appointment, function(err, html)) // passing my object in directly
sails.hooks.views.render('report', { appointment }, function(err, html)) // es6 shorthand property

The reason why I need the hook to work is because I need to access the HTML in order to save it to my S3 bucket.

A: I think it should be sails.hooks.http.app.render  not sails.hooks.views.render.
AppointmentService.getAppointmentObject(req.params.id)
    .then((response) => {
        sails.hooks.http.app.render('report', { appointment: response }, (err, html) => {
            if (err) return res.send(500, err);
            return res.send(200, html);
        })
    })
    .catch(err => res.status(err.status || 500).send(err.message));

A: I've worked around this problem by using res.render instead of res.view, which gave me access to the html.
    AppointmentService.getAppointmentObject(req.params.id)
        .then((response) => {
            res.render('report', { appointment: response }, (err, html) => {
                // I can access the html here
                res.send(200, html);
            });
        })
        .catch(err => res.status(err.status || 500).send(err.message));


text:
Q: Consolidate two large folders of music in Windows I have two large folders of music on my Windows 7 machine, each with many subfolders.  What is the best way to combine the folders into one, keeping only one copy of duplicate files?

A: Short version: It depends.
If you're sure that the duplicate music is going to be identical, then you can use a duplicate file finder to eliminate the duplicates.  Once that's done you can consolidate however you want.
If you might have done things like tagged some songs and not others, then AllDup will help you out.  It's a duplicate file finder that's smart enough to ignore tags on MP3 files.  It might ignore tags with other audio types too, I've also heard that the author is pretty responsive, if you need an extra feature or two.
If you've got the same music in possibly different formats, (like some MP3, some FLAC, some AAC/MP4) then you'll need music library software that can help you organize all that music and find your best quality audio out of what's available.  You might have to do some listening to see what sounds best to you though, there's no good standards for measuring audio quality*.  MediaMonkey is one such program -- this isn't an advertisement that it will be any good for you, just an example of what you're looking for.
Finally, if your music collections are a mess with files of varying quality, some tagged, some not tagged, some named or tagged incorrectly, then quit downloading junk from LimeWire and copying crap from your friends and buy your own music.  :-P  For real though, at this point you'll need software like MusicBrainz Picard that can take an audio fingerprint of your songs, identify it against a music database, and then tag it correctly.  Then go up to the previous option of getting some kind of library software to get everything organized.

*I've heard of things like EAQUAL, but they still have failings compared to real humans listening.

A: Well maybe this is a too simple way but why don't you rename the second folder to the same name like the first one. Windows will merge the folders and you can overwrite double files.

A: What you want is some kind of duplicate file finder :-)
Do a Google search, there are lots to choose from.
The one I use is this one http://www.afterdawn.com/software/desktop/misc_desktop_tools/fast_duplicate_file_finder.cfm
It's freeware, so you don't have to pay.
I use it very successfully for tidying up, and it copes with any file type.

A: If you want something more sophisticated, try WinMerge.

WinMerge is an Open Source differencing and merging tool for Windows. WinMerge can compare both folders and files, presenting differences in a visual text format that is easy to understand and handle.

A: Here is a great free small/fast utility to locate and delete duplicate files. Duplicate File Finder
There are some other file management related utilities that are also available on the website.


text:
Q: Evt.TickCount() not found with Python2.6 on OSX 10.6.3 With Python2.6, the Evt module (from Carbon import Evt) does not have seem to respond to TickCount() on OSX. But Python2.5 is fine:
from Carbon import Evt
s = Evt.TickCount()

On Python2.5 I get a returned integer. On Python2.6 I get:
AttributeError: 'module' object has no attribute 'TickCount'

This is on Snow Leopard. Is there some library that needs to be updated on OSX to allow for TickCount() to work? I'm actually having this problem due to using py2app.
Update for Barry's answer:
The problem is that the application that py2app creates, when launched, gives me:
  File "/Users/cybertoast/Projects/scripts/dist/fixcatalystlibs.app/Contents/Resources/__boot__.py", line 40, in mainloop
  [0x0-0x913913].org.pythonmac.unspecified.fixcatalystlibs[11722]       stoptime = Evt.TickCount() + timeout
  [0x0-0x913913].org.pythonmac.unspecified.fixcatalystlibs[11722]   AttributeError: 'module' object has no attribute 'TickCount'

I added VERSIONER_PYTHON_PREFER_32_BIT=yes to my .bash_profile, but the app that py2app creates still has the same problem. The python interpreter, however is happy with the 32-bit fix. But still need a solution to py2app.

A: Since the broken code was only being used for argv emulation, I was able to get my app working by disabling argv emulation.  This can be done by setting the 'argv_emulation' key in the py2app OPTIONS hash to False.
Example:
APP = ['MyApp.py']
OPTIONS = {
   'argv_emulation': False,
   ...
}

setup(
    app=APP,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

A: The code I have been using requires the use of argv_emulation, so the above solutions have not aided me. In the end, I made use of LSArchitecturePriority in the plist file, setting it to i386. This solved my problem, and allowed me to keep the argv_emulation set to True.
More info can be found here: http://developer.apple.com/library/mac/#documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html#/

A: Python runs in 64-bit mode by default in Snow Leopard. It appears that Carbon.Evt hasn't made the transition to full 64-bit compatibility. You can confirm this by trying to run in 32-bit mode (see man python):
oso:~ barry$ export VERSIONER_PYTHON_PREFER_32_BIT=yes
oso:~ barry$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Carbon.Evt as evt
>>> evt.TickCount()
2973070
>>>

So, either run py2app in 32-bit mode, or tell us what you're trying to do and perhaps we can provide a 64-bit compatible alternative.

A: Probably the easiest solution is to use another, 32-bit-only Python instead of the Apple-supplied one in 10.6 - for example, install Python 2.6 using the python.org installer.  If you want to distribute your app as a standalone app that can be used on multiple OS X versions, you'll need to do that anyway.


text:
Q: Swift: Append Custom UIView programmatically This is a near duplicate of this other SO question, however I'm running into some issues that it makes it appear like I'm not doing it correctly. For reference, I followed this excellent tutorial on creating re-usable views from a custom class and xib file (it's only a few minutes :) and I have no problems at all dragging that into another view onto my storyboard (as demonstrated at the end of the video)
Nevertheless for my case — I'm trying to call my custom class programmatically, and add it as a subview to one of my ScrollView instances.
class MainController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        first.directionalLockEnabled = true
        first.pagingEnabled = true
        var item = MyCustomView(frame: CGRectMake(0, 0, self.view.frame.width, 200))
        self.scrollView.addSubview(item)
    }

}

My Custom view looks like this:
import UIKit

class MyCustomView: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var dressTitle: UILabel!
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("MyCustomView", owner: self, options: nil)
        self.view.frame = bounds
        self.addSubview(self.view)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)

    }
}

There is an associated .xib file with it too that has the label and image.
So my question is, my view never appears in my ScrollView. I've double checked the constraints on my scroll view... I can even append simple UIView's with obvious visible dimensions CGRectMake(0, 0, 100, 100)... and nothing ever gives. What am I missing?

A: With some messing around I accidentally got it to work by duplicating the loadFromNib method to a second initializer in the CustomView.swift file. As seen in the video tutorial posted in the original question it shows just one of the initializers.... but in my case I had to add extra code to the init(frame). Eg:
// once with a NSCoder
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    NSBundle.mainBundle().loadNibNamed("Item", owner: self, options: nil)
    self.view.frame = bounds
    self.addSubview(self.view)
}

// for this to work programmatically I had to do the same...
override init(frame: CGRect) {
    super.init(frame: frame)
    NSBundle.mainBundle().loadNibNamed("Item", owner: self, options: nil)
    self.view.frame = bounds
    self.addSubview(self.view)
}


text:
Q: phpDocumentor with PHP 7.1 Return Type Declarations We are attempting to start using phpDocumentor for a Symfony 3 site running PHP 7.1.
We are using return type declarations on nearly every entity to keep things clean. phpDocumentor does not seem to support this although I see several references to PHP 7 support on their GitHub.
This is the error for every single entity:
Parse Error: Syntax error, unexpected ':', expecting ';' or '{'

A: I encountered this problem when I migrated from PHP 5 to PHP 7.1 on Ubuntu / Linux, so you need to make sure that you are really using PHP 7.x!

*

*Click on any route name on yourSymfonyprofiler, then click to Configuration(left bottom) and check your PHP Configuration. In my
case 7.1.9-1+ubuntu17.04.1+deb.sury.org+1. Or simply display     phpinfo();

*If you still using PHP < 7.x that means you need to enable PHP 7.x and disable other versions :
sudo a2enmod php7.1
sudo a2dismod phpx.x
sudo service apache2 restart
Nb: I assume that you are using Ubuntu / Linux.


text:
Q: Ansible lineinfile command error when not using "tasks:" before the lineinfile items I'm with a problem when running lineinfile command. I've written the following script, which works like a charm:
- hosts: centos1
  user: root
  tasks:
  - name: Replace nsswitch.conf passwd configuration
    lineinfile:
          path: /etc/nsswitch.conf
          regexp: "^passwd:" #line to be searched
          line: "passwd:     xxx yyy zzz" # new line replacing the above
          state: present
          create: True
    when: ansible_os_family == 'RedHat' and ansible_distribution_major_version|int >= 8

but on the prod server, yml scripts are summoned by a "main.yml", more or less like this:
---
include: script1.yml
include: script2.yml
include: myscript.yml
...

and then I was requested by my senior analyst to remove the "hosts", "user" and "tasks" from the final version, and add a tag on each lineinfile entry, which looked like this:
- name: Replace nsswitch.conf passwd configuration
  lineinfile:
        path: /etc/nsswitch.conf
        regexp: "^passwd:" #line to be searched
        line: "passwd:     files sss systemd" # new line replacing the above
        state: present
        create: True
  when: ansible_os_family == 'RedHat' and ansible_distribution_major_version|int >= 8
  tags:
    - nsswwitch_change

but now when I run the playbook, either through my yml file or the main file, I get the following error:
ansible-playbook 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /bin/ansible-playbook
  python version = 2.7.5 (default, Aug 13 2020, 02:51:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
Using /etc/ansible/ansible.cfg as config file
host_list declined parsing /tmp/hosts as it did not pass its verify_file() method
script declined parsing /tmp/hosts as it did not pass its verify_file() method
auto declined parsing /tmp/hosts as it did not pass its verify_file() method
Parsed /tmp/hosts inventory source with ini plugin
ERROR! 'lineinfile' is not a valid attribute for a Play

The error appears to be in '/app/ansible/roles/linux-sap-hana/tasks/raul-mnsswitch.yml': line 26, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

- name: Replace nsswitch.conf passwd configuration
  ^ here

I'm literally out of ideas, because the only way I was able to make it work was adding the host, user and tasks at the beggining  of the playbook.
Any help would be appreciated folks, thanks a lot in advance.

A: If you top-level playbook looks like this:
include: script1.yml
include: script2.yml
include: myscript.yml

Then each of those included documents needs to be a playbook: that means it needs to be a list of plays, not a list of tasks:
- name: play 1
  hosts: all
  tasks:
    ...

- name: play 2
  hosts: all
  tasks:
    ...

Otherwise, how will Ansible know which hosts to target?
Note that the include module is deprecated:

DEPRECATED
Removed in
version 2.16
Why
it has too many conflicting behaviours depending on keyword combinations and it was unclear how it should behave in each case. new actions were developed that were specific about each case and related behaviours.
Alternative
include_tasks, import_tasks, import_playbook

You should be using import_playbook instead.

If you want to include a list of tasks, you can only do that via the include_tasks or import_tasks modules, as part of task in a play:
- name: play 1
  hosts: all
  tasks:
    - name: import script1
      import_tasks: script1.yml

    - name: import script2
      import_tasks: script2.yml

NB: To make sure you're clear on the nomenclature:
# This entire block is a playbook

# This is a play
- hosts: all
  tasks:
    # This is a task
    - name: Example task 1
      debug:
        msg: This is an example task

# This is a play
- hosts: all
  tasks:
    # This is a task
    - name: Example task 2
      debug:
        msg: This is an example task


text:
Q: Webscraping: Separating phrases from HTML text output in python Im learning web scraping for apartments. The HTML block for one apartment looks like this:
Input
# Create a web search and save the results
base = 'https://www.booli.se/'
addition = 'kungsholmen,vasastan,gardet/115353,115349,115347'
url = base+addition
print(url)
notar = requests.get(url) # load the webpage content
page = notar.content # get the url content
soup = BeautifulSoup(page, 'lxml') # convert it to a beautiful soup object

links = soup.find_all('a', href=re.compile('/annons/'))

Output

<picture><source sizes="(min-width: 460px)
959px, (min-width: 991px) 459px, 459px"
srcset="//bcdn.se/images/cache/27006816_796x0.webp 796w,
  //bcdn.se/images/cache/27006816_360x0.webp 360w,
  //bcdn.se/images/cache/27006816_270x0.webp 270w" type="image/webp"/><source sizes="(min-width: 460px) 959px, (min-width: 991px) 459px, 459px" srcset="//bcdn.se/images/cache/27006816_796x0.jpg 796w,
  //bcdn.se/images/cache/27006816_270x0.jpg 360w,
  //bcdn.se/images/cache/27006816_270x0.jpg 270w" type="image/jpeg"/></picture>

Balkong

Eldstad

Tomtebogatan 5B

4 895 000 kr

Värdering

5 470 000 kr

Vasastan -
 Birkastan

Lägenhet

2 rum

52 m²

931 kr/mån

When I access the text of each HTML block / each apartment then the text comes, but all together, without spacing in-between. The words are different for every apartment, as is the order of the phrases (the features comes first and it could be 0-5 features, which makes an order method invalid) and I would like to be able to save the name, price, features etc. into a table.
Input
for nr_aps, row in enumerate(links):
    row.str
    info = row.text # show each apartment info
    print(info)
    print('')

Output
BalkongEldstadTomtebogatan 5B4 895 000 krVärdering5 470 000 krVasastan - BirkastanLägenhet2 rum52 m²931 kr/mån

Do you have any idea of how to save each section to a table? Thank you!

A: You are saving all the appartment info into one variable "info".
If you want to just print the appartment one at a time just use
print(row.text)

Or simply just add \n to make a new line
info = row.text + "\n"


text:
Q: How to integrate php values in chart script? This is the code which i have used for chart with php. How to make "data: [28, 48, 40, 19, 86, 27, 90, 20, 80, 81, 56, 55,]" which is script to php. I want send data as php variable.
<script>
     $(document).ready(function() {

         var lineData = {
             labels: ["January", "February", "March", "April", "May", "June", "July", "AUG", "SEP", "OCT", "NOV", "DEC"],
             datasets: [
                 {
                     label: "Sale",
                     backgroundColor: "rgba(26,179,148,0.5)",
                     borderColor: "rgba(26,179,148,0.7)",
                     pointBackgroundColor: "rgba(26,179,148,1)",
                     pointBorderColor: "#fff",
                     data: [28, 48, 40, 19, 86, 27, 90, 20, 80, 81, 56, 55,]
                 },

             ]
         };

         var lineOptions = {
             responsive: true
         };

         var ctx = document.getElementById("lineChart").getContext("2d");
         new Chart(ctx, {type: 'line', data: lineData, options:lineOptions});

     });
  </script>


text:
Q: Past Continuous with while The sentence:

The boy stole / was stealing the apples while nobody was looking / looked.

Question: Which variant is more appropriate?

A: The second verb, to look should be in past progressive. It's about an action that was (or in this case was not) going on during another action.
The first could go either way, depending on context. Is there some other activity going to be mentioned that is also located in time during the apple theft? For example, if the next sentence were to start:

It suddenly occurred to him that stealing was naughty

Then the progressive is most appropriate for to steal as well. The same is true if the sentence were in answer to the question "what was the boy doing at 2pm yesterday?", but that would be an unusual case.
If nothing like that applies, then stole is more natural. Past progressives are usually used when locating actions in time, either to specific times or in relation to other actions. However, I can't say that using the progressive in this case would be wrong as such, just strange.


text:
Q: Dropdown in a submenu not visible despite Z-Index is set I really can't understand how to solve this issue. I am using Bootstrap 3, and adding the submenu functionality on top with an additional custom CSS.
The second level menu item is visible only in the submenu element visual part and not the part on the right:

.dropdown-submenu {
  position: relative;
  z-index: 9999999;
}

.dropdown-submenu>.dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -6px;
  margin-left: -1px;
  -webkit-border-radius: 0 6px 6px 6px;
  -moz-border-radius: 0 6px 6px 6px;
  border-radius: 0 6px 6px 6px;
}

.dropdown-submenu:hover>.dropdown-menu {
  display: block;
  z-index: 9999999;
}

.dropdown-submenu>a:after {
  display: block;
  z-index: 9999999;
  content: " ";
  float: right;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 5px 0 5px 5px;
  border-left-color: #cccccc;
  margin-top: 5px;
  margin-right: -10px;
}

.dropdown-submenu:hover>a:after {
  border-left-color: #ffffff;
}

.dropdown-submenu.pull-left {
  float: none;
}

.dropdown-submenu.pull-left>.dropdown-menu {
  left: -100%;
  margin-left: 10px;
  -webkit-border-radius: 6px 0 6px 6px;
  -moz-border-radius: 6px 0 6px 6px;
  border-radius: 6px 0 6px 6px;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        Blog

        About The Tests

            Clearing Floats

                Page with comments

                Page with comments disabled

                More

                    3rd level link more options

                    3rd level link

        Lorem Ipsum

        <form class="navbar-search navbar-form" method="get" action="">
          <input type="text" class="form-control" placeholder="Search" name="s">
        </form>

Do you know how to make the menu visible? Where is my mistake? I set z-index higher in the element, display is block so I really don't know how to solve...
Thanks in advance!

A: You are not using the right selectors for the hovering. This rule:
.dropdown-submenu:hover>.dropdown-menu {
  display: block;
  z-index: 9999999;
}

should have this selector (just .dropdown:hover instead of .dropdown-submenu:hover) :
.dropdown:hover > .dropdown-menu {

That change alone makes the dropdown work: https://codepen.io/anon/pen/eGVQMm
But there might be other rules which you also should change


text:
Q: How do i reset a child component's search-input I have a child component that contains a search input which is CriminalSearch.vue, algolia vue-instantsearch for the full question i put it here..
https://gist.github.com/abrhambas01/84518e8437ae2ff1a0dc3dfca202fd00


text:
Q: Entity Framework Core 5.0 How to convert LINQ for many-to-many join to use Intersection table for ASP.NET Membership Question:
How do I convert a LINQ query the performs a LEFT OUTER JOIN on a sub-select that INNER JOINS two tables and has a predicate?
Context:
I am upgrading from Entity Framework 6 (EF6) to Entity Framework Core 5 (EFCore) using the EFCore Tools Reverse Engineering feature. I have a query that is using LINQ to query a many-to-many relationship on the ASP.NET Membership system between the AspNet_Users and AspNet_Roles tables. The query abstracts away the join through the AspNet_UsersInRoles intersection table. As a result, in EF6 I have the following LINQ:
(from r in this.DbContext.aspnet_Users
where r.UserId == dpass.UserId
select r.aspnet_Roles.Select(x => x.RoleName)
).FirstOrDefault();

That generates the following SQL Query (retrieved using SQL Server Profiler):
DECLARE @p__linq__0 uniqueidentifier = '<Runtime_GUID>'

SELECT
    [Limit1].[UserId] AS [UserId],
    [Join1].[RoleName] AS [RoleName],
    CASE WHEN ([Join1].[UserId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM (SELECT TOP (1) [Extent1].[UserId] AS [UserId]
        FROM [dbo].[aspnet_Users] AS [Extent1]
        WHERE [Extent1].[UserId] = @p__linq__0
        ) AS [Limit1]
LEFT OUTER JOIN (SELECT [Extent2].[UserId] AS [UserId]
                    , [Extent3].[RoleName] AS [RoleName]
                FROM [dbo].[aspnet_UsersInRoles] AS [Extent2]
                INNER JOIN [dbo].[aspnet_Roles] AS [Extent3]
                    ON [Extent3].[RoleId] = [Extent2].[RoleId]
                ) AS [Join1]
    ON [Limit1].[UserId] = [Join1].[UserId]

I have converted the LINQ to the following:
(from ur in this.DbContext.aspnet_UsersInRoles
 join r in this.DbContext.aspnet_Roles
    on ur.RoleId equals r.RoleId
  where ur.UserId == dpass.UserId
  join u in this.DbContext.aspnet_Users
    on ur.UserId equals u.UserId
 into UserRolesJoined from UserRoles in UserRolesJoined.DefaultIfEmpty()
  select new { ur.UserId, ur.Role.RoleName }
 )

That generates the following SQL query (retrieved using EFCore's new .ToQueryString() method):
DECLARE @__dpass_UserId_1 uniqueIdentifier = '<Runtime_GUID>'
SELECT [a].[UserId], [a2].[RoleName]
FROM [aspnet_UsersInRoles] AS [a]
INNER JOIN [aspnet_Roles] AS [a0] ON [a].[RoleId] = [a0].[RoleId]
LEFT JOIN [aspnet_Users] AS [a1] ON [a].[UserId] = [a1].[UserId]
INNER JOIN [aspnet_Roles] AS [a2] ON [a].[RoleId] = [a2].[RoleId]
WHERE [a].[UserId] = @__dpass_UserId_1

The SQL SELECT statement from EFCore is different than the SQL SELECT statement from EF6; however, the SQL Select result is identical. Is this the correct way to re-write the LINQ, or did I get it wrong? Any help is greatly appreciated.
UPDATE
Once I ran the Reverse Engineering tool, the original LINQ command had the following errors:

*

*CS1061 'aspnet_Users' does not contain a definition for 'aspnet_Roles' and no accessible extension method 'aspnet_Roles' accepting a first argument of type 'aspnet_Users' could be found (are you missing a using directive or an assembly reference?)

When I add public IEnumerable<object> aspnet_Roles; to aspnet_users, I then get the following error.

*CS1061 'object' does not contain a definition for 'RoleName' and no accessible extension method 'RoleName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Below are the tables in question from the ASP.NET Membership system that Microsoft created. For reference for the full schema, see: https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/membership/creating-the-membership-schema-in-sql-server-cs
aspnet_UserInRoles
[Index(nameof(RoleId), Name = "aspnet_UsersInRoles_index")]
public partial class aspnet_UsersInRoles
{
    [Key]
    public Guid UserId { get; set; }
    [Key]
    public Guid RoleId { get; set; }

    [ForeignKey(nameof(RoleId))]
    [InverseProperty(nameof(aspnet_Roles.aspnet_UsersInRoles))]
    public virtual aspnet_Roles Role { get; set; }
    [ForeignKey(nameof(UserId))]
    [InverseProperty(nameof(aspnet_Users.aspnet_UsersInRoles))]
    public virtual aspnet_Users User { get; set; }
}

aspnet_Roles
public partial class aspnet_Roles
{
    public aspnet_Roles()
    {
        aspnet_UsersInRoles = new HashSet<aspnet_UsersInRoles>();
    }

    public Guid ApplicationId { get; set; }
    [Key]
    public Guid RoleId { get; set; }
    [Required]
    [StringLength(256)]
    public string RoleName { get; set; }
    [Required]
    [StringLength(256)]
    public string LoweredRoleName { get; set; }
    [StringLength(256)]
    public string Description { get; set; }

    [ForeignKey(nameof(ApplicationId))]
    [InverseProperty(nameof(aspnet_Applications.aspnet_Roles))]
    public virtual aspnet_Applications Application { get; set; }
    [InverseProperty("Role")]
    public virtual ICollection<aspnet_UsersInRoles> aspnet_UsersInRoles { get; set; }
}

aspnet_Users
[Index(nameof(ApplicationId), nameof(LastActivityDate), Name = "aspnet_Users_Index2")]
public partial class aspnet_Users
{
    public aspnet_Users()
    {
        Users = new HashSet<Users>();
        aspnet_PersonalizationPerUser = new HashSet<aspnet_PersonalizationPerUser>();
        aspnet_UsersInRoles = new HashSet<aspnet_UsersInRoles>();
    }

    public Guid ApplicationId { get; set; }
    [Key]
    public Guid UserId { get; set; }
    [Required]
    [StringLength(256)]
    public string UserName { get; set; }
    [Required]
    [StringLength(256)]
    public string LoweredUserName { get; set; }
    [StringLength(16)]
    public string MobileAlias { get; set; }
    public bool IsAnonymous { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime LastActivityDate { get; set; }

    [ForeignKey(nameof(ApplicationId))]
    [InverseProperty(nameof(aspnet_Applications.aspnet_Users))]
    public virtual aspnet_Applications Application { get; set; }
    [InverseProperty("User")]
    public virtual aspnet_Membership aspnet_Membership { get; set; }
    [InverseProperty("User")]
    public virtual aspnet_Profile aspnet_Profile { get; set; }
    [InverseProperty("aspUser")]
    public virtual ICollection<Users> Users { get; set; }
    [InverseProperty("User")]
    public virtual ICollection<aspnet_PersonalizationPerUser> aspnet_PersonalizationPerUser { get; set; }
    [InverseProperty("User")]
    public virtual ICollection<aspnet_UsersInRoles> aspnet_UsersInRoles { get; set; }
}

A: If I were you I wrote this query like this:
var result = context.UserRoles
                    .Where(x => x.UserId == ID_TO_SEARCH)
                    .Join(
                        context.Roles,
                        ur => ur.RoleId,
                        r => r.Id,
                        (ur, role) => new
                        {
                            ur,
                            role
                        }
                    )
                    .Select(x => x.role.Name)
                    .FirstOrDefault();

This produces query which, as for me, totally fine and more elegant:
SELECT TOP(1) [a0].[Name]
FROM [AspNetUserRoles] AS [a]
INNER JOIN [AspNetRoles] AS [a0] ON [a].[RoleId] = [a0].[Id]
WHERE [a].[UserId] = N''

UPDATE:
If I understand correctly what I've been asked in the comments, then this query will select a role name LIKE LEFT JOIN:
var rolesQuery = context.UserRoles
                         .Join(
                            context.Roles,
                            ur => ur.RoleId,
                            r => r.Id,
                            (ur, r) => new
                            {
                                ur,
                                r
                            }
                        );

    var result = context.Users
                        .Where(x => x.Id == "")
                        .Select(u => new
                        {
                           Name = u.UserName,
                           Role = rolesQuery
                               .Where(sub=> sub.ur.UserId == u.Id)
                               .Select(sub=> sub.r.Name)
                               .FirstOrDefault()
                        })
                        .FirstOrDefault();

Which results in this SQL statement:
      SELECT TOP(1) [a1].[UserName] AS [Name], (
          SELECT TOP(1) [a0].[Name]
          FROM [AspNetUserRoles] AS [a]
          INNER JOIN [AspNetRoles] AS [a0] ON [a].[RoleId] = [a0].[Id]
          WHERE [a].[UserId] = [a1].[Id]) AS [Role]
      FROM [AspNetUsers] AS [a1]
      WHERE [a1].[Id] = N''

As you can see there is NO LEFT JOIN, but sub-select will return data in similar way as LEFT JOIN does. Unfortunately, lambda-based queries do not support full LEFT JOIN and the only option to write real LEFT JOIN can be riched with SQL-like IQueryable.
I saw a method called LeftJoin() inside EF core 5 lib, but it throws NotImplementedException. I think it something that will be released later

A: If you need just role names for particular user, query should be simplified:
var query =
   from r in this.DbContext.aspnet_Users
   where r.UserId == dpass.UserId
   from ro in r.aspnet_Roles
   select ro.RoleName;


text:
Q: Why does PHP Include not work with child Includes? I may have phrased the question slightly wrong so feel free to edit the title.
I was working on a site and I made this whole PHP Include system that was easy so that people with less knowledge could edit the content. Anyway it was like this.
Say you have index.php and the code is.
<?PHP
   include 'tabs.php';
?>

and then tabs.php is:
include 'tab-1.php'

2, 3 etc.
and then tab-1 is:
<?PHP
include 'tab-1-content.php'
?>

I hope you kind of get the idea, of course the formatting was way neater and there was html around it and stuff but the point is it didnt work at all. It seems like you can only include one file and then if there is an include in that file it wont work. I was wondering if anyone could explain this!?
Thanks!

A: I think multiple includes doesn't cause problems ... but if it doesn't work for you, it's most probably you have a conflict in the files' paths.
My advice is to test the includes statements one by one for example:-
include 'tabs.php';

if the above line works fine, add into "tabs.php" the following line
include 'tab-1.php'

and keep going until you find the file where the problem happens.


text:
Q: Angularjs filter part of name I have a jsFiddle here - http://jsfiddle.net/GRw64/
I'm new to Angularjs so still finding my feet
My example is a simple ng-init of customer names.
An input field and a ng-repeat to filter the name in the input field against the customer names.
If you type a name in the input field the ng-repeat filters the list to show that name.
If I type Chris the name 'Chris Dave' and 'Chris' appear in the list.
If I change to 'Chris Dave', 'Chris Dave' is still showing in the list but 'Chris' disappears
How can I get a return with all the results that match at least one word in the search.
<!doctype html>

        Names:

        <input type="text" data-ng-model="name" />

{{ cust.name }}

A: You can also provide a function to the filter filter of Angular:
ng-repeat="cust in customers | filter:filterByName"

Then you have to define the function in your controller:
$scope.filterByName = function(customer) {
  if(!$scope.name) {
    return true;
  } else {
    var keywords = $scope.name.toLowerCase().split(' ');

    for(var i in keywords){
        var k = keywords[i];
        if (customer.name.toLowerCase().indexOf(k) >= 0) {
            return true;
        }
    }
    return false;
  }
}

Working example

A: Suppose you treat the space-separated keywords as OR relationship, you can create a custom filter to achieve what you need like this:
var app = angular.module('myApp', []);
app.filter('myFilter', function () {
    return function (names, keyword) {
        var listToReturn = [];
        if (keyword === undefined) return names;
        var keywords = keyword.toLowerCase().split(' ');
        angular.forEach(names, function (name) {
            for(var i in keywords){
                var k = keywords[i];
                if (name.name.toLowerCase().indexOf(k) >= 0) {
                    listToReturn.push(name);
                    break;
                }
            }
        });
        return listToReturn;
    };
});

DEMO


text:
Q: How to expand date ranges by taking into account overlapping days in PostgreSQL? Given the following table created in a PostgreSQL database using the following SQL statements:
CREATE TABLE reservations (
    reservation_id INT PRIMARY KEY,
    check_in_date DATE NOT NULL,
    check_out_date DATE NOT NULL
);

INSERT INTO reservations VALUES
    (1,  '2021-01-04', '2021-01-05'),
    (2,  '2021-01-05', '2021-01-07'),
    (3,  '2021-01-06', '2021-01-07'),
    (4,  '2021-01-06', '2021-01-08'),
    (5,  '2021-01-08', '2021-01-09'),
    (6,  '2021-01-08', '2021-01-09'),
    (7,  '2021-01-08', '2021-01-10'),
    (8,  '2021-01-13', '2021-01-17'),
    (9,  '2021-01-13', '2021-01-14'),
    (10, '2021-01-14', '2021-01-15'),
    (11, '2021-01-15', '2021-01-16'),
    (12, '2021-01-16', '2021-01-17');

The table represents the list of reservations of a Bed&Breakfast with check-in date and check-out date.
It is requested to retrieve how many rooms should be set up and available for each week. In order to reduce maintenance expenses, it is required to minimise the number of offered rooms. Additionally a ,room can always be made available the same day as the check-out date. For example, if a room is checked out on the 2021-01-08 and another one is checked in on the same day, the count of rooms that needs to available for the 2021-01-08 will be only 1, and not 2.
The result should be the following:

week
number_of_rooms

1
3

2
2

My approach is the following:
WITH reservations_with_expanded_dates AS (
    SELECT
        reservation_id,
        Generate_series(check_in_date::DATE,
            check_out_date::DATE,
            '1day')::DATE AS stay
    FROM
        reservations
)
SELECT
    week,
    max(number_of_rooms)
FROM (
    SELECT
        Date_part('week', stay) AS week,
        stay,
        count(*) AS number_of_rooms
    FROM
        reservations_with_expanded_dates
    GROUP BY
        stay) AS reservations_per_day
GROUP BY
    week

Which gives the following result:

week
number_of_rooms

1
4

2
3

The result is not correct because my approach doesn't take into account the fact that a room can always be made available the same day as the check-out date. How can I improve my query to take this into account?
Moreover, is there a better way in terms of performance to achieve what I am trying to do?

A: You can do:
select week, max(rooms_used) as max_rooms_used
from (
  select date_part('week', d) as week, count(*) as rooms_used
  from (
    select *,
      generate_series(check_in_date,
                      check_out_date - 1,
                      interval '1 day')::date as d
    from reservations
  ) x
  group by d
) y
group by week

Result:
week  max_rooms_used
----  --------------
1     3
2     2

See running example at db<>fiddle.

A: Something like this would work, it shows you per day how many rooms you need and for what reservation the room is. It's just an example that could be extended with late-check-out, different types of rooms, etc. etc.
CREATE TABLE reservations (
    reservation_id INT PRIMARY KEY,
    check_in_out tsrange
);

INSERT INTO reservations VALUES
    (1,  tsrange('2021-01-04 15:00', '2021-01-05 11:00','[)')),
    (2,  tsrange('2021-01-05 15:00', '2021-01-07 11:00','[)')),
    (3,  tsrange('2021-01-06 15:00', '2021-01-07 11:00','[)')),
    (4,  tsrange('2021-01-06 15:00', '2021-01-08 11:00','[)')),
    (5,  tsrange('2021-01-08 15:00', '2021-01-09 11:00','[)')),
    (6,  tsrange('2021-01-08 15:00', '2021-01-09 11:00','[)')),
    (7,  tsrange('2021-01-08 15:00', '2021-01-10 11:00','[)')),
    (8,  tsrange('2021-01-13 15:00', '2021-01-17 11:00','[)')),
    (9,  tsrange('2021-01-13 15:00', '2021-01-14 11:00','[)')),
    (10, tsrange('2021-01-14 15:00', '2021-01-15 11:00','[)')),
    (11, tsrange('2021-01-15 15:00', '2021-01-16 11:00','[)')),
    (12, tsrange('2021-01-16 15:00', '2021-01-17 11:00','[)'));

SELECT  s::date
    ,   EXTRACT(WEEK FROM s)
    ,   COUNT(DISTINCT reservation_id)
    ,   ARRAY_AGG(DISTINCT reservation_id ORDER BY reservation_id)
FROM    reservations
        RIGHT JOIN  (SELECT s FROM generate_series('2021-01-01 15:00'::timestamp, '2021-01-21'::timestamp, INTERVAL '1 DAY') g(s)) s ON s <@ check_in_out
GROUP BY 1,2
ORDER BY 1;

A late checkout will change the number of rooms needed:
UPDATE  reservations
SET     check_in_out = tsrange('2021-01-06 15:00', '2021-01-08 17:00','[)')
WHERE   reservation_id = 4;

Unless somebody else checks in late:
UPDATE  reservations
SET     check_in_out = tsrange('2021-01-08 18:00', '2021-01-10 11:00','[)')
WHERE   reservation_id = 7;

And you check for 18:00 hours how many rooms you need:
SELECT  s::date
    ,   EXTRACT(WEEK FROM s)
    ,   COUNT(DISTINCT reservation_id)
    ,   ARRAY_AGG(DISTINCT reservation_id ORDER BY reservation_id)
FROM    reservations
        RIGHT JOIN  (SELECT s FROM generate_series('2021-01-01 18:00'::timestamp, '2021-01-21'::timestamp, INTERVAL '1 DAY') g(s)) s ON s <@ check_in_out
GROUP BY 1,2
ORDER BY 1;


text:
Q: A water drop in a falling lift Consider a lift, which is at rest in an homogeneous gravity field. There is a thin layer(with thickness $h$) of water on the floor of the lift. At some moment a single cable, supporting the lift, breaks and the lift begins free falling(forever). It is easy to describe qualitatively what happens with water, i think: the formation of a drop begins. During this process the drop jumps up from the floor and once the total kinetic energy of the drop is dissipated into the heat, the center of the drop stands at some height $H$ from the floor. (All the kinetic energy of the drop is coming from the difference in surface tension energy of water between initial and end moments.)
Question: How to determine(approximately) $H$ ?
For simplicity let's assume that the cross-section of the lift is a disc-shaped with radius $R$.  $(h<<R)$
Remark: A key point is to determine how the total kinetic energy distributes between internal kinetic energy and translational kinetic energy of the drop, i think. With this the problem will be solved.
So it is convenient at the early stage of formation of the drop ignore viscosity effects of water and air resistance.
Edit:
I would like to clarify that by internal kinetic energy i mean the kinetic energy of macroscopic motion of water inside the drop. At early stage there is no energy loss assumed, for simplicity.

A: The only reason the water would form into a drop is the surface tension. You can work out the reduction in the energy stored in the surface tension in being a drop rather than a flat surface using a simple calc of the surface area. There's no particular reason I can see that the drop would float off the floor at all.

A: Unless there is some inital temperature difference, its total kinetic energy is just its translational kinetic energy, which is the energy gained from its change in shape due to surface tension, from which you can get its temperature and also its velocity $v_0$.
You have the surface area, temperatures, conductivities, so you can get the heat transfer per time from fourier's law.
From which you can get the energy E(t), which gives you v(t), a solution to v(t)=0, if it exists, is T, then integrate v(t) from 0 to T to get H.
Most likely it wont come to a full stop, it could be in thermal equilibrium and still have translation kinetic energy, and even more likely it approaches velocity 0 asymptotically.


text:
Q: Set a template on a custom post in the plugin I looked at some answers and didn't help
I'm trying the next section (right away) but it returns the template if errors in WordPress's built-in function lines. Like get_header ()
add_filter('template_include', 'my_custom_template');

function my_custom_template($single) {

global $post;

/* Checks for single template by post type */
if ( $post->post_type == 'simulators' ) {
        return SIMULATOR_URI . 'inc/themes/admin/single-simulators.php';
    }

return $single;

}

Basically, the template is already listed in WordPress templates, is there an easy way to set it as a custom post template?


text:
Q: How to compare date string using javascript I have the following string value of a date, Sun Apr 07 2019 00:00:00 GMT-0300, and I need to compare with the following date format 2019-04-08T03:00:00.000Z, note that both are the same day, I need to compare them and return a true as being equal days,
but I do not know how to do this using javascript, any help?
I tried to do something like this but it does not return me true:
if (input) {

     //input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"

     var situation = angular.isArray(item.situation) ? item.situation : [item.situation];

     // situation =
     //[
     //    0: "2019-04-08T03:00:00.000Z"
     //    1: "2019-04-13T03:00:00.000Z"
     //]

     if (!angular.isArray(input.value)) {
        condition = situation.indexOf(input.value) >= 0;

     } else if (angular.isArray(input.value)) {
        condition = $window._.intersection(situation, input.value).length > 0;
     }
}

if (condition) {
    break;
}

//input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"
 situation =
     [
         0: "2019-04-08T03:00:00.000Z"
         1: "2019-04-13T03:00:00.000Z"
     ]

A:
Sun Apr 07 2019 00:00:00 GMT-0300
2019-04-08T03:00:00.000Z
note that both are the same day

No, they are not.
You can convert them both to ISO string and just compare their date parts as strings (if I understood the question correctly, you want to compare date only, without time):
function isSameDate(date1, date2) {
  const [d1, ] = (new Date(date1)).toISOString().split('T');
  const [d2, ] = (new Date(date2)).toISOString().split('T');
  return d1 === d2;
}

A: Convert all the values to Date objects and compare those. Use a framework/library to do it, because parsing strings to dates manually has lots of places where it can go wrong.
Currently you are comparing the literal Strings. Because neither "2019-04-08T03:00:00.000Z", nor "2019-04-13T03:00:00.000Z" match "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)", your second if statement fails.

A: Build a date from the strings and compare the days (ie number of seconds since epoch / number of seconds in a day):

const sameDay = (dateString1, dateString2) => {
  let time1 = (new Date(dateString1)).getTime();
  let time2 = (new Date(dateString2)).getTime();
  return Math.floor(Math.abs((time1-time2))/(1000*60*60*24))==0;
}

console.log(
  sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-08T03:00:00.000Z'),
  sameDay('Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)','2019-04-13T03:00:00.000Z'),
);


text:
Q: Laravel am I doing multiple queries by calling the Auth::user() multiple times in my controller In my controller I get the logged in user id and username like this:
$userId = Auth::user()->id;
$username = Auth::user()->user_name;

But will the above code produce two queries?
I dont understand how Auth::user() works behind the scene

A: If your code generates 2 query save user in another variable.
Like this:
$user = Auth:user();
$userId = $user->id;
$username = $user->user_name;

Laravel does not store all user in session, it stores only user id. And when call user() function laravel will get user from database with saved user id.

A: Auth::user() return an object with your user data from the users table.
So, if you want just one query, use :
$user = Auth::user();
echo $user->user_name;

Have a look on official doc, at Validation section.
Be sure that your user is logged before call Auth method :
if (Auth::check()) {
// User logged
}

A: If you want reduce database query, fetch Authenticated user like this:
 $user = Auth::user():
 $id = $user->id;
 $name = $user->name;
 dd($user);

In laravel Auth::user() has all data of current authenticated user.


text:
Q: Creating Web Service in ASP.NET from existing API I am looking to create a web service from an existing API. The existing API is from a separate Windows program that allows the calculation of mileages between 2 more more locations. The API is in C#. There are also different types of calculations (Shortest Distance, Lowest-Cost, etc).
I am confused on how to create a RESTFUL web service that will allow multiple locations. Example in RESTFUL API tutorials show for an example api/books/1/To Kill A Mockingbird/ would get the record for a book. But how would this be for multiple locations? Would it be api/sd/Kansas City,MO/Chicago,IL/Miluwake,WI? How would it know if I'm looking to get the calculations of 2 vs. 10 locations? Could I program it to have 10 locations entered in the URL?

A: You don't have to use url segments to accept parameters. You could use a query string parameter with place names, say, semicolon-delimited, then split them out in your code.
/api/sd?cities=Kansas City,MO;Chicago,IL;Miluwake,WI

Then in your code just use Request.QueryString["cities"].Split(';');

A: I think that as your route grows, you may run into other problems such as a url that is too long (there are limits to URL size, from what I understand -- https://stackoverflow.com/a/1051565/507025).  If you're going to have and API that can accept an endless number of parameters, I think you would want to do something like sending a JSON object with the request so the API controller can process it.
Additionally, a JSON object might be simpler to process, code wise.
Try here: https://stackoverflow.com/a/20226220/507025


text:
Q: Searching for a combination of characters in a file I am trying to create a program that reads a file and searches for a specific combination of characters.
For example: "/start/ 4jy42jygsfsf /end/".
So I want to find all the "strings" starting with /start/ and ending with /end/.
In order to do that, I use read() function because the file might be a binary file (it doesn't have to be a file with chars).
I call the read() function like that:
#define BUFFSIZE 4000

// more declarations

while (read(file_descriptor, buffer, BUFFSIZE) > 0)
{
    //search for /start/
    //then search for /end/
    //build a string with all the chars between these two
    //keep searching till you reach the end of buffer
}

Assume that every /start/ is followed by an /end/.
The question is:
How do I deal with cases that this combination of characters is cut in half?
For example, let's say that the first time read() gets called, in the end of this buffer I spot /star and the next time read() gets called at the start of the second buffer there is t/ 4jy42jygsfsf /end/.
This combination might get cut anywhere. The solutions I thought will result to many many lines of code. Is there any smart way to deal with all these cases?

A: When you reach the end of the buffer, record the state of the current partial match, if any.  Then when you get the next buffer, you have 4 general cases:

*

*Not inside any text to be matched.

*Saw just a beginning / at the end of the last buffer

*Currently inside /start/.  Another variable records how far you have matched.

*Currently inside /end/.  Same variable as for /start/ records how far you have matched.

Your states inside the matcher are generally:

*

*Currently not matching anything

*Just saw a / - next looking for an 's' or an 'e'.

*Matching either start/ or end/.

*Matched - either /start or /end.

Based on the partial match, just jump to the right state in the matcher.
OR
You can use the PCRE library.  It supports partial matching.  But probably is overkill for your purposes.


text:
Q: AddressVerify API — do not have permissions to make this API call I have called AddressVerify API of PayPal in sandbox mode but it returns with error,
[L_ERRORCODE0] => 10002
[L_SHORTMESSAGE0] => Authentication/Authorization Failed
[L_LONGMESSAGE0] => You do not have permissions to make this API call
[L_SEVERITYCODE0] => Error

My code for AddressVerification is,
function verify_address($PayPalConfig, $email, $street, $zipcode) {

    $PayPal = new PayPal($PayPalConfig);

    $AVFields = array(
        'EMAIL' => $email,
        'STREET' => $street,
        'ZIP' => $zipcode,
    );

    $PayPalRequestData = array(
        'AVFields' => $AVFields,
    );

    $PayPalResult = $PayPal->AddressVerify($PayPalRequestData);
    return $PayPalResult;

}

I want to know is there any setting to enable this API Call or any other method which will call this api successfully?

A: Address Verification is normally not enabled with sandbox. So, you will need to open a support request or make phone call to enable that.


text:
Q: Passing location to different view with segue very very new to iOS programming, so I appreciate any help with this.
All I actually want to do is pass the variable of my current coordinates to a different view when a button is pressed. I can't work out how to do this using my current work - I'm getting in a total muddle. My project is essentially made from lots of chunks of code from various sources. I'll share with you the parts that I think are relevant, and hopefully somebody can at least point me in the right direction!
This is from my MainViewController.m:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

if (currentPosition == nil) {

    MKMapPoint point = MKMapPointForCoordinate(newLocation.coordinate);

    double pointsPerMeter = MKMapPointsPerMeterAtLatitude(newLocation.coordinate.latitude);

    double visibleDistance = pointsPerMeter * 500.0;

    MKMapRect rect = MKMapRectMake(
                                   point.x - visibleDistance, point.y - visibleDistance,
                                   visibleDistance * 2, visibleDistance * 2);
           [self.mapView setVisibleMapRect:rect animated:YES];

    NSURL *url = [NSURL URLWithString:@"https://url.url/json.json"];
    NSData *data = [NSData dataWithContentsOfURL:url];

    NSError *error;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data
                                                     options:0
                                                       error:&error];
    if (error != nil)
    {

    }

    CLLocationCoordinate2D location;
    NSMutableArray *newAnnotations = [NSMutableArray array];
    MKPointAnnotation *newAnnotation;

    for (NSDictionary *dictionary in array)
    {

        location.latitude = [dictionary[@"lat"] doubleValue];
        location.longitude = [dictionary[@"lon"] doubleValue];

        newAnnotation = [[MKPointAnnotation alloc] init];

        newAnnotation.coordinate = location;

        HUWMapAnnotation *annotation = [[HUWMapAnnotation alloc] initWithCoordinate:newAnnotation.coordinate];
        annotation.messagetitle = dictionary[@"name"];
        annotation.email = dictionary[@"message"];
        annotation.username = dictionary[@"user"];

        [self.mapView addAnnotation:annotation];

        [newAnnotations addObject:newAnnotation];

    }

}
currentPosition = newLocation;
}

- (void)viewDidLoad { [super viewDidLoad];

// Check if the user has enabled location services.
if ([CLLocationManager locationServicesEnabled]) {
    // Create a location manager.
    locationManager = [[CLLocationManager alloc] init];
    // Set ourselves as it's delegate so that we get notified of position updates.
    locationManager.delegate = self;
    // Set the desired accuracy.
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // Start tracking.
    [locationManager startUpdatingLocation];
}
}

Like I said, I've trimmed this down substantially to the bits I think are relevant. Let me know if I have missed something essential. I've got my storyboard set up with a button ready to go, and a segue with its identifier.
I assume that I should be using prepareForSegue - but my issue is that I quite simply don't know how to get my coordinates into that situation.
I hope somebody will be able to help me (and I apologise for the large amount of copy-pasted code!)

A: To pass objects between view controllers using segues, do something like the following:
1) create a segue between the source and destination view controllers in IB, give it an identifier @"MySegue".
2) let's say the destination vc needs a string to run:
// DestinationVC.h
@interface DestinationVC : UIViewController
@property(strong, nonatomic) NSString *string;
@end

3) the source vc initiates a segue:
[self performSegueWithIdentifier:@"MySegue" sender:self];

4) the source vc prepares by initializing the property on the destination vc:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"MySegue"]) {
        DestinationVC *vc = [segue destinationViewController];
        vc.string = // some object that the source vc has.  this could be your CLLocationCoordinate2D
    }
}


text:
Q: Resolved Promise not executing then function I'm facing an issue where in my resolved promise is not executing the next chained then.
My code is like below
WordDocument.prototype.Open = function (data) {
        var _this = this;
        debugger;
        var that = this;
        var input = {
            onBeforeClose: function (data, callback) {
            },
            onBeforeSave: function (data, callback) {
                //alert('on Save');
                //this.Save(data);
            },
            path: "\\ElectronClient\\cm.doc"
        };
        var deferred = Q.defer();
        this.getDocument(data.docusId)
            .then(function (httpRes) {
                debugger;
                var response = JSON.parse(httpRes);
                return _this.saveDocumentInTemp(response);
            }).then(function (fileRes) {
                debugger;
                return _this.getInteropHandle(input);
            })["catch"](function (err) {
                deferred.reject(err);
            })["finally"](function (f) {
                debugger;
            });
        return deferred.promise;
    };

The first then is executing perfectly fine..and then function is getting executed properly...but as you can see that I have returned the Promise of
_this.saveDocumentInTemp(response);

to the next chained then..but this second then is never getting executed..
The code for _this.saveDocumentInTemp(response); is like below:(not posting the exact code)
WordDocument.prototype.saveDocumentInTemp = function (response) {
    var deferred = Q.defer();
    deferred.resolve(true);
    return deferred.promise;
};


text:
Q: Slow spring-ws/hibernate application on osx Recently I've got my new mac book. I port my java project(spring 4/hibernate 5/spring-ws/spring-security/tomcat/ojdbc) from Windows laptop. Everything works fine until yesterday. All request took very long time to proceed. Normally response from spring-ws endpoint took under 1s(with remote oracle db via vpn). Now it is about 16s. When I turn off spring-security(with same db for users, checking every soap request via basic http auth) in application, I can lower response to 6s.
With spring-security turned off(6s responses) i turn on logging for hibernate.stat and finds out that jdbc connection is established in about 5,5s.
I dont understand what happened. Responses on mac was fine before, after morning application redeploy it slow down. I tried different tomcat installation, local db, even reinstall my mac, no changes at all.
Edit: I run application in parallel on Windows laptop and there are no issues on Windows
Edit 2: I create console java app with simple jdbc connection and it take about 5s to establish connection. So it seems it is network related issue.
Edit 3: I switch oracle for postgresql db(same server) and postgre is doing fine. Oracle still slow.

A: Finally I realized what was the problem. As I said in edit 2, it was network related. My nameserver was not configured properly. So I have two options:

*

*edit /etc/resolv.conf and set correct nameserver ip or configure nameserver itself

*disable/comment /etc/resolv.conf nameserver and add db ip/host to /etc/hosts


text:
Q: Linking C++ on Rust: undefined reference to `operator delete(void*)' and `__gxx_personality_v0', libstdc++ missing? I'm trying to build a cpp cmake project and link to my Rust project.
cmake_minimum_required(VERSION 3.0)
set (CMAKE_CXX_STANDARD 17)
project(ZLMediaKit_LIB CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17")

set(ENABLE_TESTS OFF FORCE)
option(ENABLE_TESTS OFF)

set(ENABLE_OPENSSL FALSE FORCE)
option(ENABLE_OPENSSL OFF)

add_subdirectory(ZLMediaKit)

add_library(libzlmediakit_cpp_interface STATIC interface.cpp)
target_include_directories(libzlmediakit_cpp_interface PUBLIC
.
${CMAKE_CURRENT_SOURCE_DIR}/ZLMediaKit/src
${CMAKE_CURRENT_SOURCE_DIR}/ZLMediaKit/3rdpart/ZLToolKit/src)
target_link_libraries(libzlmediakit_cpp_interface zlmediakit zltoolkit mpeg mov flv libstdc++)
install(TARGETS libzlmediakit_cpp_interface DESTINATION .)

Here's my build.rs:
extern crate cmake;
use cmake::Config;

fn main()
{
    let dst = Config::new("zlmediakit_lib").build();

    println!("cargo:rustc-link-search=native={}", dst.display());
    println!("cargo:rustc-link-lib=static=libzlmediakit_cpp_interface");
}

But I'm getting undefined reference errors:
ong)':
          /usr/include/c++/9/ext/new_allocator.h:128: undefined reference to `operator delete(void*)'
          /usr/bin/ld: /home/dev/orwell/liborwell_rust/zlmediakit_rust/target/debug/build/zlmediakit_rust-499cc82f14515635/out/liblibzlmediakit_cpp_interface.a(interface.cpp.o): in function `ZLRTSPClient::~ZLRTSPClient()':
          /home/dev/orwell/liborwell_rust/zlmediakit_rust/zlmediakit_lib/ZLRTSPClient.h:14: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()'
          /usr/bin/ld: /home/dev/orwell/liborwell_rust/zlmediakit_rust/target/debug/build/zlmediakit_rust-499cc82f14515635/out/liblibzlmediakit_cpp_interface.a(interface.cpp.o): in function `std::default_delete<ZLRTSPClient>::operator()(ZLRTSPClient*) const':
          /usr/include/c++/9/bits/unique_ptr.h:81: undefined reference to `operator delete(void*, unsigned long)'
          /usr/bin/ld: /home/dev/orwell/liborwell_rust/zlmediakit_rust/target/debug/build/zlmediakit_rust-499cc82f14515635/out/liblibzlmediakit_cpp_interface.a(interface.cpp.o): in function `__static_initialization_and_destruction_0(int, int)':
          /usr/include/c++/9/iostream:74: undefined reference to `std::ios_base::Init::Init()'
          /usr/bin/ld: /usr/include/c++/9/iostream:74: undefined reference to `std::ios_base::Init::~Init()'
          /usr/bin/ld: /home/dev/orwell/liborwell_rust/zlmediakit_rust/target/debug/build/zlmediakit_rust-499cc82f14515635/out/liblibzlmediakit_cpp_interface.a(interface.cpp.o):(.data.rel.local.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to `__gxx_personality_v0'
          collect2: error: ld returned 1 exit status

I've researched and found some answers (Link error "undefined reference to `__gxx_personality_v0'" and g++) that old me to link against libstdc++. As you see, I'm already doing that.
If I try to compile the CMake project alone, it links sucessfully. However then I compile everything from the Rust side, it gives this error.
Complete output of rust compilation


text:
Q: Comparing column with column of lists and highlighting matches in Pandas, Python I have 2 dataframes in Pandas:
df1 = pd.DataFrame({"ID": [1, 2, 5, 9, 15, 44]})

df2 = pd.DataFrame({"col1": [a, b, c, d],
"col2":[[1, 2, 3, 4, 5], [6, 9, 15, 16, 18], [44], [88, 564, 9856]})

I am interested in matches between df1["ID"] and df2["col2"]. If there are any matches, I would like to highlight them in df2.
I found some inspiration here:
comparing two columns and highlighting differences in dataframe
And here:
colour element of a list by looping over another list
This is what I have and is not correct.
def highlight():
    df = pd.DataFrame(columns=d.columns, index=d.index)
    df2.loc[df2['col2'].eq(df1['ID']), ['col1', 'col2']] = 'background: yellow'
    return df

df1.style.apply(highlight, axis=None)


text:
Q: Значение this.el остается undefined при изменении Здравствуйте.
Имеется вьюшка:
var SessionView = Backbone.View.extend({
el: $("#main_content"),

template: JST["main"],

render: function()
{
    $(this.el).html(this.template);
    return this;
}
});

var view = new SessionView();

И роутер:

var ProfileRouter = Backbone.Router.extend({
   routes: {
     "main": "main"
   },
   main: function(){
      view.render();
   }
});

В итоге:
this.el равен undefined, и тем самым шаблон не рендерится.
Но если $(this.el).html(this.template); заменить на $("#main_content").html(this.template); - то все работает.

Пробовал использовать this.$el.html() - он тоже не рендериться, хотя селектор указывает верный
Подскажите пожалуйста что я делаю не так?
A: Роитинг и создание Backbone histrory происходит в $(document).ready, а new SessionView перенес в роутинг при рендереге, но все так же и осталось.
То что SessionView не видит id #main_content видимо из-за того что он подключается до рендеринга html, но если View обрамлять $(document).ready - то роутер просто не находит его.
Перенес подключение js файлов в конец страницы и this.el - заработал. Спасибо вам за помощь и наведение в правильную сторону размышления.


text:
Q: How to to implement a call button in the ListView? I am working on an android project. It is blood donor searching app. When the user searches for blood donor, the current location of the user is identified by the GPS. The coordinates are then compared with the details in the database. Then matching donor contact details are retrieved.
The details are printed in the format of a ListView. I want to provide a calling option with these details. for eg. when the details are displayed, the user can long press on the phone number to call the donor. can this be implemented?
How can I implement this? Is it possible

A: Implement setOnLongClickListener on your Phone number textView. For example,
txtPhoneNumber.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
         Uri number = Uri.parse("tel:"+ txtPhoneNumber.getText().toString);
         Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
         startActivity(callIntent);

         return true;
        }
    });

And the permission <uses-permission android:name="android.permission.CALL_PHONE" />
BTW are you using a custom adapter for your listview?

A: listView.setOnItemLongClickListener(new OnItemLongClickListener() {

      public boolean onItemLongClick(AdapterView<?> arg0, View v,
              int position, long arg3) {
          Toast.makeText(ListViewTestActivity.this, "content"+position, Toast.LENGTH_LONG).show();
          return false;
      }
  });

A: For TextView long click:
textView.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        callNumber(textView.getText().toString().trim());
        return true;
    }

});
Here is the method with which you can make a call:
private void callNumber(String telephoneNumber) {
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telephoneNumber.replace("-", "")));
    startActivity(intent);
}

Dont forget to add permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.CALL_PHONE" />


text:
Q: connecting to Access in vb6 I am trying to connect to database with password, but i m getting an Error
This is my Connection String
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Database\HMS.mdb;" _
& "Password=admin;"

I am Getting an Error :
Cannot Start Your Application. Workgroup Information File is Missing or Opened Exclusively by the another user.

A: Try this connection string:
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & App.Path & "\Database\HMS.mdb;" _
& "Jet OLEDB:Database Password=admin;"


text:
Q: How to end all processs of one MPI communicator without closing the program? In fortran, how do I finish only one communicator (not MPI_COMM_WORLD) without closing the program?
I've tried to do:
call MPI_ABORT(mpiCommGroup, ierror, ierr)

But the program ends


text:
Q: VueJS dynamically add textareas based on user click (tinymce issue) I built a dynamic form where the user has the option to add as many HTML textareas as possible. The problem I'm running into is when the user loads the next textarea, I lose tinymce. Same thing happening for any external script (example: datepicker and Select2.js). Any ideas?
Here is my code

      <email_template_row></email_template_row>

<button class="btn btn-sm btn-success" @click="addRow" type="button">Add Row</button>
// Tinymce code here...
// load vuejs from cdn...
        Vue.component('email_template_row', {
            template: '
<textarea name="col_2_content[]" class="form-control tinymce" placeholder="Body"></textarea>
',
        });
        var vue = new Vue({
            el: '#app',
            data:{
              counter: 1
            },
            methods: {
                addRow: function () {
                    this.counter += 1;
                }
            },
        });

Thank you.

A: You need to re-initialize those components after one is appended to the HTML.
So basically your addRow method should look like this:
addRow: function () {
    this.counter += 1;

    tinymce.init({
      selector: 'textarea',  // change this value according to your HTML, you can be more specific
      auto_focus: 'element',
      // add your configuration
    });
}


text:
Q: Android RadioGroup click listener I have definiation below of radiogroup with radiobuttons. How properly implement onClickListener ? I got ArrayIndexOutOfBoundsException. I don't know what is wrong.
 public void createRadioButton(Integer amount, LinearLayout layout, Integer text) {

    AppCompatTextView txt = new AppCompatTextView(activity);
    AppCompatButton btn = new AppCompatButton(activity);
    btn.setText("Click");
    txt.setText(text);
    final AppCompatRadioButton[] rb = new AppCompatRadioButton[amount];
    final RadioGroup rg = new RadioGroup(activity);

    rg.setOrientation(RadioGroup.VERTICAL);

    for( i=0; i<amount; i++){
        rb[i]  = new AppCompatRadioButton(activity);
        rg.addView(rb[i]);
        rb[i].setId(i + 100);
        rb[i].setText("Test " + i);
    }
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            int selectedId = rg.getCheckedRadioButtonId();
            rb[i] = (AppCompatRadioButton) activity.findViewById(selectedId);

           Toast.makeText(activity, "VALUE" rb[i].getText(), Toast.LENGTH_SHORT).show();
        }
    });
    layout.addView(txt);
    layout.addView(rg);
    layout.addView(btn);
}

A:  for( i=0; i<amount; i++){
        rb[i]  = new AppCompatRadioButton(activity);
        rg.addView(rb[i]);
        rb[i].setId(i + 100);
        rb[i].setText("Test " + i);

    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            int selectedId = rg.getCheckedRadioButtonId();
            rb[i] = (AppCompatRadioButton) activity.findViewById(selectedId);

           Toast.makeText(activity, "VALUE" rb[i].getText(), Toast.LENGTH_SHORT).show();
        }
    });
}

If you want to add a onclicklistener for each item that you loop over, you need to extend your for loop so it also iterates over your onclicklistener, like this.

A: use setOnCheckedChangeListener for radiogroup
use like this
radiogroup_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    switch (checkedId){
                        case R.id.radiobutton_male :
                             break;
                        case R.id.radiobutton_female :

                            break;
                        default:
                             break;
                    }
                }
            });

A: After the loop your i values will be equal to amount and you are using the same i here rb[i] = (AppCompatRadioButton) activity.findViewById(selectedId);
and your list size equal to amount-1 this is why you get ArrayIndexOutOfBoundsException

A: You have a few errors in your code. First your parameter text should be a "String", not an integer. However, the main problem in your code is that you're overidding the last radioButton ( rb[i] ) with your code. You shouldn't do this.
The best way to do it is to declare your variable i in the loop and to create a new RadioButton when the user clicks on it.
Ps : The solution you validated is unefficient as it creates a click listener everytime you create a button. Or it always update the same listerner because you only have one button.
Try the following code ;)
public void createRadioButton(Integer amount, LinearLayout layout, String text) {

    AppCompatTextView txt = new AppCompatTextView(activity);
    AppCompatButton btn = new AppCompatButton(activity);
    btn.setText("Click");
    txt.setText(text);
    final AppCompatRadioButton[] rb = new AppCompatRadioButton[amount];
    final RadioGroup rg = new RadioGroup(activity);

    rg.setOrientation(RadioGroup.VERTICAL);

    for(int i=0; i<amount; i++){
        rb[i]  = new AppCompatRadioButton(activity);
        rg.addView(rb[i]);
        rb[i].setId(i + 100);
        rb[i].setText("Test " + i);
    }
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int selectedId = rg.getCheckedRadioButtonId();
            AppCompatRadioButton button= (AppCompatRadioButton) activity.findViewById(selectedId);

            Toast.makeText(activity, "VALUE" +  button.getText(), Toast.LENGTH_SHORT).show();
        }
    });
    layout.addView(txt);
    layout.addView(rg);
    layout.addView(btn);
}


text:
Q: Pyautogui mouse click on different resolution I'm writing a script for automatizing some tasks at my job. However, I need to make my script portable and try it on different screen resolution.
So far right now I've tried to multiply my coordinate with the ratio between the old and new resolutions, but this doesn't work properly.
Do you know how I can convert my X, Y coordinates for mouse's clicks make it works on different resolution?

A: Quick question: Are you trying to get it to click on certain buttons? (i.e. buttons that look the same on every computer you plug it into) And by portable, do you mean on a thumb drive (usb)?
You may be able to take an image of the button (i.e. cropping a screenshot), pass it on to the opencv module, one of the modules has an Image within Image searching ability. you can pass that image along with a screenshot (using pyautogui.screenshot()) and it will return the (x,y) coordinates of the button, pass that on to pyautogui.moveto(x,y) and pyautogui.click(), it might be able to work. you might have to describe the action you are trying to get Pyautogui to do a little better.


text:
Q: Play 2048 using selenium I have written code that will play 2048 untill the game end but is there any way to have selenium click the try again button when it pops up?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()
browser.get('https://gabrielecirulli.github.io/2048/')

grid = browser.find_element_by_tag_name('body')
direction = {0: Keys.UP, 1: Keys.RIGHT, 2: Keys.DOWN, 3: Keys.LEFT}
count = 0
browser.find_element_by_class_name('grid-container').click()
while True:
    count += 1
    grid.send_keys(direction[count % 4])
    try:
        WebDriverWait(browser, .00001).until(
            EC.presence_of_element_located((By.ID, "game-message game-over")))
        browser.find_element_by_class_name('game-over').click()
    except:
        print("OK")

A: After quickly playing the game, the retry button looks to be:
Try again

So
browser.find_element_by_class_name('retry-button').click()

Should work for you