text:
Q: WPF window_loaded exception in my first WPF application I am learning WPF and its my first MVVM application. I am seeing a video where the MVVM is demonstrated using Silverlight app. However, I am mimicking it for WPF. in Silverlight, the video presenter creates an event in UserControl XAML tag namely UserControl_Loaded which is successful.
However, I am creating a Window_Loaded in Window root element of xaml file of MainWindow.xaml
I am getting this error :( Please help me. This event "Window_Loaded" is in this 5th line only.
Exception:

'Add value to collection of type
  'System.Windows.Controls.UIElementCollection' threw an exception.'
  Line number '5' and line position '28'.
Inner Exception:
{"Window must be the root of the tree. Cannot add Window as a child of
  Visual."}

Please also explain me why it is happening along with the solution. I am just trying to learn MVVM and using observable collection, INotifyPropertyChanged and a model class and I am generating data of this object in hardcoded way.
Note:
I suspect it is due to clr-namespace.
First, I am wondering, why if I type clr, intellisense is not taking me to clr ? Rather it just takes me to first http in the sequence of list of namespaces. Second, the Silverlight Video used the namespace of the project, however, I used the namespace of the View. Because, when I use the namespace of the project, it gives me error saying "view" is not found. Anywhere I am going wrong :(
(OR):
Is it due to a new Window.xaml page that I am trying to insert into another window.xaml page ? Unlike the Silverlight video where it does insert a UserControl into a Page.
MainWindow into MainWindow is a problem here ?
If I use UserControl into MainWindow will it be resolved ? Meaning tha, we cnn't have window into window ?

A: You can not have a Window inside another Window! Window should be the root element of your xaml, and you can add other elements inside it. For example Grid. My suggestion is to find some WPF tutorials and books (not silverlight), for starting, because WPF is much more powerfull, and in many ways different.

A: Window.xaml:
<Window  x:Class="WpfMvvmApplication1.Views.Login"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:View="clr-namespace:WpfMvvmApplication1.Views">
<Grid>
   <View:UserControl/>
</Grid>
</Window>

This will import your usercontrol into window./
Hope this will help you.


text:
Q: why the submenu opens a bit late after the first click? Both menu and sub menu have the same css features. Submenu opens when I hover the Products and Campaigns buttons. The submenu is opening but I wonder why the submenu opens a bit late after the first click but opens normally in the next clicks?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hemilia</title>

    <button class="drop-btn" onmouseenter="onMouseEnter('.products')" onmouseleave="onMouseLeave('.products')">Products</button>
    <button class="drop-btn" onmouseenter="onMouseEnter('.campaigns')" onmouseleave="onMouseLeave('.campaigns')">Campaigns</button>
    <button class="drop-btn">Contact</button>
    <button class="drop-btn">About</button>

      <button class="products-btn">Food</button>
      <button class="products-btn" >Clothes</button>
      <button class="products-btn" >Accessories</button>

      <button class="campaigns-btn">New</button>
      <button class="campaigns-btn" >Old</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Home Page content not showing in Magento 2.4.3-p1 I am using codazon theme for my Magento store. The home page content is not displaying.
Previously it was working fine. Please suggest.

A: There are several reasons why the content on your home page may not be displaying. Here are some steps you can take to troubleshoot the issue:

*

*Check if the content is enabled: Make sure that the content you want to display on your home page is enabled. To do this, go to your Magento admin panel and navigate to Content > Pages > Home Page. Then, click on the Content tab and ensure that the content is enabled.

*Clear cache: It is possible that the content is not displaying due to cached files. To clear the cache, go to System > Cache Management in your Magento admin panel and click on the Flush Magento Cache button.

*Check for conflicts: Sometimes, there can be conflicts with other extensions or modules that may be preventing your content from displaying. Try disabling any recently installed extensions or modules to see if that resolves the issue.

*Check for errors: Check your server error logs to see if there are any errors that may be causing the content to not display. If there are any errors, try fixing them or consult with your hosting provider or developer for further assistance.


text:
Q: If the sum of two $p$th powers is divisible by $p$, then it is divisible by $p^2$
If $p > 2$ is a prime and $p | (x^p + y^p)$, then show that $p^2 | (x^p + y^p)$

I have been stuck on this problem for a while now. (Though my textbook is prone to mistakes so the original proposition could be wrong).

A: By Fermat's little theorem, $t^p\equiv t\pmod p$ for any $t$, so if $p\mid x^p+y^p$ then in fact $p\mid x+y$ (or $y\equiv -x\pmod p$).
Now, since $p$ is odd, $$x^p+y^p=(x+y)(x^{p-1}-x^{p-2}y+x^{p-3}y^2-\cdots+y^{p-1}).$$ The first term is a multiple of $p$, as explained above. The second is $$\sum_{k=0}^{p-1}(-1)^k x^{p-1-k}y^k=\sum_{k=0}^{p-1}x^{p-1-k}(-y)^k\equiv \sum_{k=0}^{p-1}x^{p-1-k}x^k=\sum_{k=0}^{p-1}x^{p-1}=px^{p-1}\equiv0\pmod p.$$

A: By Fermat's Little theorem you have $x^p=x\bmod p$ and $y^p=y\bmod p$. Hence $p$ divides $x+y$. So we can write $y=kp-x$. Hence $y^p=(kp-x)^p$. Expanding by the binomial theorem we get $-x^p$ plus terms in $p^2$.

A: By Fermat's little theorem, if $p$ is prime, $x^p\equiv x\pmod p$.  Therefore, $p\mid x^p+y^p$ iff $x^p+y^p\equiv 0\pmod p$ so that $x+y\equiv 0\pmod p$.
Then $y=kp-x$ for some integer $k$  Therefore, $$x^p+y^p=x^p+\sum_i\binom{p}{i}(kp)^i(-x)^{p-i}.$$  Expanding out a few terms, we can rearrange this as follows:
$$
x^p+\sum_{i=2}^p\binom{p}{i}(kp)^i(-x)^{p-i}+\binom{p}{1}(kp)(-x)^{p-1}+(-x)^p.
$$
Since $p$ is an odd prime, $(-x)^p=-x^p$, which cancels with $x^p$.  All of the terms in the sum are divisible by $p^2$ since $i\geq 2$, it follows that $p^2\mid p^i\mid (kp)^i$.  Finally, $p^2\mid \binom{p}{1}(kp)(-x)^{p-1}=kp^2x^{p-1}$ since $\binom{p}{1}=p$.

A: Hint $\,{\rm mod}\ p\!:\  f(x) = x^p\!+y^p \equiv (x\!+\!y)^2 g(x,y)\,$ since $\,x\equiv -y\,$ is a double root of $f(x)\,$ by $\,f(-y) \equiv 0,$ $\,f'(-y) = p(-y)^{p-1}\!\equiv 0.\ $ So $\,\ p\mid x^p\!+y^p\equiv x\!+\!y\,\Rightarrow\, p^2\mid (x\!+\!y)^2\mid x^p\!+y^p$


text:
Q: How to add object to document before returning it? I want to solve the following problem:
After fetching a collection from Firestore via angularfire, I want to iterate through each document within these collection and than do a separate Firestore request to get a corresponding document which values I want to insert into the first document before returning the collection.
For example, there is a object called ball with the properties
interface Ball: {
  uid: string;
  color: string;
}

And a object player with the properties
interface Player: {
  uid: string;
  correspondingBall: ball;
}

Within the Firestore collection, I save a document from type Player with the corresponding id from the corresponding ball (I hope you know what I mean).
Now, I access the the collection player
getRecentPlayers(): Observable<Player[]> {
    const players: AngularFirestoreCollection<any> = this.angularFirestore.collection<Player>('players');
    return players ? players.snapshotChanges().pipe(
      map(players => {
        return players.map(player => {
          const data = player.payload.doc.data() as Player;
          const correspondingBall: AngularFirestoreDocument<Ball> = this.angularFirestore.doc('balls/' + data.correspondingBall);
          correspondingBall ? correspondingBall.snapshotChanges().pipe(
            map(ball => {
              const data = ball.payload.data() as Ball;
              return data;
            })
          ) : null;
          return {...data, correspondingBall}
        })
      })
    ) : null;
  }

That way, I wouldn't work. Can someone help me?
Thank you very much!!

A: in general the way is: make a consult (return an array of values), make a switchMap, create an array of observables, make a forkjoin, map with index to add the new properties. I go to code using simples gets
getPlayers().pipe(
  switchMap(players=>{
    //in players we has an array of player
    //create an array of observables with the array
    const obs=players.map(player=>getBall(player.ballId)
    //a switchMap must return an observable, so return a forkJoin
    return forkjoin(obs).pipe(
       //but we transform the result that is an array
       //with the values of getBall(1),getBall(2)..
       map((ball,index)=>{
          //concat the properties of players[index] with the ball
          return {...players[index],..ball}
       })
    )
  }
)).subscribe(res=>console.log(res))


text:
Q: How to use Vue.JS & Vue-Resource in Sails.JS? I'm new to Sails.JS and want to use Vue.JS in my views (every .ejs has a script) but I don't know the correct way to do it.
If I create a script tag in the end of the view, this throws an error because Vue.JS hasn't loaded. So, I created a folder in assets to save all my .js files and now I don't know how to import Vue-Resource without getting this error: Cannot read property 'get' of undefined.
I've checked this: https://github.com/pagekit/vue-resource/issues/579 but still haven't had success.
Thanks for your help!

A: In your vue main.js make sure you have
var VueResource = require('vue-resource');
Vue.use(VueResource);

In vue templates you can access it like:
<script>
    export default {
        data(){
            return {}
        },
        created(){
            console.log(typeof this.$http);
        },
        mounted(){
            console.log(typeof this.$http);
        }
    }
</script>

When dealing with resources I recommend using Vuex and use the state to hold the data. https://vuex.vuejs.org/


text:
Q: How to output the list of probabilities on each token via model.generate? Right now I have:
model = GPTNeoForCausalLM.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.cuda()
gen_tokens = model.generate(input_ids, do_sample=specifiedDoSample, output_scores=True, temperature=specifiedTemperature, max_new_tokens=specifiedNumTokens, repetition_penalty=specifiedRepetitionPenalty, top_p=specifiedTopP)
gen_text = tokenizer.batch_decode(gen_tokens)[0]
print(gen_text)

This will print the generated text. However, I want it to list the top N tokens in each step as well as their probability (N being a number specified by me), similar to OpenAI's beta playground where you can select "Show probabilities: Full spectrum". For example, if the prompt is "You are now a", the next token should say something like {"vampire": 51%, "corpse": 32% ... etc.}
What is the easiest way to do this via Huggingface Transformers?

A: You need to add ", output_scores=True, return_dict_in_generate=True" in the call to the generate method, this will give you a scores table per character of generated phrase, which contains a tensor with the scores (need to softmax to get the probas) of each token for each possible sequence in the beam search.
Look at generation_utils.py in the transformers source tree, starting at "def generate"

A: A potential workaround is in the thread https://github.com/huggingface/transformers/issues/10012.
Use beam search as described in the thread, using n beams where n is the number of probs you want to display, but only looking 1 token into the future. Then, according to comment by mshuffett:

I just moved this line below the return_dict_in_generate block.
next_token_scores = next_token_scores + beam_scores[:, None].expand_as(next_token_scores)

I tried it and it worked perfectly. The next single token's probabilities now displayed correctly.
Alternatively you can try the solutions described in https://github.com/huggingface/transformers/issues/16010. I haven't gotten around to it because it looks slightly more involved than the easy workaround.


text:
Q: Android - MediaPlayer Buffer Size in ICS 4.0 I'm using a socket as a proxy to the MediaPlayer so I can download and decrypt mp3 audio before writing it to the socket. This is similar to the example shown in the NPR news app however I'm using this for all Android version 2.1 - 4 atm.
NPR StreamProxy code - http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/StreamProxy.java
My issue is that playback is fast for 2.1 - 2.3, but in Android 4.0 ICS the MediaPlayer buffers too much data before firing the onPrepared listener.
An example amount of data written to the Socket OutputStream before onPrepared():
On SGS2 with 2.3.4 - onPrepared() after ~ 133920 bytes
On Nexus S with 4.0.4 - onPrepared() after ~ 961930 bytes
This also occurs on the Galaxy Nexus.
Weirdly the 4.0 emulator doesn't buffer as much data as 4.0 devices. Anyone experience a similar issue with the MediaPlayer on ICS?
EDIT
Here's how the proxy is writing to the socket. In this example it's from a CipherInputStream loaded from a file, but the same occurs when it's loaded from the HttpResponse.
final Socket client = (setup above)

// encrypted file input stream
final CipherInputStream inputStream = getInputStream(file);

// setup the socket output stream
final OutputStream output =  client.getOutputStream();

// Writing the header
final String httpHeader = buildHttpHeader(file.length());
final byte[] buffer = httpHeader.getBytes("UTF-8");
output.write(buffer, 0, buffer.length);

int writtenBytes = 0;
int readBytes;
final byte[] buff = new byte[1024 * 12]; // 12 KB

while (mIsRunning && (readBytes = inputStream.read(buff)) != -1) {
    output.write(buff, 0, readBytes);
    writtenBytes += readBytes;
}

output.flush();
output.close();

The HTTP Headers that are written to the MediaPlayer before the audio..
private String buildHttpHeader(final int contentLength) {
    final StringBuilder sb = new StringBuilder();

    sb.append("HTTP/1.1 200 OK\r\n");
    sb.append("Content-Length: ").append(contentLength).append("\r\n");
    sb.append("Accept-Ranges: bytes\r\n" );
    sb.append("Content-Type: audio/mpeg\r\n");
    sb.append("Connection: close\r\n" );
    sb.append("\r\n");

    return sb.toString();
}

I've looked around for alternate implementations but as I have encrypted audio and the MediaPlayer does not support InputStreams as a data source my only option (I think..) is to use a proxy such as this.
Again, this is working fairly well Android 2.1 - 2.3 but in ICS the MediaPlayer is buffering a huge amount of this data before playing.
EDIT 2 :
Further testing is showing that this is also an issue on the SGS2 once upgraded to Android 4.0.3. So it seems like the MediaPlayer's buffering implementation has changed significantly in 4.0. This is frustrating as the API provides no way to alter the behaviour.
EDIT 3 :
Android bug created. Please add comments and star there as well
http://code.google.com/p/android/issues/detail?id=29870
EDIT 4 :
My playback code is fairly standard.. I have the start() call on the MediaPlayer in my onPrepared() method.
mCurrentPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mCurrentPlayer.setDataSource(url);
mCurrentPlayer.prepareAsync();

Have tried it using just prepare() and also ajacian81's recommended way but to no avail.
I should add that recently a Google employee got back to me about my question and confirmed that the buffer size was intentionally increased in ICS (for HD content). It has been requested to the API developers to add the ability to set a buffer size on MediaPlayer.
Though I think this API change request had been around before I came along so I wouldn't advise anyone to hold their breath.

A: Would it be possible to see the code where you're start()ing the MediaPlayer?
Are you using the STREAM_MUSIC audio stream type?
player.setAudioStreamType(AudioManager.STREAM_MUSIC);

Have you also experimented between player.prepareAsync(); and player.prepare();?
There was a similar issue last year I remember, where the solution was to: start, pause and then onPrepared to start():
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(src);
player.prepare();
player.start();
player.pause();
player.setOnPreparedListener(new OnPreparedListener() {
@Override
                public void onPrepared(MediaPlayer mp) {
                    player.start();
                }
          });

Unlikely to be the fix in this case, but while you're spinning your wheels this might be worth a shot.

A: For me the solution was to use MediaCodec with AudioTrack, I found all I need to know here:
This could be a solution: http://www.piterwilson.com/blog/2014/03/15/mediacodec-mediaextractor-and-audiotrack-to-the-rescue/


text:
Q: Creating a summary column of if another column is present I am wanting to creat a column showing the combination of if other columns are present, this is best explained as an example:
##random data
Data <- data.frame(
    a = sample(c("0", "1"), 10, replace = TRUE),
    b = sample(c("0", "1"), 10, replace = TRUE),
    c = sample(c("0", "1"), 10, replace = TRUE),
    d = sample(c("0", "1"), 10, replace = TRUE)
)

##this creates a table like this

| a  | b  | c  | d  |
| :- |: - | :- |: - |
| 0  | 0  | 0  | 1  |
| 0  | 1  | 0  | 1  |
| 0  | 0  | 1  | 1  |
| 0  | 0  | 0  | 0  |
| 0  | 1  | 1  | 0  |
| 0  | 1  | 1  | 0  |
| 0  | 1  | 1  | 0  |
| 1  | 1  | 1  | 0  |
| 1  | 0  | 0  | 0  |
| 0  |0   | 1  | 1  |

##I wish to add a column on the end saying if a 1 is present with a space, for instance:

| a  | b  | c  | d  |together  |
| :- |: - | :- |: - |          |
| 0  | 0  | 0  | 1  |d         |
| 0  | 1  | 0  | 1  |b d       |
| 0  | 0  | 1  | 1  |c d       |
| 0  | 0  | 0  | 0  |None      |
| 0  | 1  | 1  | 0  |b c       |
| 0  | 1  | 1  | 0  |b c       |
| 0  | 1  | 1  | 0  |b c       |
| 1  | 1  | 1  | 0  |a b c     |
| 1  | 0  | 0  | 0  |a         |
| 0  |0   | 1  | 1  |c d       |

Does any one have any code for this? I have tried with if else functions, or coding it as 0010 = c, 0001 = d but with 8 variables in the real dataset this is quite a lot!
Many thanks

A: One way would be:
library(dplyr)

set.seed(2311)

Data <- data.frame(
  a = sample(c("0", "1"), 10, replace = TRUE),
  b = sample(c("0", "1"), 10, replace = TRUE),
  c = sample(c("0", "1"), 10, replace = TRUE),
  d = sample(c("0", "1"), 10, replace = TRUE)
)

Data %>%
  rowwise %>%
  mutate(
    together = paste(
      names(.)[which(c_across(everything()) == 1L)],
      collapse = ' '
    ),
    together = replace(together, together == '', 'None')
  )

Output (the test set is different as you haven't set the seed):
# A tibble: 10 × 5
# Rowwise:
   a     b     c     d     together
   <chr> <chr> <chr> <chr> <chr>
 1 0     0     1     1     c d
 2 1     0     0     0     a
 3 0     0     0     0     None
 4 1     1     1     0     a b c
 5 1     1     0     0     a b
 6 1     1     0     1     a b d
 7 0     0     0     1     d
 8 1     0     0     0     a
 9 0     1     0     0     b
10 0     1     0     1     b d

A: Here is one option in tidyverse
library(dplyr)
library(tidyr)
Data %>%
   mutate(across(everything(),
    ~ case_match(.x, 1 ~ cur_column()), .names = "{.col}_new")) %>%
   unite(together, ends_with("_new"), sep = " ", na.rm = TRUE)

-output
# A tibble: 10 × 5
       a     b     c     d together
   <dbl> <dbl> <dbl> <dbl> <chr>
 1     0     0     0     1 "d"
 2     0     1     0     1 "b d"
 3     0     0     1     1 "c d"
 4     0     0     0     0 ""
 5     0     1     1     0 "b c"
 6     0     1     1     0 "b c"
 7     0     1     1     0 "b c"
 8     1     1     1     0 "a b c"
 9     1     0     0     0 "a"
10     0     0     1     1 "c d"

data
Data <- structure(list(a = c(0, 0, 0, 0, 0, 0, 0, 1, 1, 0), b = c(0,
1, 0, 0, 1, 1, 1, 1, 0, 0), c = c(0, 0, 1, 0, 1, 1, 1, 1, 0,
1), d = c(1, 1, 1, 0, 0, 0, 0, 0, 0, 1)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -10L))

A: in Base R you could do:
cbind(df, together=apply(df, 1, function(x)paste(names(df)[x>0], collapse = ' ')))
   a b c d together
1  0 0 0 1        d
2  0 1 0 1      b d
3  0 0 1 1      c d
4  0 0 0 0
5  0 1 1 0      b c
6  0 1 1 0      b c
7  0 1 1 0      b c
8  1 1 1 0    a b c
9  1 0 0 0        a
10 0 0 1 1      c d

or even:
df$together <- NULL # NOT NECESSARY
idx <- which(df>0, TRUE)
n <- tapply(names(df)[idx[,2]], idx[,1],paste, collapse = ' ')
df[names(n), 'together'] <- n

df
# A tibble: 10 × 5
       a     b     c     d together
   <dbl> <dbl> <dbl> <dbl> <chr>
 1     0     0     0     1 d
 2     0     1     0     1 b d
 3     0     0     1     1 c d
 4     0     0     0     0 NA
 5     0     1     1     0 b c
 6     0     1     1     0 b c
 7     0     1     1     0 b c
 8     1     1     1     0 a b c
 9     1     0     0     0 a
10     0     0     1     1 c d


text:
Q: How to disable the warning of Unnecessary Using of Directive in vscode? I am currently using VS code develop my game with Unity.
Every time I open the editor, there is a 99+ Unnecessary using of directive which makes me unhappy. Since there are lots of dependency of 3rd party plugins, I'am not sure weather I can remove them. So I want to have some method to disable them.
I tried something like:
"csharp.lint.unnecessaryUsingDirective": "ignore"

But obviously, it doesn't work. So I wish there would be something I can do to hide or disable this warning.

A: I think this issue has already been addressed in the latest version of Omnisharp — but because we are forced to use the legacy C# extension for Unity, the solution remains unclear.
We should be able to add something like this to an omnisharp.json file in our project root:
{
    "IgnoredCodeIssues": [
        "^Unnecessary using directive.$"
    ]
}

But presently, this throws an error:
System.FormatException: Unsupported JSON token 'StartArray' was found.
Path 'IgnoredCodeIssues', line 2 position 27.

I have opened a new issue specifically for the legacy C# extension, in hopes that it gets some feedback from the Omnisharp-VSCode team.


text:
Q: SublimeUI5 in Sublime Text During installation of SublimeUI5 in sublime Text I am facing a problem in 5th step actually.
check the link for Installation: GitHub (qmacro)
In console its throwing me an error saying:
WindowsError: [Error 3] The system cannot find the path specified:
> u'c:\\[sublime_install]\\Data\\Packages\\SublimeUI5\\Templates\\*.*

Please check the below figure:

A: You will have to replace [sublime_install] with proper path. For example,
let's say you cloned git repo to folder:
C:\Users\hollaajay\AppData\Roaming\Sublime Text 2\Packages

NOTE: considering your username is "hollaajay' for Windows as well.
In your STProjectMaker settings you will have to write something like this:
{ "template_path" : "c:/users/hollaajay/AppData/Roaming/Sublime Text 2/Packages/SublimeUI5/Templates }


text:
Q: get id for element that was clicked How do I get the id of the element that was clicked when I have a function like this?
$("#btnOne, #btnTwo").on("click", "input.select", function () {

I tried:
this.id;

and
$(this).attr("id");

Here is the html

                <asp:TextBox ID="tbSearchField" Text="Search..." ClientIDMode="Static" Width="400px" runat="server" CssClass="text ui-widget-content ui-corner-all"></asp:TextBox>

                <input type="button" id="btnSearch" data-str="tblOwnerSearchResults" value="Search" Class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

                <asp:TextBox ID="tbDirector" Text="Search..." ClientIDMode="Static" Width="400px" runat="server" CssClass="text ui-widget-content ui-corner-all"></asp:TextBox>

                <input type="button" id="btnDirectorSearch" data-str="tblDirectorSearchResults" value="Search" Class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

But I am not getting any id from either.
Thanks

A: You use the delegated syntax of the .on().
The event occurs on the input.select element not the #btnOne or#btnTwo.
If you want the containers (#btnOne or btnTwo) id use
$("#btnOne, #btnTwo").on("click", "input.select", function () {
   var id = $(this).closest('#btnOne, #btnTwo')[0].id;
});

Use @undefined's answer if you are using version 1.7 and higher (which you should be)

A: this in your code refers to the input element not the #btnOne and #btnTwo elements, you can use delegateTarget property of event object which refers to the target element of the event delegation.
$("#btnOne, #btnTwo").on("click", "input.select", function(event) {
    console.log(event.delegateTarget.id);
});

http://jsfiddle.net/WNC5y/

A: Since I cant see your HTML I'll offer an example:
HTML

Hello World

jQuery
$(document).ready(function() {
    $("div").click(function() {
        var id = $(this).attr("id");
        alert(id);
    });
});

Tested and works...I did need to wrap the div click selector in quotes (duh!)
Again with respect to my comment, this approach is probably the cleanest for a simple jQuery onClick event.  If you must use the .on() binding method for jQuery it's quite similar.
Delegates

In order to use the .on() delegate method of click event binding, the syntax (as you have in your question) would look something like this:
HTML

Hello World

I'm a delegate!

jQuery
$(document).ready(function() {
    $("#myTable").on("click", "div", function() {
        var id = $(this).attr("id");
        alert(id);
    });
});

This way of event-binding allows for any elements that are descendants (children) of your parent event handler (in our case, #myTable) to be bound as well.  The advantage is any children created and added to the event handler AFTER the handlers creation are also bound.  It can potentially be a godsend for saving time.  Basically, it allows for a quick way to bind events to dynamic objects.  Try it out!

A: Try this code :
$("#btnOne, #btnTwo").click(function(){
    $(this).attr("id");
});


text:
Q: Tornado PeriodicCallback execute at once I want to do refresh a object every 10 minutes so i use tornado.ioloop.PeriodicCallback(myjob, 10*60*1000) BUT the first execution is 10 minute later. Is there some setting to make myjob running at 0 min,10 min, 20min .....?
class Store(object):
    def __init__(self):
        self.data = None

    @tornado.gen.coroutine
    def load(self):
        with (yield STORE_POOL.connected_client()) as client:
            data = yield client.call("HGETALL", self.static_dict_key)
            self.data = {data[i].decode("utf-8"): int(data[i + 1]) for i in range(0, len(data), 2)}

def main():
    ...
    store = Store()
    # ----> Do i need to add some code here? [1]
    backjob = tornado.ioloop.PeriodicCallback(store.load, BACKJOB_TIME)
    backjob.start()

Do i need to add some code in [1]?
I guess there will be 2 plans:
1> change some setting in PeriodicCallback().
2> execute store.load once before PeriodicCallback() BUT I have no idea about how to run a job synchronously with @tornado.gen.coroutine only once.

A: This is very common and I've written similar functions for convenience. Here's a simple way of adding variably timed execution:
from tornado import ioloop

class VariableFire(object):

    def __init__(self, max_delay, increment_by):
        """
        :param max_delay: Max number of seconds.
        :param increment_by: Increment delay per interval until max is hit.
        """
        self.max_delay = max_delay
        self.increment_by = increment_by
        self.delay = 1

    def fire(self, fn, *args, **kwargs):
        # execute
        fn(*args, **kwargs)

        # get the delay interval
        delay = self.delay

        if self.delay < self.max_delay:
            # increment the delay by certain amount
            self.delay += self.increment_by
        elif delay > self.max_delay:
            # reset value to max_delay
            self.delay = delay = self.max_delay

        ioloop.IOLoop.current().call_later(delay, self.fire, fn, *args, **kwargs)

variable = VariableFire(max_delay = 30, increment_by = 3)
variable.fire(print, 'Hello World')

ioloop.IOLoop.current().start()

If you're clever, you can make it into a decorator and use it on functions directly but for the sake of simplicity...

1> change some setting in PeriodicCallback().

Can't do it with PeriodicCallback but with my example, you could change the intervals at a later time.

2> execute store.load once before PeriodicCallback() BUT I have no
  idea about how to run a job synchronously with @tornado.gen.coroutine
  only once.

If you decide to use code similar to my example, you could just run:
variable.fire(store.load)


text:
Q: MVC - Bootstrap autocomplete Typeahead I want to create autocomplete in my MVC site on a textbox with bootstrap typeahead but its not working.
@Html.EditorFor(model => model.Address.Name)

@Html.ValidationMessageFor(model => model.Address.Name)

// AUTOCOMLETE
        $("#Address_Name").typeahead({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Places",
                    type: "POST",
                    dataType: "json",
                    data: { term: request },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name + ' - ' + item.Address, value: item.Name };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });

In the Controller:
// AUTOCOMPLETE - Places
    public ActionResult Places(string term)
    {
        var result = (from r in unitOfWork.AddressRepository.Get()
                         where r.Name.ToLower().Contains(term.ToLower())
                      select new { r.Name, Address = r.Street }).Distinct();

        return Json(result, JsonRequestBehavior.AllowGet);
    }

In the Controller if I put a breakpoint I see in the String term what I wrote to the textbox and the result contains all of the found elements.
When I print the 'data' in the 'Success' section, the message is:

[object Object] [object Object] [object Object] [object Object]

A: You can create simple HTML5 Autocomplete in Boostrap like this
HTML
<label class="label">Input with autocomlete</label>
       <label class="input">
                        <input type="text" list="list">
                        <datalist id="list">
                            <option value="Alexandra"></option>
                            <option value="Alice"></option>
                            <option value="Anastasia"></option>
                            <option value="Avelina"></option>
                        </datalist>
        </label>


text:
Q: Google Analytics -- Question on how it affects search results on Google Simple true or false:  Having Google Analytics installed on your page will automatically cause that page to be indexed by Google and appear in their search results.

A: There is a new awesome site for answer this kind of questions: WebApps @ StackExchange. I think you will get better answers there.


text:
Q: SQL Server 2008 Copy Database Wizard: Fail I am trying to use the SQL Server 2008 Copy Database Wizard to copy a SQL Server 2008 database.  I am using the SQL Management Object method.  The database contains a full-text index.  I have set the 'Server - Properties - Advanced - Full-Text Upgrade Option' to Reset.  However, the copy fails with the following error:
ERROR :
errorCode=-1073548784 description=Executing the query "/*
'==============================================..."
failed with the following error: "Cannot use a CONTAINS or
FREETEXT predicate on table or indexed view 'Product' because
it is not full-text indexed."

Any ideas on why this is happening and how I can copy my database would be greatly appreciated.

A: although I haven't resolved the issue I was having earlier, I have tried and succeeded with an acceptable alternative approach - copy only backup and restore.
Here are some useful references to read:
Copying Databases with Backup and Restore:
http://msdn.microsoft.com/en-us/library/ms190436.aspx
Copy Only Backup for SQL Server 2005 and SQL Server 2008:
http://www.mssqltips.com/tip.asp?tip=1772
Thanks to all those that stopped by to view and edit / re-format my question.
Kind Regards
Walter

A: I ran into the same issue as well.  I was never able to use the Copy Database Wizard to copy the database.
I even removed and then re-added the full-text indexes and catalog.
Performing a backup, and then a restore to a new database (don't forget to manually change the filenames that SQL will restore to, or it will try to overwrite the existing database.) worked just fine.
In my case, I didn't even want the full-text catalog, so I didn't care if it didn't come across.

A: I had the same issue with the Copy Database wizard. I was unable to do a backup to my local machine since the server was on a hosted environment and did not have access. This doesn't set the Identity for tables though. My solution was:

*

*Create the a new local database.

*Use the Import wizard, right click on database. Tasks->Import Data

*Use the Sql Server Native Client and set the Source and Destination. This will import the tables / data but will not import the indexes / constraints.

*Use the scripts below to get the indexes / constraints and foreign key from your source and run them on your local database. https://www.mssqltips.com/sqlservertip/3443/script-all-primary-keys-unique-constraints-and-foreign-keys-in-a-sql-server-database-using-tsql/


text:
Q: Use AWS Java SDK inside EMR Job I have a Scalding job packed in fatjar and running on EMR Hadoop cluster. Recently I added new feature requiring DynamoDB connection inside map. But as soon as mapper reaches DynamoDB initialization it throws following exception:
Error in configuring object
    at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:112)
    at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:78)
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:136)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:450)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:344)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:172)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:166)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.ReflectionUtils.setJobConf(ReflectionUtils.java:109)
    ... 9 more
Caused by: cascading.flow.FlowException: internal error during mapper configuration
    at cascading.flow.hadoop.FlowMapper.configure(FlowMapper.java:102)
    ... 14 more
Caused by: com.esotericsoftware.kryo.KryoException: Unable to find class: com.amazonaws.http.conn.$Proxy7
Serialization trace:
connManager (com.amazonaws.http.impl.client.SdkHttpClient)
httpClient (com.amazonaws.http.AmazonHttpClient)
client (awscala.dynamodbv2.DynamoDBClient)
client (me.chuwy.enrich.hadoop.DuplicateStorage$DynamoDbStorage)
duplicateStorage (me.chuwy.enrich.hadoop.ShredJob)
$outer (me.chuwy.enrich.hadoop.ShredJob$$anonfun$11)
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readName(DefaultClassResolver.java:138)
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:115)
    at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:610)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:599)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:648)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:605)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:648)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:605)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:648)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:605)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:729)
    at com.twitter.chill.SomeSerializer.read(SomeSerializer.scala:25)
    at com.twitter.chill.SomeSerializer.read(SomeSerializer.scala:19)
    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:648)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:605)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:648)
    at com.esotericsoftware.kryo.serializers.FieldSerializer$ObjectField.read(FieldSerializer.java:605)
    at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:221)
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:729)
    at com.twitter.chill.SomeSerializer.read(SomeSerializer.scala:25)
    at com.twitter.chill.SomeSerializer.read(SomeSerializer.scala:19)
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:729)
    at com.twitter.chill.SerDeState.readClassAndObject(SerDeState.java:61)
    at com.twitter.chill.KryoPool.fromBytes(KryoPool.java:94)
    at com.twitter.chill.Externalizer.fromBytes(Externalizer.scala:145)
    at com.twitter.chill.Externalizer.maybeReadJavaKryo(Externalizer.scala:158)
    at com.twitter.chill.Externalizer.readExternal(Externalizer.scala:148)
    at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1839)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1997)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1921)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1997)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1921)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1997)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1921)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at java.util.HashMap.readObject(HashMap.java:1180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1897)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1997)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1921)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1997)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1921)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at cascading.flow.hadoop.util.JavaObjectSerializer.deserialize(JavaObjectSerializer.java:101)
    at cascading.flow.hadoop.util.HadoopUtil.deserializeBase64(HadoopUtil.java:312)
    at cascading.flow.hadoop.util.HadoopUtil.deserializeBase64(HadoopUtil.java:293)
    at cascading.flow.hadoop.FlowMapper.configure(FlowMapper.java:81)
    ... 14 more
Caused by: java.lang.ClassNotFoundException: com.amazonaws.http.conn.$Proxy7
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass

I think that problem may be in that EMR AMI is shipping with its own jars in /usr/share/aws/aws-java-sdk/ and they conflict with libs that I include in fat jar, I tried to delete them, but then other EMR steps are failing.

A: Problem is in Scalding serialization, not in binary incompatibility as I suspected initially. DynamodDB client is not serializable entity, because it contains things like handlers, thread pools, etc. Therefore it should be initialized straight inside job and declared as lazy val.


text:
Q: How do I fetch all headers in Javascript? Quick and dirty experiment:
function fetchHead(url) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.getAllResponseHeaders())
        }
    }

    request.open('HEAD', url, true)
    request.send(null)
}

It only shows three headers: ["cache-control", "content-type", "expires"]. But there are a dozen headers in the actual response, as seen in the Network Inspector in the Development Toolbar.
Is there any (other) way to get all headers in Javascript? Is it possible (at all) to read a custom response header from within Javascript?
PS - The response does have Access-Control-Allow-Origin: *. Somehow the browsers does seem to strip out a lot of the headers though.

A: For security reasons browsers restrict access to most HTTP Headers calls via XMLHttpRequest. Best reference for this is probably the Fetch standard.
These restricted list can be expanded by the server returning a Access-Control-Expose-Headers header telling the browser which headers are safe for JavaScript to have access to.

A: I can't reproduce this. MDN says that all headers will be returned in lowercase.


text:
Q: Is the use of "flashing about" correct in this sentence? Is the use of "flashing about" correct in this sentence?

He hanged the animal's heads on the walls, flashing about the heads to his hunter friends in the luxurious parties he held.

A: Possibly more common and acceptable at some previous point in time--the language appears to be dated. It would not be written that way now. And the word "flashing" (as it is used in this context) is typically only used now for things that are suddenly shown or revealed, like a cop's badge or a coworker's baby pictures.


text:
Q: Error while storing looped checkbox's value - Android I have a program that will shows AlertDialog with some looped checkbox (checkboxes values come from database), then user will choose the checkbox, after that I want to store all the chosen checkbox to a variable, then store the value to database.
So the flow is :
Read value From Database -> Print all the value (loop) to Alert Dialog checkbox -> User check the checkbox then click OK -> the value of chosen checkbox will be stored and pass to DBHelper
I Have tried to code it, it runs good till when I want to store the value of the chosen checkbox, but I get error and the error is java.lang.NullPointerException..
Here I store the selected value to a string temp[i] (See the builder.setPositiveButton), then outside the loop, I pass the temp[i] to the groupToBePosted
This is my Code, wish you could help me to store the value and pass it to the database,,
Thank you..
    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {

    case R.id.bBrowseSelectGroup:
        myDb.open();
        final String[] groupName = myDb.fetchGroupName(username);
        myDb.close();
        final boolean[] itemsChecked = new boolean[groupName.length];
        AlertDialog.Builder builder = new AlertDialog.Builder(
                CreateAnnouncementActivity.this);

        builder.setTitle("Choose Your Group : ");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                myDb.open();
                final String[] groupId = myDb.fetchGroupId(username);
                myDb.close();
                String selectedGroup="Post To : ";
                String temp[] = null;
                for (int i = 0; i < groupName.length; i++) {
                if (itemsChecked[i]) {
                    temp[i]=groupId[i];
                    selectedGroup=selectedGroup+groupName[i]+", ";
                    itemsChecked[i]=false;
                }
            }

             PostTo.setText(selectedGroup); //Set the TextView Value

             for(int i=0;i<temp.length;i++){
                 groupToBePosted[i]=temp[i];
             }

            }
        });
        builder.setMultiChoiceItems(groupName, new boolean[] { false,
                false, false },
                new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which,
                            boolean isChecked) {
                        itemsChecked[which] = isChecked;
                    }
                });
        builder.show();

        myDb.close();
        break;

    case R.id.bDoPostAnnouncement:

        //Get all the data stored and pass to the database
        for(int i=0; i<groupToBePosted.length;i++){
            myDb.open();
            myDb.insertNewAnnouncement(title, detail, time, groupToBePosted[i], username);
            myDb.close();
        }

        break;
    }
}

And here is the logcat

A: Use a LinkedList:
LinkedList<String> temp =  new LinkedList<String>();

Then replace
temp[i]=groupId[i];

by
temp.add(groupId[i]);

Then later iterate over the list instead the temp array. Change:
for(int i=0;i<temp.length;i++){
    groupToBePosted[i]=temp[i];
}

to
int i=0;
for(String t:temp){
    groupToBePosted[i]=t;
    i++;
}


text:
Q: Output 2 different queries to a single resultset My db schema is something like this -
Table - 1
-----------------------------------------------------------------------
|Src_Country_Code|Total_Src_Amount|Dest_Country_Code|Total_Dest_Amount|
-----------------------------------------------------------------------

I want the output in the following form -
Country_Code||SrcAmount||Dest_Amount

Country_Code is present in both Src_Country_Code and Dest_Country_Code : eg-
Sample records
abc|50|efg|100
efg|400|abc|200

The output If I select the country abc should be like-
abc|50|200

Also, if the second record doesn't exist, the output should be -
abc|50|0

I tried a lot of variations but nothing seems to work. Help would be appreciated.

A: Something like this
SELECT nvl(src.Src_Country_Code, dest.Dest_Country_Code) Country_Code,
       nvl(Total_Src_Amount,0) Total_Src_Amount,
       nvl(Total_Dest_Amount, 0) Total_Dest_Amount
FROM
  (SELECT Src_Country_Code,
          sum(Total_Src_Amount) Total_Src_Amount
   FROM table1
   GROUP BY Src_Country_Code) src
FULL JOIN src.Src_Country_Code = dest.dest_Country_Code
  (SELECT Dest_Country_Code,sum(Total_dest_Amount) Total_dest_Amount
   FROM table1
   GROUP BY Dest_Country_Code) dest

A: You can use Join like below.
SELECT T1.Src_Country_Code,T1.Total_Src_Amount,T2.Total_Dest_Amount
FROM Table1 T1
LEFT JOIN Table1 T2 ON T1.Src_Country_Code = T2.Dest_Country_Code

Working Fiddle - http://sqlfiddle.com/#!9/34723/1


text:
Q: Angular Animation Performance State/Transition vs Query I am currently working with angular animations. Therefore I figured out two possible methods to attach animations to components. In the following I am describing them as State/Transition-Animations and Query-Animations.
In this question I mainly want to know if there is a performance difference in going for one or the other way!?

1. State/Transition-Animations
.html
<div [@animation_foo]/>

.ts
trigger('animation_foo', [
    state('true', style({...}),
    state('false', style({...})
    transition('true => false', animate(...)
]

2. Query-Animations
.html
<div [@animation_foo]>
    <div class="bar"/>
</div>

.ts
trigger('animation_foo', [
    query('.bar', style({...}), animate('10ms', style({...}))
]

Further thoughts:

*

*My main concern with point 2. Query is that:

*

*If you do not have one query but multiple, which are combined via group(...) and the css selector is going to find elements on a deeper level ('.foo > :nth-child(n+3) .bar') you have to iterate over a very big part of the DOM-Tree.

*The stylings and animation applied to the elements happens after finding the element and before the animation - every time - because I expect, that it cannot be pre-compiled by the compiler?

*

*Environment/Target platform: I know it's might not related to a casual Web-Application, but I try to think in big enterprise applications with multiple router, nested components and lots of ngIf's ngFors, so that I personally can imagine that querying all that could be some effort.

*Browser: I know that browser differently behave differently. Personally I am interested only in Chrome for the moment - But for the sake of community a general answer would be awesome.
If you have any further information that are important to note, it would be nice to share (bugs, ...)

A: Angular uses the web animations api, so it's not changing style properties through JavaScript and is therefore quite performant. You can check the performance of different animation frameworks (javascript-based) vs CSS with the HTML 5 Animation Speed Test.
The performance in different browsers is therefore dependent on the browser compatibility of the web animations api (unfortunately the section is not being maintained yet). But, according to the comment here, it is not fully supported yet across common browsers and is being polyfilled for Edge/Safari.


text:
Q: Div Bind issues I have a document where i have disabled the scroll on page by using
$('body').bind('touchmove', false);

Now i'm loading a page dynamically into a div after click of a button...
$('#myContentPage').load('details.html #myCOntentPage');

I want to unbind 'touchmove' only from the div #myContentPage after load is finished.
I tried
$('#myContentPage').bind('touchmove', true); after page load , but it does not seem to work.
HTML Structure before load

HTML Structure after load

A: The problem is that you can't detach the touchmove event callback form '#myContentPage' because it was attached to his parent- , Do the best way to fix it is to attach a new handler to #myContentPage that will stop Propagation to  which cancel the event.
$('#myContentPage').load('details.html #myCOntentPage', function() {
    $('#myContentPage').bind('touchmove', function(event){
        event.stopPropagation() ;
    });
});

If that doesn't help (from some unknown reason), try this:
$('#myContentPage').load('details.html #myCOntentPage', function() {
    $('body').unbind('touchmove');
    $('body').on('touchmove', ':not(#myContentPage)', function(){
        return false;
    });
});

A:  $('#myContentPage').off('touchmove'); // if you bind event using `on()`

OR
 $('#myContentPage').unbind('touchmove');

so,
$('#myContentPage').load('details.html #myCOntentPage', function() {
    $('#myContentPage').off('touchmove');
});

A: After yor new page is loaded, you can use this  to unbind your previously attached event
$('#myContentPage').unbind('touchmove');

A: Try:
$('body').bind('touchmove', function(ev){
  if ( ev.target.id != "myContentPage"){
    return false;
  }
});

Instead of:
     $('body').bind('touchmove', false);


text:
Q: Sorting Custom Taxonomy in ASC/DESC order? Before anyone say that I didn't try let me say I tried a lot to achieve this. I even achieved but  when I add the following code to functions.php  the sorting works but the filters on left side doesn't work.
function orderby_tax_clauses( $clauses, $wp_query ) {
global $wpdb;
$taxonomies = get_taxonomies();
foreach ($taxonomies as $taxonomy) {
if ( isset( $wp_query->query['orderby'] ) && $taxonomy == $wp_query->query['orderby'] )     {
$clauses['join'] .=<<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb-    >term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
            $clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)";
            $clauses['groupby'] = "object_id";
        $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
        $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
}
}
return $clauses;
}

add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );

This particular code
add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );

is creating the problem I think because when I remove this line it filters properly. I think its creating some query conflict and giving " No results found" when I use both filter and soering option. When I use only orting  it works and when I use only filter it works. How to make both work together ?
This is the site:
http://tjdesigners.info/mooctracks/searchresults/?
Please help me out!
Thank you so much!
Tirtha

A: If you really need to sort by taxonomy term, I think you have a bad design of the data structure in your application. Think about it.
A taxonomy is a way to group things, lets say posts. A taxonomy is a group of "terms" and the posts are grouped by the shared "terms" between them. From my point of view, if the terms are used as they should be, sorting by terms is not useful at all and have no sense.
Lets go with an example in your page: You can filter by "Codecademy" platform, so you get the group of items assigned to "Codecademy". Then you click in the "platform" table header to sort by "Codecademy", where the logic is?. It is like having a group of "dentists" that you want to sort by "dentists"; you may want to sort by something that describe each dentist, like name or cost, but not by "dentists". Do you get my point? If you need to sort by some posts characteristic, you should use customs post meta fields or core post fields, not taxonomies.
Another example, if you want to sort alphabetically by the "platform" taxonomy, what you really want is sort the terms of a taxonomy alphabetically and the show the posts for each term, this is not sorting the posts, it is sorting the terms.
Anyway, if you really want to sort by taxonomy term you can do it, not by a standard way provided by Wordpress but by a custom way like your workaround in the custom SQL you are using or the example of this article.


text:
Q: How to auto-generate a group of matrices? I have to make a bunch of matrices and since it is way to much I would to like to automatize the process.
I need matrices with three lines:
U -fixed- (each matrix should have one at 0.5 step)
n 0 to 1 in 0.001
m 0 to n (for each of the 'n' values)

I would appreciate any kind of help, or at least a direction of what to do.


text:
Q: Slow Skscene transition I have two scenes: Home and Play. The transition to play scene is really slow compared to the transition to home scene. I think this is because there's more happing in my play scene. Is there any way I can preload play scene ? Or make the transition more seamless?
I'm interested in the answer in this forum Preload a Scene to prevent lag?
but I have no idea where to begin. Where do I place part A and B of the answer
Here is what I'm using
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch = touches
    let location = touch.first!.locationInNode(self)
    let node = self.nodeAtPoint(location)

    if (node.name == "Balloon") {

        let sceneAction = SKAction.runBlock({
            let secondScene = Scene2(size: self.size)
            let transition = SKTransition.fadeWithDuration(1)
            secondScene.scaleMode = SKSceneScaleMode.AspectFill
            self.scene!.view?.presentScene(secondScene, transition: transition)
        })
            PlayButton.runAction(SKAction.sequence([sound,SKAction.animateWithTextures(array, timePerFrame: 0.1),sceneAction,SKAction.waitForDuration(1)]))

    }

Any other solution is fine.
Thanks

A: I do this and works:
in didView of HomeScene put preloadGameScene()
And always in home scene:
fileprivate var nextScene: SKScene?

func preloadGameScene () {
    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue, {
        self.nextScene = GameScene(fileNamed:"yoursksfilename")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            print("SCENE LOADED")
            let loading = self.childNodeWithName("Loading") as? SKLabelNode
            self.playButton?.hidden = false
            self.playButton?.alpha = 0
            //loading?.hidden = true
            self.playButton?.runAction(SKAction.fadeAlphaTo(1.0, duration: 0.4))
            loading!.runAction(SKAction.fadeAlphaTo(0.0, duration: 0.4))
        })

    })
}

goToGameScene() is called by a button personal SKButton class:
    func goToGameScene () {
        guard let nextScene = nextScene else {return}
        let transition = SKTransition.crossFadeWithDuration(0.5)
        nextScene.scaleMode = .AspectFill
        scene!.view?.presentScene(nextScene, transition: transition)
    }

UPDATE SWIFT 3
fileprivate var nextScene: SKScene?

func preloadGameScene () {
        let qualityOfServiceClass = DispatchQoS.QoSClass.background
        let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass)
        backgroundQueue.async(execute: {
            self.nextScene = GameScene(fileNamed:"yoursksfilename")
            DispatchQueue.main.async(execute: { () -> Void in
                print("SCENE LOADED")
                let loading = self.childNode(withName: "Loading") as? SKLabelNode
                self.playButton?.isHidden = false
                self.playButton?.alpha = 0
                //loading?.hidden = true
                self.playButton?.run(SKAction.fadeAlpha(to: 1.0, duration: 0.4))
                loading?.run(SKAction.fadeAlpha(to: 0.0, duration: 0.4))
            })

        })
    }


text:
Q: ServiceStack automatic dispose I'm new to ServiceStack and I was trying to use it. I have a question to do: from the documentation I read that "ServiceStack only calls Dispose() on dependencies resolved within ServiceStack Requests, i.e. it tracks any disposables resolved from Funq and disposes of them at the end of a ServiceStack request.". What does it mean? Below you can see my example code: in this case, I was trying to dispose of JsonServiceClient using lazy property in the base class, but Dispose() not being invoked. Could you explain to me how does it work?
class Program
{
    static void Main(string[] args)
    {
        new AppHost().Init();
        var test = HostContext.AppHost.Container.TryResolve<Worker>();
        test.DoWork();
    }
}

public abstract class BaseWorker : IDisposable
{
    private JsonServiceClient client;
    public JsonServiceClient Client => client ??  (client = new JsonServiceClient());

    public virtual void Dispose()
    {
        client?.Dispose();
    }
}

public class Worker : BaseWorker
{
    public void DoWork()
    {
        var res = Client.ToPostUrl();
    }
}

public class AppHost : AppHostBase
{

    public AppHost() : base("Services", typeof(AppHost).Assembly)
    { }

    public override void Configure(Container container)
    {
        container.Register<Worker>(c => new Worker()).ReusedWithin(ReuseScope.Request);
    }
}

public class StoreGist : IReturn<StoreGistResponse> { }

public class StoreGistResponse
{
    public string Date { get; set; }
}

Thanks in advance.

A: First of all you don't need to dispose JsonServiceClient as it doesn't retain any resources and its Dispose() is a NOOP.
I'd also recommend against using Request Scoped dependencies, basically if your dependencies only use ThreadSafe dependencies register it as a singleton (the default):
container.AddSingleton(c => new Worker()); //Equivalent to:
container.Register(c => new Worker());

Otherwise register it as a transient dependency, e.g:
container.AddTransient(c => new Worker()); //Equivalent to:
container.Register(c => new Worker()).ReusedWithin(ReuseScope.None);

"ServiceStack only calls Dispose() on dependencies resolved within ServiceStack Requests, i.e. it tracks any disposables resolved from Funq and disposes of them at the end of a ServiceStack request.". What does it mean?

It just means if ServiceStack is resolving and injecting your dependencies, e.g. in your ServiceStack Services, then ServiceStack will also dispose them. But if you're resolving dependencies from the IOC yourself you would need to explicitly dispose of them, typically with a using, e.g:
using var test = HostContext.AppHost.Container.TryResolve<Worker>();
test.DoWork();


text:
Q: Detect when home button is pressed In my app, I need to hide a UIImageView when the user presses the home button. I tried using pressesBegan(_:with:) but is was never calling. Does anyone know how to detect when the home Button is pressed?
@IBOutlet weak var shouldHideView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

func hide(){
    self.shouldHideView.isHidden = true
}

override fun pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?){
    self.hide()
}

A: As a rule, the tool you want for this is UIApplicationDelegate.applicationWillResignActive(_:). This is called a bit more frequently than when the home button is pressed, but generally it's what you actually mean. (There is no call made only when the home button is pressed.)

A: As far as I know, the home button press event is not available on the iOS SDK. You could use any of the following UIApplicationDelegate methods to observe when the application goes to the background:
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Tells the delegate that the app is now in the background.
}


text:
Q: How to open and close virtual keyboard using Java I tried all answers from here:
open the Windows virtual keyboard in a Java program
I executed Runtime.getRuntime().exec("cmd /c osk"); and I cant close it as advised and I need to close it after some processes.
I tried:
import java.io.IOException;

public class ShowVirtualKeyboard{

    public static void main(String argv[]) throws IOException {
    String sysroot = System.getenv("SystemRoot");
    Process proc = Runtime.getRuntime().exec(sysroot + "/system32/osk.exe");
}
}

and I got the error
Cannot run program "C://Windows/system32/osk.exe": CreateProcess error=740, The requested operation requires elevation

A: I think is a little bit late but I managed to open and close the virtual keyboard (TabTip.exe) using cmd as you do and JNA (Java Native Access) library:
To open the keyboard:
// Java

String command = "cmd /c \"C:\\Program Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe\"";
Process = Runtime.getRuntime().exec(command);
process.waitFor();
process.destroy();

// Kotlin

val command = "cmd /c \"C:\\Program Files\\Common Files\\Microsoft Shared\\ink\\TabTip.exe\""
val process = Runtime.getRuntime().exec(command)
process.waitFor()
process.destroy()

To close it:
//Java

String KEYBOARD_CLASS_NAME = "IPTIP_Main_Window";
int WM_SYS_COMMAND = 0x0112;
WinDef.WPARAM SC_CLOSE = WinDef.WPARAM(0xF060);
WinDef.HWND handle = User32.INSTANCE.FindWindow(KEYBOARD_CLASS_NAME, "");
if (handle != null) {
    User32.INSTANCE.SendMessage(handle, WM_SYS_COMMAND, SC_CLOSE, WinDef.LPARAM(0));
}

//Kotlin

val KEYBOARD_CLASS_NAME = "IPTIP_Main_Window"
val WM_SYS_COMMAND = 0x0112
val SC_CLOSE = WinDef.WPARAM(0xF060)
val handle = User32.INSTANCE.FindWindow(KEYBOARD_CLASS_NAME, "")
if (handle != null) {
    User32.INSTANCE.SendMessage(handle, WM_SYS_COMMAND, SC_CLOSE, WinDef.LPARAM(0))
}

Closing the process or killing it from cmd was not working for me so I had to do it in the native way. I hope this works for you too.


text:
Q: Use the date time in the timezone of the record owner on custom object I have a custom object My_Object__c.
I want to build a Formula Checkbox field where the checkbox is checked if the CreatedDate local time in the Timezone of the Owner was more than 6 pm.
E.g. we have a user In California and a user in London.
I want the My_Checkbox__c to be checked if it was > 6 pm in California for Cali user, and > 6 pm for London user on their corresponding records.
Is that possible?


text:
Q: how to Project all columns in relational algebra do we need project sign (pi) when we dont want to filter any columns in relational algebra?
or simply if we want to get every column to be returned?
and i guess same goes with the selction operator i.e if we dont want to filter any rows.

A: You use projection per columns when you want a value like another value but with only the given columns. If you don't, don't. (Although projecting on all columns outputs its input relation.)
You use selection/restriction per a condition when you want a value like another value but with only the tuples satisfying the condition. If you don't, don't. (Although selection/restriction on an always-true condition outputs its input relation.)
Relation operators are like any other operators. You use them in an expression to build the value you want out of given values.
(One of the many ways that the SQL database programming language is poorly designed is that to algebraically select/restrict (WHERE) and/or join (JOIN) you must also project (SELECT).)


text:
Q: Hover image, haven't touch the image but it works, how to remove extra hidden image? I've tried many ways for almost 2 days but seems like I hit the wall. Have a look at the picture. I hover a little bit on the corner, but it's working although I haven't touch the images yet. I want to remove extra image. (Clearly, I pressed ctrl+a on the website to see the image to make sure there are no extras because I want to make hover).

Here is my code for body

and for my css..
#social {
    margin-top:20px;
}

#social ul li {
    float:left;
    list-style:none;
    margin-top:20px;
}

#social ul li a {
    margin-right:10px;
}

#social ul li a img {
    width:40px;
    height:40px;
    filter:grayscale(100%);
    -webkit-filter: grayscale(100%); /* For Webkit browsers */
    filter: gray; /* For IE 6 - 9 */
    -webkit-transition: all .6s ease; /* Fade to color for Chrome and Safari */
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
}

#social ul li a:hover img {
    filter: grayscale(0%);
    -webkit-filter: grayscale(0%);
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

So far, I thought this problem maybe rely on padding and margin and I tried to make padding 0 and margin 0, but it's still not working. Or the problem with .png format? I'm so confused, really!! Does any of you have solution? Thanks.
Here is my JSfiddle so that you guys are able to understand : http://jsfiddle.net/MkNm2/

A: Even if it is a png you are hovering on the transparent part and so this happens. There is no solution to avoid this up to my knowledge.


text:
Q: How can I remove height in FlexBox children when the direction is row? Background
At first, I wanted to narrow the space between two lines of text through line-height in the FlexBox, but line-height can't work on the flex-direction:row, it will always fill the height itself, unless I change the direction to column

Question
How can I remove filling the heights in the flexbox children when the direction is row like as column, or some articles explain the different strategies for row and column filling the heights
I had tried to use align-item: center, but it can't work, you can see my snippet, it still has the heights.

.container {
  width : 200px;
  height : 200px;
  display : inline-flex;
  flex-wrap : wrap;
}

.container_row {
  flex-direction : row;
}
.box {
  width : 100%;
  background-color : red;
}

.container_column {
  flex-direction : column;
}

.container_align_center {
  align-items : center;
}
}

row

Box1

Box2

Box3

row with align center

Box1

Box2

Box3

 column

Box1

Box2

Box3

A: An initial setting in a flex container is align-content: stretch.
That means that free space in the container – in the cross-axis – will be distributed evenly among flex items.
As a result, in a row-direction container, items will expand vertically consuming all available height.
You can override this default setting with flex-start, flex-end, center or other possible values.

.container {
  width: 200px;
  height: 200px;
  display: inline-flex;
  flex-wrap: wrap;
}

.container_row {
  flex-direction: row;
  align-content: flex-start; /* NEW */
}

.box {
  width: 100%;
  background-color: red;
}

.container_column {
  flex-direction: column;
}

Box1

Box2

Box3

Box1

Box2

Box3


text:
Q: wxpython menu bar not displaying I am trying to write a timetabling program using wxpython for gui and am using the getting started tutorial on the wxpython wiki to get up to speed with wxpython but when I try to add a menu bar to wxFrame, the menu bar does not show. Any ideas why this is happening?
I am using ubuntu 10.10 and python 2.7. The code is given below:
#! /usr/bin/env python2.7
import wx, os

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(200,100))
        self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        self.CreateStatusBar() # A Statusbar in the bottom of the window

        # Creating the menubar.
        menuBar = wx.MenuBar()

         # Setting up the menu.
        filemenu= wx.Menu()

        # wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets.
        menuAbout = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
        menuExit = filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")

        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.

        # Set events.
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)

        self.Show(True)

    def OnAbout(self,e):

        # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
        dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK)
        dlg.ShowModal() # Show it
        dlg.Destroy() # finally destroy it when finished.

    def OnExit(self,e):
        self.Close(True)  # Close the frame.
        '''
        # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
        filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
        filemenu.AppendSeparator()
        filemenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")

        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
        self.Show(True)
        '''

app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()

A: I had the same error and I solved it no using standard IDs provided by wxWidgets.
Try with this:
# wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets.
menuAbout = filemenu.Append(102, "&About"," Information about this program")
menuExit = filemenu.Append(103,"E&xit"," Terminate the program")

A: Someone had a similar issue on the wxPython list. I think the menu was appearing in the "taskbar" or something because the OS had been configured for that, kind of like a Mac. If you're using a custom theme, try a standard one instead. You can also try running the wxPython demo to see if it has the same issue.

A: add this to ~/.bashrc:
export UBUNTU_MENUPROXY=0
from https://bugs.launchpad.net/ubuntu/+source/wxwidgets2.8/+bug/682478

A: Somehow it is not a wxpython problem. It is a feature. It is supposed to behavior in this way.

Apple and Microsoft specify slightly different layouts for menubars. (Apple specification. Microsoft specification.) WxWidgets will automatically move certain menus on a Macintosh, to ease the task of writing cross-platform applications with native look and feel on both MS-Windows and Apple Macintosh;

The About/Exit menu item would locate at the dock menu.

Check: https://wiki.wxpython.org/Optimizing%20for%20Mac%20OS%20X

A: I had the same problem where i could not see the menu bar because it as in the "taskbar" way up there. So you can just add this to your python script if you do not want to permanantly change your .bashrc file
import os
os.environ["UBUNTU_MENUPROXY"]="0"


text:
Q: Malloc vs new -- different padding I'm reviewing someone else's C++ code for our project that uses MPI for high-performance computing (10^5 - 10^6 cores). The code is intended to allow for communications between (potentially) different machines on different architectures. He's written a comment that says something along the lines of:

We'd normally use new and delete, but here I'm using malloc and free. This is necessary because some compilers will pad the data differently when new is used, leading to errors in transferring data between different platforms. This doesn't happen with malloc.

This does not fit with anything I know from standard new vs malloc questions.
What is the difference between new/delete and malloc/free? hints at the idea that the compiler could calculate the size of an object differently (but then why does that differ from using sizeof?).
malloc & placement new vs. new is a fairly popular question but only talks about new using constructors where malloc doesn't, which isn't relevant to this.
how does malloc understand alignment? says that memory is guaranteed to be properly aligned with either new or malloc which is what I'd previously thought.
My guess is that he's misdiagnosed his own bug some time in the past and deduced that new and malloc give different amounts of padding, which I think probably isn't true. But I can't find the answer with Google or in any previous question.
Help me, StackOverflow, you're my only hope!

A: Your colleague may have had new[]/delete[]'s magic cookie in mind (this is the information the implementation uses when deleting an array). However, this would not have been a problem if the allocation beginning at the address returned by new[] were used (as opposed to the allocator's).
Packing seems more probable. Variations in ABIs could (for example) result in a different number of trailing bytes added at the end a structure (this is influenced by alignment, also consider arrays). With malloc, the position of a structure could be specified and thus more easily portable to a foreign ABI. These variations are normally prevented by specifying alignment and packing of transfer structures.

A: I think you are right. Padding is done by the compiler not new or malloc. Padding considerations would apply even if you declared an array or struct without using new or malloc at all. In any case while I can see how different implementations of new and malloc could cause problems when porting code between platforms, I completely fail to see how they could cause problems transferring data between platforms.

A: The layout of an object can't depend on whether it was allocated using malloc or new. They both return the same kind of pointer, and when you pass this pointer to other functions they won't know how the object was allocated. sizeof *ptr is just dependent on the declaration of ptr, not how it was assigned.

A: IIRC there's one picky point. malloc is guaranteed to return an address aligned for any standard type. ::operator new(n) is only guaranteed to return an address aligned for any standard type no larger than n, and if T isn't a character type then new T[n] is only required to return an address aligned for T.
But this is only relevant when you're playing implementation-specific tricks like using the bottom few bits of a pointer to store flags, or otherwise relying on the address to have more alignment than it strictly needs.
It doesn't affect padding within the object, which necessarily has exactly the same layout regardless of how you allocated the memory it occupies. So it's hard to see how the difference could result in errors transferring data.
Is there any sign what the author of that comment thinks about objects on the stack or in globals, whether in his opinion they're "padded like malloc" or "padded like new"? That might give clues to where the idea came from.
Maybe he's confused, but maybe the code he's talking about is more than a straight difference between malloc(sizeof(Foo) * n) vs new Foo[n]. Maybe it's more like:
malloc((sizeof(int) + sizeof(char)) * n);

vs.
struct Foo { int a; char b; }
new Foo[n];

That is, maybe he's saying "I use malloc", but means "I manually pack the data into unaligned locations instead of using a struct". Actually malloc is not needed in order to manually pack the struct, but failing to realize that is a lesser degree of confusion. It is necessary to define the data layout sent over the wire. Different implementations will pad the data differently when the struct is used.

A: This is my wild guess of where this thing is coming from. As you mentioned, problem is with data transmission over MPI.
Personally, for my complicated data structures that I want to send/receive over MPI, I always implement serialization/deserialization methods that pack/unpack the whole thing into/from an array of chars. Now, due to padding we know that that size of the structure could be larger than the size of its members and thus one also needs to calculate the unpadded size of the data structure so that we know how many bytes are being sent/received.
For instance if you want to send/receive std::vector<Foo> A over MPI with the said technique, it is wrong to assume the size of resulting array of chars is A.size()*sizeof(Foo) in general. In other words, each class that implements serialize/deserialize methods, should also implement a method that reports the size of the array (or better yet store the array in a container). This might become the reason behind a bug. One way or another, however, that has nothing to do with new vs malloc as pointed out in this thread.

A: When I want to control the layout of my plain old data structure, with MS Visual compilers I use #pragma pack(1). I suppose such a precompiler directive is supported for most compilers, like for example gcc.
This has the consequence of aligning all fields of the structures one behind the other, without empty spaces.
If the platform on the other end does the same ( i.e. compiled its data exchange structure with a padding of 1), then the data retrieved on both side justs fits well.
Thus I have never had to to play with malloc in C++.
At worst I would have considered overloading the new operator so as it performs some tricky things, rather than using malloc directly in C++.

A: In c++: newkeyword is used to allocate some particular bytes of memory with respect to some data-structure. For example, you have defined some class or structure and you want to allocate memory for its object.
myclass *my = new myclass();

or
int *i = new int(2);

But in all cases you need the defined datatype (class, struct, union, int, char etc...) and only that bytes of memory will be allocated which is required for its object/variable. (ie; multiples of that datatype).
But in case of malloc() method, you can allocate any bytes of memory and you don't need to specify the data type at all times. Here you can observe it in few possibilities of malloc():
void *v = malloc(23);

or
void *x = malloc(sizeof(int) * 23);

or
char *c = (char*)malloc(sizeof(char)*35);

A: malloc is a type of function
and new is a type of data type in c++
in c++, if we use malloc than we must and should use typecast otherwise compiler give you error
and if we use new data type for allocation of memory than we no need to typecast


text:
Q: browserify chokes when requiring openpgp When I run browserify on a file containing require ('openpgp'), the error message says it cannot find ./config module.
Test file:
var openpgp = require ('openpgp');

Error message:
Error: Cannot find module './config' from '/usr/lib/node_modules/openpgp/dist'
    at /usr/lib/node_modules/browserify/node_modules/resolve/lib/async.js:55:21
    at load (/usr/lib/node_modules/browserify/node_modules/resolve/lib/async.js:69:43)
    at onex (/usr/lib/node_modules/browserify/node_modules/resolve/lib/async.js:92:31)
    at /usr/lib/node_modules/browserify/node_modules/resolve/lib/async.js:22:47
    at FSReqWrap.oncomplete (fs.js:82:15)

Browserify works fine when requiring other modules, just not openpgp.  The version of openpgp is the latest (2.2.2).
Is this a problem with the openpgp build?  Or is this a browserify problem?


text:
Q: customize cursor in oracle plsql How can I customize implict cursor to scan remote query (dblink) with similar name and identical structure (with similar filed name)?
I try this procedure code but I have this errors:

*

*line: 9, column: 38, error: PL/SQL: ORA-00942: tabella o vista
inesistente

*line: 15, column: 41, error: PLS-00364: uso della variabile di indice
loop 'C1' non valido

create table t1@DBLINK (
    id number,
    f1 varchar2(100),
    f2 varchar2(100),
    f3 varchar2(100),
    f4 varchar2(100)
);

insert into t1@DBLINK values (1,'t1 r1 f1','t1 r1 f2','t1 r1 f3','t1 r1 f4');
insert into t1@DBLINK values (2,'t1 r2 f1','t1 r2 f2','t1 r2 f3','t1 r2 f4');

create table t2@DBLINK (
    id number,
    f1 varchar2(100),
    f2 varchar2(100),
    f3 varchar2(100),
    f4 varchar2(100)
);

insert into t2@DBLINK values (1,'t2 r1 f1','t2 r1 f2','t2 r1 f3','t2 r1 f4');
insert into t2@DBLINK values (2,'t2 r2 f1','t2 r2 f2','t2 r2 f3','t2 r2 f4');

 1 CREATE OR REPLACE PROCEDURE test AS
 2    nt varchar2(10);
 3    nf varchar2(10);
 4    js varchar2(400);
 5 BEGIN
 6     FOR n0 IN 1..2
 7         LOOP
 8             nt := 't' || n0 || '@DBLINK'; -- table name
 9             FOR c1 IN (SELECT * FROM nt)
10                 LOOP
11                     js := null;
12                     FOR n1 IN 1..4
13                         LOOP
14                             nf := 'f' || n1; -- field name
15                             js := js || c1.nf;
16                         END LOOP;
17                     dbms_output.put_line(js);
18                 END LOOP;
19         END LOOP;
20 EXCEPTION WHEN OTHERS THEN
21     NULL
22 END;


text:
Q: In double slit experiment, It's the wave function who represent particles, travelling? I saw some videos that tend to show traveling waves to represent the photon/electron in a double slit experiment. Is it right? Because the space between the electron gun and the screen where these particles can land could be considered a system with boundaries, would this be represented by standing waves? In the other way of thinking the electrons/photons are moving, so does it mean the wave function should be moving too and the system should be considered like traveling waves (getting out from the gun and collapsing on the screen) representing the photons/electrons?

A: First we need to clarify:

*

*the electron when traveling from the gun to the screen, does not have a well defined position

*the electron is in a superposition of states

*it is the electron's wavefunction that describes its probability distribution in space

*the electron is in between the gun and the screen

*as the electron interacts with the screen, its position becomes well known, that is why we see a point on the screen

*the screen is in a superposition of states too, but we see it as well defined, because complex systems are harder to be in superpositions (they have rest mass and do not move fast)

*the wavefunction as per QM describes the probability of finding the electron at a certain position

*when the electron interacts with the screen, it's wavefunction collapses, and the electron's position will be known on the screen

*the wavefunction describes the probability distribution of this, and many electrons need to be fired and measured on the screen to see the same pattern as what the wavefunction describes

A: I believe the electrons possess a position wavefunction which is initially concentrated at the edge of the gun (think of a gaussian) with a momentum concentrated at "moving forward". As time passes, the peak of the position wavefunction advances towards the screen, while becoming more and more spread out.
Note that this wavefunction occupies all of the room, it includes the values in the slits and on the detector screen at all times. As the peak of the wavefunction approaches the slits, its shape begins to change more noticeably, showing the effects of diffraction. Once it passes them, the section of it on the detector will become more and more like the expected interference pattern.
So at each point in time, there is a position wavefunction that occupies all the room. The evolution of this wavefunction is given by the time dependent Shrodinger equation. Thus, it would be a travelling wave-pulse.


text:
Q: How to disable ripple effect in polymer paper elements? I am writing a web app for mobile using polymer which will be packaged using phonegap to run on android device. I am using polymer paper-tabs and core-animated-pages to show a switching effect. On a device, everything works well except the ripple effect on tab touch. It makes the entire thing looks ugly and laggy. How do I disable the ripple effect in paper tabs (and eventually every other paper element) ?
I tried setting the noink property to true in source of paper-tabs as following, but it din't work.
 Polymer('paper-tabs', {

/**
 * If true, ink ripple effect is disabled.
 *
 * @attribute noink
 * @type boolean
 * @default false
 */
noink: true,

A: You can use the noink attribute on the elements that have ripple effects to turn it off:
<paper-button noink>No ink!<paper-button>
<paper-tabs noink>...<paper-tabs>

AFAICT, the first may not work until the next Polymer release of paper-button. It does work in master however if you want to bleed on the edge.


text:
Q: 4 Primes in 9 consecutive Integers This is not so much a question, as it is an interesting (to me at least) observation.
Part of a more complex problem involved finding primes in 9 consecutive Integers greater than 2.
Not being the smartest math guy out "there", I used my current math knowledge + logic, and quickly removed all even numbers as well as numbers ending in 5.
Left were numbers ending in 1, 3, 7 & 9.
I scribbled down some code in Python, and noticed that every time I found 4 primes in 9 consecutive integers, the lowest one always ended in 1.
I concentrated on numbers divisible by 3 and found that the lowest prime MOD 3 had to equal 2:

Remembering that if the sum of digits is divisible by 3, then the number itself is too, I logically discovered that the sum MOD 3 would increase by 2 when going from a number ending in 9 to one ending in 1, hence any sequence of "prime candidates" starting with a number ending in anything by 1 would contain all 3 possible results of the number MOD 3 = [0,1,2], whereas only a sequence starting with a number ending in 1, would only contain 2 of those, and therefore be able to have a sequence with all 4 numbers being prime candidates.
This may be extremely elementary for most of you math experts out there, but I just found it interesting, and discoveries like these are why I love math.
I would love to hear more facts about this particular "primes in 9 consecutive integers" study.
Thanks.

A: It's not hard to show that any 'quadruplet primes' of the type described in the post are congruent (smallest to largest) to $11, 13, 17, 19$ $\pmod{30}$, with the exception of some quadruplets where the smallest prime is less than or equal to $5$.
If this sort of thing is interesting, one can think about double quadruplet primes where the smallest primes in each quadruplet differ by $30$.  The smallest such grouping (I think) is $1006301, 1006303, 1006307, 1006309, 1006331, 1006333, 1006337, 1006339$.

A: You are basically looking for $2$ consecutive pairs of twin primes, which is the only way for $9$ consecutive integers to contain $4$ primes larger than $3$.
It is not known whether there are infinitely many pairs of twin primes, so it is obviously not known whether there are infinitely many consecutive pairs of twin primes.
Of course, except for the first set ($5,7,11,13$), every such set will contain exactly one number ending with each digit ($1,3,7,9$).
There is nothing "too special" about it, as the only reason for this is the use of the decimal base system for representation.


text:
Q: Set KUBECONFIG environment variable dynamically I am quite new to Bash and working on multiple kubernetes cluster. I wanted some kind of utility wherein I can set my KUBECONFIG variable dynamically as I work on multiple clusters. My kubeconfig file lies in multiple folders. What I want is to find all the kubeconfig files , get the paths and concatenate the paths with colon , set it to KUBECONFIG variable and export it in bashrc file.
I know pieces of command but not able to frame full code.
find /Users/anandabhishe/gitlab/ -name kubeconfig.yaml -exec echo {} \;

I want to concatenate the output of find command and set my KUBECONFIG. like this "
export KUBECONFIG=/Users/anandabhishe/gitlab/work2/kubeconfigs/scdc1-staging-hrwork-dev/kubeconfig.yaml:/Users/anandabhishe/gitlab/work2/kubeconfigs/scdc2-prod-hrwork-uat/kubeconfig.yaml:/Users/anandabhishe/gitlab/work2/kubeconfigs/scdc2-prod-hrwork/kubeconfig.yaml "

A: You can try something like that:
export KUBECONFIG=$(for i in $(find /Users/anandabhishe/gitlab/ -iname 'kubeconfig.yaml') ; do echo -n ":$i"; done | cut -c 2-)


text:
Q: Android app update after server change I'm new on android developping and I want to create an small app whitch parse my php file from my server.
I can parse a php file, but if php file change my apps doesn't update - I must close app and reopen. What is best way to check if php file is updated and show updated file?
Or insert timer in app? But I think this is not best way to insert timer every  1 seconds to check php file and update app screen. Maybe everyone know where find tutorial or something?

A: There are 2 ways

*

*use push notification to notify devices that php file is updated.

*check file whether it is changed or not on regular intervel.

in my opinion 1st way is far better. Because when you use 2nd way, it might consume more battery and internet data usage.


text:
Q: Hosting a Web Application on a local server I have an application developed in asp.net. I'm trying to host it on a server so that my manager can access it from a different location. Since I'm not aware of how to process this, any help would be highly appreciated.

A: If you're using web server IIS In the first step you need to :

*

*Start menu write >> inetmgr

*going to control panel and click administrative tools > IIS

*Open IIS ->SItes --> Add web site and enetr the site name click OK

*you may click on the Advance Settings.  from the right panel and modify some settings that you want to modify. In general it is not needed and you can keep it default.

*Now, your website is ready to be browsed, you can right click on the website name (SampleWebSite in my case) and go to Manage Web Site > Browse and you should have an Internet Explorer window open displaying the default page of your website or web application. I suggest you to hosted with asphostportal.com because they are cheap and their support will help you.


text:
Q: Can't run executable linked with libc I am assembling my hello world with the following command:
nasm -f elf64 test.asm
I then link with this:
ld -s test.o -lc
I know this works because file a.out shows me
a.out: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), stripped
However when i run this with ./a.out i get bash: ./a.out: No such file or directory
When link without libc it runs fine! How can I get my libc linked exe to run?

A: The immediate problem is that ld uses /lib/ld64.so.1 as interpreter by default and you may be missing that (it can be a symlink to /lib64/ld-linux-x86-64.so.2 or whatever is appropriate):
$ readelf -l a.out | grep interpreter
      [Requesting program interpreter: /lib/ld64.so.1]
$ ls -l /lib/ld64.so.1
ls: cannot access /lib/ld64.so.1: No such file or directory

You can work around this by setting the interpreter explicitly by passing -dynamic-linker /lib64/ld-linux-x86-64.so.2 option to your ld invocation:
$ ld -s -dynamic-linker /lib64/ld-linux-x86-64.so.2 test.o -lc
$ readelf -l a.out | grep interpreter
      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
$ ./a.out
$

The simple rule of thumb however is to use gcc for linking if you need libc, it will do everything right for you. Also make sure you use main as entry point so that normal libc startup code has a chance of initializing. Similarly, just return from your main at the end and do not use exit syscall directly (you may use the exit function from libc if you really want). In general, using syscalls is not recommended.


text:
Q: aws elastic beanstalk; how to move a file within my app root using .ebextensions I'm trying to move a file located within my app directory:
{MyAppRoot}/.aws_scripts/eb_config.js

to
{MyAppRoot}/config.js.

I need this mv or cp to happen before the app is actually restarted, as this files presence is required immediately by the main app module. I've tried using .ebextensions various mechanisms like commands, container_commands, etc but all fail, with either no stat, or permission denied. I'm unable to get further details from eb_activity.log or any of the other log files. I came across this similar question on the aws forums but I'm not able to achieve any success.
What's the proper way to accomplish this? Thanks.

A: In commandsyour project specific files are not set up yet.
In container_commands they files are in a temporary staging location, but current path is that staging directory. The following should work:
container_commands:
    cp .aws_scripts/eb_config.js config.js.


text:
Q: Redux: How to unit test an async action that dispatches another async action I'm having a hard time trying to test an async function that that dispatches another async function:
export function validateVerifyCode(payload, pin) {
  return dispatch => {
    dispatch(requesting());
    return fetch(`${BASE_URL}/register`).then(resp => {
        return resp.json()
      })
      .then(json => {
        dispatch(hasSubscriptionCheck(json));
        }
      })
      .catch(error => dispatch(hasError(error)))
  }
}

function hasSubscriptionCheck(payload) {
  return dispatch => {
    dispatch(requesting());
    return fetch(`${BASE_URL}/subscriptions`)
      .then(resp => resp.json())
      .then(json => {
        if (json.length == 0) {
          dispatch(handleStripeSubmit(payload));
        }
      })
      .catch(error => dispatch(hasError(error)));
  }
}

The problem is in my unit test it doesn't actually call hasSubscriptionCheck:
  it('validates the verify code', (done) => {
    const stub = sinon.stub(Stripe.card, 'createToken');
    stub.onCall(0).returns(new Promise((resolve) => {
      resolve({});
    }));

    nock(BASE_URL)
      .defaultReplyHeaders({
        'Content-Type': 'application/json',
        'Authentication': token
      })
      .post('/register')
      .reply(200, {id: 'userid1234'})
      .get('/^subscriptions')
      .reply(200, []);

    const store = mockStore({});

    const payload = {
...
    };

    store.dispatch(actions.validateVerifyCode(payload, '123456'))
      .then(() => {
        console.log(store.getActions());
      })
      .then(done)
      .catch(done);
  })

What's weird though is that when i console.log store.getActions(), I see 2 actions:
[ { type: 'REQUESTING' }, { type: 'REQUESTING' } ]

How I tell the test framework to invoke the second fetch?