text:
Q: Complexity of an optimization problem with larger feasible set of an NP-hard problem Suppose the following problem is NP-hard:
\begin{eqnarray}
   \min & f(\boldsymbol{x})\\
    s.t. & \\
   A\boldsymbol{x} &= b\\
\boldsymbol{x} & \in Z^n
\end{eqnarray}
Then what can we say about the complexity of the following problem:
\begin{eqnarray}
   \min & f(\boldsymbol{x})\\
    s.t. & \\
   B\boldsymbol{x} &= d\\
\boldsymbol{x} & \in Z^n
\end{eqnarray}
where $ \{ \boldsymbol{x} : A\boldsymbol{x} = b\} \subseteq  \{ \boldsymbol{x} : B\boldsymbol{x} = d\}$ ?

A: In general, not much.  Some extreme cases are

*

*$B = A$ and $d=b$, in which case the complexities are the same too, and

*$B=0$ and $d=0$, in which case the second problem is trivial.

The problems (more precisely, their decision versions) are in $NP$, because given $x$ you can verify the value of $f(x)$ and the constraint $Bx=d$ in polynomial time.


text:
Q: Why do I need to set the Visibility of LinkButton in a ListView Layout in the LayoutCreated event instead of directly on the LinkButton? I have a ListView control and in the LayoutTemplate I have a LinkButton.  I tried setting the Visible property to <%# IsUserAdmin %>, where IsUserAdmin is a method which returns true or false depending on whether the user is an admin or not and sets the visibility of the control, but I found out that this does not work for the LayoutTemplate and instead of I have to go to the LayoutCreated event and get the control and then set its visibility.  I am curious why I have to do it this way with a control in the LayoutTemplate?  I can use the <%# IsUserAdmin %> on the Visible property of a control in the ItemTemplate with no problem.  I was thinking it would actually be easier for the LayoutTemplate because there is only 1 control generated instead of multiple controls for the ItemTemplates.

A: Does <%= IsUserAdmin %> instead of <%# %> deliver the expected behavior?
You shouldn't use <%# %> in non-databound situations. So for manipulating properties on objects that are just on your form use <%= %>. This'd work as long as IsUserAdmin is a public property.

redpajama_set_name: RedPajamaStackExchange


text: Q: Create dynamic items in list view using kendo UI I am working in a web application, which using Kendo UI. I required a dynamic box  view in list view. ie, there is a plus and minus button, so when user click on that button , new boxes should create and can add items to the selected box.


text:
Q: Generic error [50000-175] caused by NullPointerException I am using H2 database in client-server mode. Server is running with version 1.3.175 and client with 1.3.168.
Everything seems working fine, but I get an exception executing some queries:

org.h2.jdbc.JdbcSQLException: General error: "java.lang.NullPointerException" [50000-175]
      at org.h2.message.DbException.getJdbcSQLException(DbException.java:332)
      at org.h2.message.DbException.get(DbException.java:161)
      at org.h2.message.DbException.convert(DbException.java:284)
      at org.h2.server.TcpServerThread.sendError(TcpServerThread.java:218)
      at org.h2.server.TcpServerThread.run(TcpServerThread.java:158)
      at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
      at org.h2.expression.Function.getCost(Function.java:2391)
      at org.h2.expression.CompareLike.getCost(CompareLike.java:417)
      at org.h2.expression.ConditionAndOr.optimize(ConditionAndOr.java:133)
      at org.h2.command.dml.Select.prepare(Select.java:813)
      at org.h2.command.Parser.prepareCommand(Parser.java:240)
      at org.h2.engine.Session.prepareLocal(Session.java:436)
      at org.h2.server.TcpServerThread.process(TcpServerThread.java:260)
      at org.h2.server.TcpServerThread.run(TcpServerThread.java:156)
      ... 1 more

at org.h2.engine.SessionRemote.done(SessionRemote.java:567)
at org.h2.command.CommandRemote.prepare(CommandRemote.java:67)
at org.h2.command.CommandRemote.<init>(CommandRemote.java:46)
at org.h2.engine.SessionRemote.prepareCommand(SessionRemote.java:439)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1109)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:74)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:264)

Thanks for help.

A: This is a bug in this version of the database engine, which was fixed in revision 5437 of the trunk.
You can either:

*

*go back to the previous version (1.3.174) which should not have this bug,

*use the latest nightly build where it should be fixed,

*download the latest source code and built the database yourself, or

*wait for the next version of H2.


text:
Q: How to run a Python script in Jenkins Pipeline and get the last token? Here is my code for Jenkins Pipeline:
A = bat(script:'c:\\python27\\python.exe D:\\A.py', returnStdout: true).tokenize().last

It works really well to run the Python script in Batch and get the last token. But now I also want to display the log of this Python script. So I tried code as below:
A = bat(script:'c:\\python27\\python.exe D:\\A.py', returnStdout: true).tokenize()
B = A.last
println A

But somehow this Python script will run twice, which is NOT what I want.
Any advice?

A: We have in code solution like (this returns last commit from repository):
def scriptToRun = """@echo off
    echo | git ls-remote repository_url.git ${branch}"""
result = bat(returnStdout: true, script: scriptToRun).trim()

I can see difference only in "echo" part. May be it'll help?


text:
Q: Integrate a function over a triangle in barycentric coordinate Let $A$ be the triangle with vertices $(0,0)$, $(2,0)$ and $(1,1)$ in $R^2$.
I want to find $$I=\int\limits_A (3x^3y-1)\mathrm{d}A.$$
My problem is that I would like to write the triangle in barycentric coordinate and integrate over the domain described in this way.
(the integral should result 1/10)
Any suggestion?


text:
Q: Nginx WordPress and another Web app URL structure I have got WordPress installed on my root example.com/ Website.
Also I have another Web application that on example.com/my-app/ which has got ugly links like example.com/my-app/file.php?arg=value to access.
How can I make my-app SEO friendly URI structure working as example below?:
example.com/my-app/file.php?arg=value
to
example.com/my-app/value/

Currently, if I access to example.com/my-app/value/ it redirects me to my WordPress post which contains some characters of the /value/. Why? Is there anyway to get this working?
My Nginx directives for domain are listed below:
location / {
  try_files $uri $uri/ /index.php?$args;
  fastcgi_read_timeout 300;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Any ideas? Should I use Ajax navigation, with switch cases? What about HTML5 pushState() API? Any working examples?
Thanks for help!

A: You should try the Rewrite plugin as mentioned in this post "Nginx rewrite rule conflict with WordPress permalinks rule", it could help solve the issue. If not, we'll have to dig deeper, let me know.


text:
Q: Difference between 32-bit and 64-bit Excel 2007 I had an argument with my colleagues over the difference between 32-bit and 64-bit Excel 2007. I said the main difference is that in 64-bit version, we'll be able to add more than 65536 rows where as in 32-bit we won't be able to add more than 65536 rows.
Please clarify this.

A: No, both 32 and 64 bit versions support more than 65536 rows, and have done since Excel 2007 was released.
The main difference is that you can work with very large workbooks in the 64 bit version.  The downside of the 64 bit version is that, at present, there is poor support from 3rd party add-ins.
Update
This was written back in 2011. I'm sure that support for 3rd party add-ins is better now. However, it may still be an issue, and before installing the 64 bit version it is worth checking that all your required tools that are built on top of Excel are compatible with the 64 bit version.

A: Excel 2007 has only a 32-bit version. Excel 2010 introduced the 64-bit option, which Microsoft actually doesn't recommend unless you really really need it for huge databases.

A: The main difference is that the 32 bit version only has access to 2GB of memory. Very large integer calculations might also be faster in the 64 bit version.
Both versions can deal with more than 65536 rows.


text:
Q: openssl s_client -connect: Peer signing digest (SHA1) I am using this command to connect to a local server:
openssl s_client -connect 127.0.0.1:3978 -sigalgs 'ECDSA+SHA256'

It connects. Whereas I was expecting the connection to fail, because the server report SHA1 as the "Peer signing digest". Why is that happening?
bash-4.4# openssl s_client -connect 127.0.0.1:3978 -sigalgs 'ECDSA+SHA256'
CONNECTED(00000003)
depth=0 CN = subsubca-ecdsa
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = subsubca-ecdsa
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/CN=subsubca-ecdsa
   i:/CN=rootca-ecdsa
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIB0zCCAVqgAwIBAgICEAMwCgYIKoZIzj0EAwIwFzEVMBMGA1UEAwwMcm9vdGNh
LWVjZHNhMB4XDTIyMTAxNzA4MzgxMVoXDTIzMTAxNzA4MzgxMVowGTEXMBUGA1UE
AwwOc3Vic3ViY2EtZWNkc2EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARovUyjxAN6
20LlQqdLFt1ZZys4sMI2JcrXiRJyqDqdwCPOEqqvm7timWKyUAVdsimoooSRJsBR
+ln6riPfdhr3ILGHAyXgPog93Sg0QARaHivozJCmPLDQ9fvHNkgnxWijdzB1MAwG
A1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBR+yiPE39VXYZpY
sSeWlHzOIAbkADAgBgNVHSUBAf8EFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwFAYD
VR0RBA0wC4IJbG9jYWxob3N0MAoGCCqGSM49BAMCA2cAMGQCMDyeF/l8WFpA5Y5q
URDJ+E+eXfyUGlwtmt/2A3UEchf6Ckq+hMnzz9eqOygy80i0vAIwOdUsV7OSKITY
twT4xWmMEpjSxoc+A8HLQuZbpwDMYhmcyScie1aUYveV1kq1Q87g
-----END CERTIFICATE-----
subject=/CN=subsubca-ecdsa
issuer=/CN=rootca-ecdsa
---
No client certificate CA names sent
Peer signing digest: SHA1
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 976 bytes and written 267 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-ECDSA-AES256-GCM-SHA384
Server public key is 384 bit
Secure Renegotiation IS supported
...

BR, Rene


text:
Q: Find most recently accessed file from give files in C How to get most recently accessed file in Linux?
I used stat() call checking for st_atime, but it is not updating if i open and read the file.

A: You can check if your filesystem is mounted with the noatime or relatime option:
greek0@orest:/home/greek0$ cat /proc/mounts
/dev/md0 / ext3 rw,noatime,errors=remount-ro,data=ordered 0 0
...

These mount options are often used because they increase filesystem performance. Without them, every single read of a file turns into a write to the disk (for updating the atime).
In general, you can't rely on atime to have any useful meaning on most computers.
If it's Ok to only detect accesses to files that happen while your program is running, you can look into inotify. It provides a method to be notified of currently ongoing filesystem accesses.
If that doesn't satisfy your requirements, I'm afraid you're out of luck.


text:
Q: Does TideSDK give you access to hardware (e.g. USB)? I need to do some basic talking to hardware over USB and am looking for a simple way to build a cross-platform desktop app.

A: What do you mean by "Talking"? you can use the "Ti.Filesystem" from the tide API, it enables you to read and write files.


text:
Q: call function dynamically, passing arguments from variable here is my ajax_handle file:
   if ($_SERVER['HTTP_X_REQUESTED_WITH'] !== "XMLHttpRequest")
    {
        echo "Error";
        exit();

    }
    $req = explode("_",$_POST['req']);
    $className = $req[0] . "Controller" ;
    $methodName = $req[1];
    $file = "application/controllers/" . $className . ".php" ;
    require_once $file;
    if ($_POST['data']) {
        var_dump($_POST['data']);
    }
    $controller = new $className;
    $result = $controller->$methodName();
    echo json_encode($result);

I send the arguments as any array in the $_POST['data'] variable. i have no idea what would be the best way to pass them to the (dynamic) $methodName function.

A: I suppose you could just pass $_POST['data'] as is to your dynamic method. You can have the
dynamic method accept the array but initially set default values so you can easily handle and
validate them. Example:
class AController
{
  public function dynamicMethod($params)
  {
    // Set default values but allow them to be overridden by $params
    $locals = array_merge(array(
      'name' => 'John Doe',
      'address' => 'Nowhere',
    ), $params);

    // Do stuffs and return result. Example:
    return array('nameAndAddress' => $locals['name'] . ' lives at ' . $locals['address']);
  }
}

You also opt to use extract() to convert the
name and address above into real local variables.
In your ajax handle:
$controller = new $className;
$result = $controller->$methodName($_POST['data']);
echo json_encode($result);

With all these said, please note that what @Sven is saying is correct. There are some security
issues in your current approach.


text:
Q: Integral of $\arccos$ function combined with exponontial function Is it possible to calculate this integral?
$$\int_0^1 x^{j}\  e^{ax^2}\arccos(x)\ dx,\qquad a\in\mathbb{R}_+,\ j\in\mathbb{N}. $$
Although the integral looks neat and fairly simple in form. I tried evaluating it using integration by parts but without success. I also couldn't find the solution in the book, "Table of Integrals, Series, and Products" by Gradshteyn and Ryzhik and Prudnikov, Brychkov, - Integrals and Series 1-3.
Can anyone help me in solving this?
Thank you.


text:
Q: pyplot - what does iloc do in this code snippet Yes, I read the documentation on pyplot's website. No, it still doesn't make sense.
What does the following code snippet do?  I think it's reading in the first 100 lines of a dataset, but not sure what it does regarding the columns:
# select setosa and versicolor
    y = df.iloc[0:100, 4].values
    y = np.where(y == 'Iris-setosa', -1, 1)

    # extract sepal length and petal length
    X = df.iloc[0:100, [0, 2]].values

    # plot data
    plt.scatter(X[:50, 0], X[:50, 1],
                color='red', marker='o', label='setosa')
    plt.scatter(X[50:100, 0], X[50:100, 1],
                color='blue', marker='x', label='versicolor')

    plt.xlabel('sepal length [cm]')
    plt.ylabel('petal length [cm]')
    plt.legend(loc='upper left')

A: the line y = df.iloc[0:100, 4].values is taking the first 100 rows (as you know), and the 5th (index 4) column. And the .values on the end is converting that to a numpy arrray, rather than a pandas series.
the line X = df.iloc[0:100, [0, 2]].values is again taking the first 100 rows, and the first and third (index 0 and 2) columns, and again converting it to an array. This one gives us a 100x2 array since we chose two columns, which I think is why the author used a capital X for the variable name, compared to a lower case y for the 100x1 array from the first step.
The third section, this line:
plt.scatter(X[:50, 0], X[:50, 1],
                color='red', marker='o', label='setosa')

makes a scatter plot with the first 50 rows of X, where the first column is the horizontal position and the second column is the vertical position. The next line:
plt.scatter(X[50:100, 0], X[50:100, 1],
                color='blue', marker='x', label='versicolor')

is doing the same thing with the bottom half (rows 50-100) of X. If you're running this code and nothing is happening, try adding plt.show() at the end.


text:
Q: LSTM for next-word Prediction, Why did the accuracy never increases from the start and how to fix it I am training a LSTM model for next word prediction in Indonesian Language. The Dataset used is around 100,000 sentences taken from wikipedia public corpora. Each sentence for the LSTM is tokenized and then sequenced into a maximum length of 9 words, 8 words for the input, and 1 word for the output.
tokenizer = Tokenizer()

tokenizer.fit_on_texts(sentences)
total_words = len(tokenizer.word_index) + 1

input_sequences = []
LENGTH_WORD = 8
for line in sentences:
    token_list = tokenizer.texts_to_sequences([line])[0]
    first_index = 0
    for i in range(1, len(token_list)):
        n_gram_sequence = token_list[first_index:i+1]
        if i>=LENGTH_WORD:
            first_index = first_index+1
        input_sequences.append(n_gram_sequence)

# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))

# create predictors and label
xs, labels = input_sequences[:,:-1],input_sequences[:,-1]

E.g. -> Input Sentence: 'I am eating an apple pie and a fried chicken inside my house'
Sequence:
['I']
['I','am']
......
['I','am','eating','an','apple','pie','and','fried']
['am','eating','an','apple','pie','and','fried','chicken']
....
The predictor and the label is then created from the input sequences. Since it is not possible to encode the output using one hot encoding due to the vocabulary size (around 50000 words), I decided to use binary encoding.
The model code is as below
model = Sequential()

# size of the input dimensions = length of the longest sequence minus 1.
# subtract one since last word is used for ys.
model.add(Embedding(total_words, 20, input_length=max_sequence_len-1))

model.add((LSTM(150)))
# Sense layer sized as the total words, because we have as many outputs as the total word count.
model.add(Dense(max_length, activation='softmax'))
adam = Adam(learning_rate=0.001)

model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
print(model.summary())
#earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')

history = model.fit(xs, ys, epochs=100, verbose=1,
                callbacks=[checkpoint])
#print model.summary()
print(model)

The accuracy keeps stuck betweeen 0.038 and 0.041 and the loss always increase in every epoch.
I have tried changing the metrics to other  accuracy such as categorical_accuracy, the LSTM unit, and the embedding output size, but the accuracy never improved at all and the loss keeps skyrocketing.


text:
Q: get the value for ALT is we check to see if an actual ALT value is set, if not we use the caption and if no caption is set we use the title function custom_pic_alt( $attachment_ID ) {

      // Get ALT
    $thumb_alt = get_post_meta( $attachment_ID, '_wp_attachment_image_alt', true );

    // No ALT supplied get attachment info
    if ( empty( $thumb_alt ) )
      $attachment = get_post( $attachment_ID );

    // Use caption if no ALT supplied
    if ( empty( $thumb_alt ) )
      $thumb_alt = get_post(get_post_thumbnail_id())->post_excerpt;

    // Use title if no caption supplied either
    if ( empty( $thumb_alt ) )
      $thumb_alt = get_post(get_post_thumbnail_id())->post_title;

    // Return ALT
    return esc_attr( trim( strip_tags( $thumb_alt ) ) );
 }

show result
<?php echo custom_pic_alt( 10 ); ?>

and i get same alt for all attachments.

A: Not sure if this'll work for you because I don't know if $attachment_ID in the function is returning anything at all... ...but assuming it is:
function custom_pic_alt( $attachment_ID ) {
    //var_dump( $attachment_ID ); //uncomment this and see if it even returns anything.
    $thumb_alt      = get_post_meta( $attachment_ID, '_wp_attachment_image_alt', true );
    $thumb_caption  = wp_get_attachment_caption( $attachment_ID );
    $thumb_title    = get_the_title( $attachment_ID );

    if( !empty( $thumb_alt ) ) :
        $alt_text = $thumb_alt;
    elseif( empty( $thumb_alt) && !empty( $thumb_caption ) ) :
        $alt_text = $thumb_caption;
    elseif( empty( $thumb_alt ) && empty( $thumb_caption ) && !empty( $thumb_title ) ) :
        $alt_text = $thumb_title;
    else :
        $alt_text = '';
    endif;

    // Return ALT
    return esc_attr( trim( strip_tags( $alt_text ) ) );
}

You just get all three values and then run conditional checks to see if they're empty or not.


text:
Q: Getting inconsistent results I'm using ANTLR 4.6 and I was trying to do some clean up on my grammar and ended up breaking it. I found out that it's because I had made the following change that I assumed would have been equivalent. Can someone explain why they are different?
First try
DIGIT : [0-9] ;
LETTER : [a-zA-Z] ;
ident : ('_'|LETTER) ('_'|LETTER|DIGIT)* ;

Second try
DIGIT : [0-9] ;
LETTER : [a-zA-Z_] ;
ident : LETTER (LETTER | DIGIT)* ;

Both produce different results than this
DIGIT : [0-9] ;
LETTER : [a-zA-Z_] ;
IDENT : LETTER (LETTER | DIGIT)* ;

A: In both your tries you changed your ident rule from a lexer rule to a parser rule since you wrote it in lower case and since it's the only difference from the second try I assume that's the problem. The lexer rules are for defining tokens for parsing, parsing rules define the way you construct your AST. Beware that making changes like that can result in great differences in the way the your AST is constructed.


text:
Q: bash_profile function to git grep and replace I wanted to create a function in my ~/.bash_profile that would git grep and list the files that contains a string and then replace all occurrences of that string with another
function git-replace() { eval git grep -l ${1} | xargs sed -i '' -e 's/${1}/${2}/g' ; }
However, if I run the function git-replace "Type1" "Type2" , nothing happens. What am I doing wrong here ?

A: There's 2 issues:

*

*don't use the evil eval

*if you want to expand a variable, don't use single quotes but double quotes, so:

git-replace() {
    git grep -l "$1" | xargs sed -i '' -e "s/$1/$2/g"
}

And no need the function statement in modern shell.
Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words


text:
Q: Abort trap: 6 Swift 4.2 Xcode Error on Release I got this error only when I build the project in for archive the application install normally in my iPhone.
Some Help please

A: I solve this problem by changing the production release to -Onone

and changing release to DWARF

In the Build setting.


text:
Q: Auto restart or power off/on mode on my mobile device, open the Application automatically in React native how-do-i-start-my-app-when-the-phone-starts-on-android
Based on above link I have modified my native code in React native project as given below, but I am not getting any result..!!
Androidmanifest.xml
``
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.freshot.co.ownerapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyA88RySEu8iI-oY15iKKLE25WKVjKefKjk"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <receiver
        android:name="com.freshot.co.ownerapp.BootReciever"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>
    </application>
</manifest>

``
BootReciever.java
`
package com.freshot.co.ownerapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction() != null) {
           if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Intent i = new Intent(context, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
    }
  }
}

`
My Sollution should be :  When ever Mobile phone / Tab Reboots or power off/on, My React native Application should open automatically

A: Won't work on modern android-  broadcast receivers are background tasks.  Background tasks can't launch foreground activities.  This method works for you to do some quick background processing, or set up some alarms for later, but it won't allow you to display an activity.
Are you a kiosk mode app where you want to take over the homescreen and lock the user into your app?  If so, you should be writing a launcher app.  If not, this kind of behavior is highly discouraged up to almost being active malware-  popping up your app on boot isn't user friendly, its spammy and annoying.
To make an activity the home screen for a kiosk, use
   <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

        <category android:name="android.intent.category.HOME" />

        <category android:name="android.intent.category.DEFAULT" />

    </intent-filter>

in your manifest, then set your app as the default launcher after install.  After that, it will always launch your app on boot and when the user clicks the home button.


text:
Q: Explanation for string behavior ["somestring" "somestring"] being evaluated to ["somestringsomestring"] I'm using python 3.10.4 right now.
I mistakenly wrote ["somestring" "somestring"] without a , separating the strings. Which evaluated to ["somestringsomestring"] without raising an error (which an error raised was my expectation).
And it seems like it was like that for previous versions.
How should I interpret the process of "string" "string" being evaluated to "stringstring"?


text:
Q: typedef declaration syntax Some days ago I looked at boost sources and found interesting typedef.
There is a code from "boost\detail\none_t.hpp":
namespace boost {

namespace detail {

struct none_helper{};

typedef int none_helper::*none_t ;

} // namespace detail

} // namespace boost

I didn't see syntax like that earlier and can't explain the sense of that.
This typedef introduces name "none_t" as pointer to int in boost::detail namespace.
What the syntax is?
And what difference between "typedef int none_helper::*none_t" and for example "typedef int *none_t" ?

A: The syntax is for a pointer to member - here it typedefs none_t as a pointer to an int data member of none_helper.
The syntax can be used e.g. this way:
 struct X { int i; };

 typedef int X::*PI;
 PI pi = &X::i;
 X* x = foo();
 x->*pi = 42;

InformIT has an article on member pointers, containing more details.

A: *

*typedef int* none_t; introduces type alias for pointer to integer.

*typedef int non_helper::*none_t; introduces type alias for pointer to integer member of non_helper class.

A: none_t is a pointer to member variable with type int of none_helper.
struct none_helper
{
  int x1;
  int x2;
};

int none_helper::* ptm = &none_helper::x1;
^^^^^^^^^^^^^^^^^^
     none_t


text:
Q: unable to open a pdf file at specific page in Adobe Reader 11 using C# code The below lines of code are used to open a PDF file at a particular page in C#. the code works absolutely fine for all the adobe version other than the latest, which is 11.
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "AcroRd32.exe";
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\Jack and Jill.pdf";
myProcess.Start();

Can some one please help me out and let know what is special with adobe reader 11. Any help will be greatly appreciated.
The error is "There was an error opening this document. The file cannot be found." (THE FILE DOES EXIST)
P.S: I have uninstalled adobe 11 and installed adobe reader 10 and the code works absolutely fine then.
also the arguments when given from command line when Acrobat Reader 11 is installed works fine and opens PDF.

A: Make sure u dont have spaces in the name of the file. it works if it has spaces in all other  adobe readers but  adobe reader 11 dosent support that.
Hope this helps

A: According to the Parameters for Opening PDF Files, your arguments line should look like this:
myProcess.StartInfo.Arguments = "/A \"page=2\" C:\\example.pdf";

A: Make sure that file C:\example.pdf exist. This error occurs when there is no file.
string pdfPath = @"C:\example.pdf";

if (System.IO.File.Exists(pdfPath))
{
     System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
     myProcess.StartInfo.FileName = "AcroRd32.exe";
     myProcess.StartInfo.Arguments = string.Format("/A \"page=2=OpenActions\" \"{0}\"", pdfPath);
     myProcess.Start();
}

A: Open Parameters for Reader 11 have changed or been removed.
Use Reader 10.
I have asked Adobe for information on Open parameters for reader 11 but had no response.


text:
Q: Firefox: save username/password for all sub domains? Not sure if this is possible -- I have a username and password combo which is valid for all sub-domains of a given domain, that is: domain1.example.com, domain2.example.com, domain3.example.com, etc. Is there any way I can tell Firefox that the saved password for one of these subdomains is valid for all of them? RIght now I have been retyping it for each one, and saving them individually. But the list of these subdomains will be constantly growing...

A: I filed a bug for this on Firefox. Surprised it wasn't filed already: https://bugzilla.mozilla.org/show_bug.cgi?id=589628

A: You can do this using firefox addon called LastPass. This addon recognizes that subdomains and prompts you to use previously saved password.
LastPass is also a third party service which stores your password in 128bit encrypted cloud server. Your passwords never leave your system. Passwords are encrypted on system and then sent server.
hope this helps.


text:
Q: Updating views on load method + http.get strange behaviour I have an AngularJS application with different views. One of those views is used to control a tool which has three different states : started, stopped, paused with corresponding buttons.
The tool runs on a server and I want to update the state of my view with the data from the server each time I go back to it. Example : I start the tool, then go to a different view, when I go back on the tool view, I call a service using $http.get to obtain the state of my tool. This returns me a string "started", and i use it to update the elements of my view.
1 - Is it better to use ng-init="update()" in my Tool.html to update at each reload like in :
<div ng-init=update()> [all my content] </div>

or to call update() in my tool controller ? Or maybe another methode you could suggest me.
2 - I tried the two precedent methods, and in each case I have a problem where sometimes, the http.get isn't working and the elements are not correctly actualised. I use it this way :
$http.get('linkToGetTheState')
          .then(function(response) {
              $scope.toolStatus = response.data;
          })
switch($scope.toolStatus)
...

Sometimes it works, other time it doesn't (when I run step by step, it skips everyting from the beginning of the http.get until the end of the switch and toolStatus stays undefined), and even weirder, it works better if I call the function twice... If anyone has any clue on what is happening here and/or why, I would be very thankful.
I hope my question is clear, I'm new to Angular/StackOverflow, and I can give more precisions if needed.

A: My problem is resolved. Here are the solutions I found :
1 - I personally prefer to call the update() function in my controller as follow :
app.controller('MyCtrl', function ($scope, ...) {
    [...]

    $scope.update = function() {
        ...
        });
    };

    [...]

    $scope.update();
});

This way, each time the corresponding view is displayed, the function is called once to update it (when changing tabs AND when refreshing the page).
- 2 For this part, I actually still don't know where the problem really came from. I used the method Gatsbill adviced me here (in the Edit part of his post) : Gatsbill answer
to clean/reorganize my project. And with the service to handle $http request, it was working fine.


text:
Q: regex to separate paragraphs by double new line Making a tiny helper for authors to add/remove empty lines in textarea. The one that removes extra lines seems to work:
if(jQuery("#remove_line").prop("checked")){
        conver = conver.replace(/^\s*[\r\n]/gm,'');
    }

But there has to be a reverse one that makes any new line into double new line (no matter if there's just 1 or even 3 new lines in a row). E.g. this:
text
text

text

text

Should be processed into this:
text

text

text

text

Anyone can help with that? Thanks in advance!

A: You can match one or more newlines [\r\n]+ and replace with 2 newlines \n\n

const regex = /[\r\n]+/gm;
const str = `text
text

text

text`;

console.log(str.replace(/[\r\n]+/g, `\n\n`));

A: didn't test but i think this could work : replace(/[\n]+?/g,'\n\n')
\n+ will match 1 or more new lines, the question mark will force to take the shortest amount possible (this will stop the matching block at the first non new line character)

A: The reverse?

addEventListener('load', ()=>{
const ta = document.querySelector('textarea');
function doubleSpaceAfter(fullText, text, insensitive = true){
  const s = insensitive ? 'i' : '';
  return fullText.replace(new RegExp('('+text+')\\s+', 'g'+s), '\n\n$1\n\n');
}
ta.value = doubleSpaceAfter(ta.value, 'text here');
}); // end load
<textarea>other stuff text here is this what you want? text here text here</textarea>


text:
Q: How to pick a random item within a list while two lists are being considered? Sorry I couldn't come with a better title. My problem is I have two lists and I want to randomly pick an item from first list and match it with an item from second list, but indexes of those items cannot be the same (li1[3] cannot be matched with li2[3]) and also after an item is picked it has to be removed from the list. I tried this code but it doesn't get the job done. Thanks for any help.
from random import choice

teams1 = ["brazil", "croatia", "england", "italy", "mexico", "cameroon", "ivory coast", "japan"]
teams2 = ["spain", "germany", "belgium", "holland", "argentina", "portugal", "france", "usa"]

counter = 3
counter2 = 8
while counter != 0:
    a = choice(range(1,counter2))
    a1 = teams1[a]
    b = choice(range(1,counter2))
    b1 = teams2[b]
    print(teams1[0], b1)
    print(teams2[0], a1)
    del teams1[a]
    del teams2[b]
    del teams1[0]
    del teams2[0]
    counter -= 1
    counter2 -= 2

print(teams1[0], teams2[0])

A: You can do this using random.randrange!
import random

teams1 = ["brazil", "croatia", "england", "italy", "mexico", "cameroon", "ivory coast", "japan"]
teams2 = ["spain", "germany", "belgium", "holland", "argentina", "portugal", "france", "usa"]

t1 = random.randrange(0, len(teams1))
t2 = random.randrange(0, len(teams2))

while t2 == t1:
    t2 = random.randrange(0, len(teams2))

rand_choice1 = teams1.pop(t1)
rand_choice2 = teams1.pop(t2)

The while loop prevents the two indices from being identical, and the .pop() builtin method of the list removes the teams we choose from the list.
This approach only lists a single matchup, but it could be easily made into a function to randomly match all teams.

A: I would not be surprised if there is a more elegant way of constructing pair combinations, but this seems to do what has been clarified in the question comments:
#/usr/bin/env python2.7
from random import shuffle

def main():

    teams1 = ["brazil", "croatia", "england", "italy",
              "mexico", "cameroon", "ivory coast", "japan"]
    teams2 = ["spain", "germany", "belgium", "holland",
              "argentina", "portugal", "france", "usa"]

    excluded_pairs = dict(zip(teams1, teams2))
    shuffle(teams1) # not really needed
    shuffle(teams2)

    while len(teams1):
        t1 = teams1.pop()
        if len(teams1) > 1:
            if teams2[-1] != excluded_pairs[t1]:
                t2 = teams2.pop(-1)
            else:
                t2 = teams2.pop(-2)
        elif len(teams1) == 0:
            t2 = teams2.pop(-1)
        elif len(teams1) == 1:
            if (teams2[-1] != excluded_pairs[t1]
                and teams2[-2] != excluded_pairs[teams1[0]]):
                t2 = teams2.pop(-1)
            else:
                t2 = teams2.pop(-2)

        print '{} vs. {}'.format(t1, t2)

    print len(teams1)
    print len(teams2)

if __name__ == '__main__':
    main()

A: Your program is right. Except that your program exits when there are still values in either lists. That is because your counter hits 0 and the condition:
while counter != 0:

no longer holds.
You can change that condition to check if there are no more items in either lists using:
while len(teams1) and len(teams2):

or :
while counter > -1:

and get rid of the last line:
print(teams1[0], teams2[0])

And your program works as expected.


text:
Q: React Module not found with Bootstrap I am working on an app that I started with create-react-app. I've included react-bootstrap and had everything working well. Then last night I tried to install react-d3-component.

I followed the npm instructions:

*

*npm install react-d3-components

*npm install & npm run build:js
After running that the next time I tried npm start I got the following error with my Bootstrap:
./src/index.js
Module not found: Can't resolve 'bootstrap/dist/css/bootstrap.css' in '/home/nick/Desktop/crypto/src'

I have since tried uninstalling react-d3-components and uninstalling and reinstalling react-bootstrap to no avail. I imagine the problem is with npm run build:js and a Bootstrap extension but I'm not sure.
Any idea how to fix this?
Live demo here: https://codesandbox.io/s/github/Nicknyr/crypto


text:
Q: Active Record Relation Joins - 3 main tables, 2 join tables The setup
I have a data model with 3 major tables (users, links, topics) with 2 join tables (link_saves and link_topics). My models:
User
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'user_id'
has_many :links, :through => :link_saves

LinkSave
belongs_to :user
belongs_to :link

Link
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'link_id'
has_many :users, :through => :link_saves

has_many :link_topics, :inverse_of => :link
has_many :topics, :through => :link_topics

LinkTopic
belongs_to :link
belongs_to :topic

Topic
has_many :link_topics
has_many :links, :through => :link_topics

The Question
I want to be able to find a list of all the topics a user has saved links for.  I would like to be able to do @user.topics and have it hop across all 5 tables from user all the way to topics.  More importantly, I want this to return an ActiveRecord relation so that I can scope/sort/page the list of user topics further so this would NOT work:
## app/models/user.rb

def topics
  links.collect(&:topics)
end

Am I going down the wrong path?  Is there a way to do this through active record without having to write all the custom SQL?  Help please!
Possible Answers (Update)
Using multiple has_many :throughs to make all the hops.  This works, but can't be best practice, right?
## app/models/user.rb
has_many :link_saves, :class_name => 'LinkSave', :foreign_key => 'user_id'
has_many :links, :through => :link_saves
has_many :link_topics, :through => :links, :uniq => true
has_many :topics, :through => :link_topics, :uniq => true

A: I think this is called a 'nested' has_many through, basically going from A to B to C.
In Rails 3.1 this functionality is now supported
http://www.warmroom.com/yesterdays/2011/08/30/rails-3-1-nested-associations/
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html (search for 'Nested')
The example they have is a bit simpler than what you have, but I think it should be enough for you to get some ideas.
class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
  has_many :commenters, :through => :comments
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :commenter
end

@author = Author.first
@author.commenters # => People who commented on posts written by the author

Prior to Rails 3.1 there was a plugin
'https://github.com/releod/nested_has_many_through'


text:
Q: NotifyDatasetChanged not working in customListView in android I have made a custom ListView and adapter for that, I have made a custom relative layout class for delete feature. Now I want to update my ListView once any of item is deleted. I have used notifydatasetChanged() method, But its not working. Please help me. My adapter is as below
public class TimelineAdapter extends ArrayAdapter<Post> {

    private final LayoutInflater mInflater;

    public TimelineAdapter(Context context) {

        super(context, R.layout.list_item_post);
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void setData(List<Post> data) {
        setNotifyOnChange(false);
        clear();
        if (data != null) {
            addAll(data);
            notifyDataSetChanged();
        }
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        Post post = getItem(position);
        PostListItem view;
        if (convertView == null) {
            view =  (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
        } else {
            view = (PostListItem) convertView;
        }
        view.setPost(post);
        return view;
    }
}

CustomListItem
if (mPost.postUser.userID == sharedConnect.mCurrentUser.userID) {
    // Log.e("Remove Post", "Success");

    //Added by jigar..
    tfragment = new TimelineFragment();
    AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());

    builder1.setMessage("Are you sure?");
    builder1.setCancelable(true);

    builder1.setPositiveButton(
            "Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

    //open = false;
                    new AsyncTask<Void, Void, Boolean>() {

                        @Override
                        protected Boolean doInBackground(Void... params) {

                            Connect sharedConnect = Connect.getInstance(getContext());
                            sharedConnect.deletePost(mPost.postID);

                            return true;
                        }

                        protected void onPostExecute(Boolean result) {

                            Toast.makeText(getContext(), "Deleted",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }.execute();

                }
            });

    builder1.setNegativeButton(
            "No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    //  open = false;
                }
            });

    AlertDialog alert11 = builder1.create();
    alert11.show();

    //end


text:
Q: How is "he do" possible grammatically?
And if he do not these three unto her, then shall she go out for
  nothing, without money. Source

Another instance:

Now he don't talk too much, talk too much. Source

Please explain how is it possible grammatically?

A: Your second example appears to be poetry written in a specialized dialect. Either one of these situations (both poetry and dialect) will use language that does not follow the standard rules of grammar. It will be more helpful to beginning students of English to concentrate on more mainstream material if they want to analyze the structure of sentences.
Going back to your first example, from the Bible: the translation there is also not standard in today's English. The verb "do [not]" used in that passage is in the subjunctive form. If we were to use that verb form today we would probably add another word, "should", in an "if" clause to make it clear that we are talking about a conditional, counter-factual situation, and we would then write it as: "If he should not do these three ..."
But both of your examples are text that might confuse advanced students or even native speakers. If you don't worry about the structure of the sentences, the meaning of both of those examples seems pretty understandable, so don't worry if passages from poetic or archaic sources conflict with what you are learning about standard, modern English.

A: The first example sounds perhaps archaic, definitely not current common usage. Perhaps someone else can shed more light.
The second example, I'm pretty sure, is simply colloquial -- technically, not correct English, but in actual common use.


text:
Q: Case insensitive expectations in Rhino Mocks I'm using Rhino Mocks to expect a call. There is a single parameter which is a string. But I'm not bothered about the case of the string. I want the test to pass even if the case is wrong. So I'm doing the following:
//expect log message to be called with a string parameter.
//We want to ignore case when verifying so we use a constraint
//instead of a direct parameter

Expect.Call(delegate { logger.LogMessage(null); })
      .Constraints(Is.Matching<string>(x => x.ToLower()=="f2"));

It seems a bit long-winded. Is there a more sensible way of doing this?

A: // arrange
var loggerStub = MockRepository.GenerateStub<ILogger>();

// act
loggerStub.LogMessage("f2");

// assert
loggerStub.AssertWasCalled(
    x => x.LogMessage(Arg<string>.Matches(
        s => string.Equals(s, "f2", StringComparison.OrdinalIgnoreCase)
    ))
);

If you don't care about parameters but just the method call:
loggerStub.AssertWasCalled(
    x => x.LogMessage(null),
    x => x.IgnoreArguments()
);

A: I would use the AAA format that @Darin suggests (or similar).  I think it's more concise, but you'll still have to use the same basic constraint for case insensitive matching, I think.  A helper method can make this more readable.
 private bool CaseInsensitive( string s, string t )
 {
      return string.Equals( s, t, StringComparison.OrdinalIgnoreCase );
 }

 var loggerMock = MockRepository.GenerateMock<Logger>();

 loggerMock.Expect( l => l.LogMessage( Arg<string>.Matches( s => CaseInsensitive( s, "f2" ))));

 classUnderTest.MethodUnderTest();

 loggerMock.VerifyAllExpectations();


text:
Q: Celery - running a set of tasks with complex dependencies In the application I'm working on, a user can perform a "transition" which consists of "steps". A step can have an arbitrary number of dependencies on other steps. I'd like to be able to call a transition and have the steps execute in parallel as separate Celery tasks.
Ideally, I'd like something along the lines of celery-tasktree, except for directed acyclic graphs in general, rather than only trees, but it doesn't appear that such a library exists as yet.
The first solution that comes to mind is a parallel adaptation of a standard topological sort - rather than determining a linear ordering of steps which satisfy the dependency relation, we determine the entire set of steps that can be executed in parallel at the beginning, followed by the entire set of steps that can be executed in round 2, and so on.
However, this is not optimal when tasks take a variable amount of time and workers have to idle waiting for a longer running task while there are tasks that are now ready to run. (For my specific application, this solution is probably fine for now, but I'd still like to figure out how to optimise this.)
As noted in https://cs.stackexchange.com/questions/2524/getting-parallel-items-in-dependency-resolution, a better way is operate directly off the DAG - after each task finishes, check whether any of its dependent tasks are now able to run, and if so, run them.
What would be the best way to go about implementing something like this? It's not clear to me that there's an easy way to do this.
From what I can tell, Celery's group/chain/chord primitives aren't flexible enough to allow me to express a full DAG - though I might be wrong here?
I'm thinking I could create a wrapper for tasks which notifies dependent tasks once the current task finishes - I'm not sure what the best way to handle such a notification would be though. Accessing the application's Django database isn't particularly neat, and would make it hard to spin this out into a generic library, but Celery itself doesn't provide obvious mechanisms for this.

A: I also faced this problem but i couldn't really find a better solution or library except for one library, For anyone still interested, you can checkout
https://github.com/selinon/selinon. Although its only for python 3, It seems to be the only thing that does exactly what you want.
Airflow is another option but airflow is used in a more static environment just like other dag libraries.


text:
Q: What does mysql -u root -p mean while logging in? I am new to using Mysql and I do not understand what does -u and -p imply?

A: These are command line options passed to mysql.
-u stands for the username and -p stands for the password
Whatever comes immediately after -u will be the username and after you press Return you need to enter your password (the password won't be visible and you need to type in your complete password followed by again a Return, you won't see * too in place of the password, it would be completely invisible).
See the manual page of mysql for more.

A: -u root says root is the user and -p will ask for a password.


text:
Q: UIImageView not redrawing when image set to nil I am using a UIImageView to display both still and animated images.  So sometimes, I'm using  .image and sometimes I'm using .animationImages.  This is fine.
Whether it's static or animated, I store the UIImages's in item.frames (see below)
The problem is that I'd like to display a UIActivityIndicatorView in the center of the view when the animation frames are loading.  I would like this to happen with no images or frames in there.  The line that isn't doing what it's supposed to is:
[self.imageView removeFromSuperview];

As a matter of fact, setting it to another image at this point doesn't do anything either.  It seems like none of the UI stuff is happening in here.  BTW,
NSLog(@"%@", [NSThread isMainThread]?@"IS MAIN":@"IS NOT");

prints IS MAIN.
The image that is in there will stick around until the new animation frames are all in there (1-2 seconds) and they start animating
This is all being run from a subclass of UIView with the UIImageView as a subview.
- (void)loadItem:(StructuresItem *)item{

    self.imageView.animationImages = nil;
    self.imageView.image = nil;

    [self.spinner startAnimating];

    self.item = item;

    if (item.frameCount.intValue ==1){
        self.imageView.image = [item.frames objectAtIndex:0];
        self.imageView.animationImages = nil;
    }else {
        [self.imageView removeFromSuperview];

        self.imageView =[[UIImageView alloc] initWithFrame:self.bounds];
        [self addSubview:self.imageView ];
        if( self.imageView.isAnimating){
            [self.imageView stopAnimating];
        }
        self.imageView.animationImages = item.frames;
        self.imageView.animationDuration = self.imageView.animationImages.count/12.0f;

        //if the image doesn't loop, freeze it at the end
        if (!item.loop){
            self.imageView.image = [self.imageView.animationImages lastObject];
            self.imageView.animationRepeatCount = 1;
        }
        [self.imageView startAnimating];
    }

    [self.spinner stopAnimating];

}

My ignorant assessment is that something isn't being redrawn once that image is set to nil.  Would love a hand.

A: What I have found is not an answer to the question, but rather a much better approach to the problem.  Simply, use NSTimer instead of animationImages.  It loads much faster, doesn't exhaust memory and is simpler code.  yay!
Do this:
-(void)stepFrame{
    self.currentFrameIndex =   (self.currentFrameIndex + 1) % self.item.frames.count;
    self.imageView.image = [self.item.frames objectAtIndex:self.currentFrameIndex];
}

and this
-(void)run{
    if (self.item.frameCount.intValue>1){
        self.imageView.image = [self.item.frames objectAtIndex:self.currentFrameIndex];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1/24.0f target:self selector:@selector(stepFrame) userInfo:nil repeats:YES];
    }else{
        self.imageView.image = [self.item.frames objectAtIndex:0];
    }
}


text:
Q: Angular 2 i18n issue I have some issues with the i18n translation in Angular 2.
I have set up an initial app with the Angular cli, added the i18n text to the header, but when I run ./node_modules/.bin/ng-xi18n I'm getting the following error
TypeError: compiler.HtmlParser is not a constructor
    at Function.Extractor.create (C:\Users\Morten\workspace\translate\node_modules\@angular\compiler-cli\src\extractor.js:57:54)
    at extract (C:\Users\Morten\workspace\translate\node_modules\@angular\compiler-cli\src\extract_i18n.js:18:43)
    at Object.main (C:\Users\Morten\workspace\translate\node_modules\@angular\tsc-wrapped\src\main.js:30:16)
    at Object.<anonymous> (C:\Users\Morten\workspace\translate\node_modules\@angular\compiler-cli\src\extract_i18n.js:46:9)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
Extraction failed

The versions I'm using are:
angular-cli: 1.0.0-beta.17
node: 6.9.1
os: win32 x64

Any idea how to fix this?


text:
Q: Highcharts 4.1.1 adding a severe drop shadow to data labels if you specify a font color I've noticed that the latest version of Highcharts (v.4.1.1) is adding severe drop-shadows to data labels if you change the font color.
For example - Here is the jsfiddle for the bar chart demo:
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/bar-basic/
Here is the exact same code, but with one change - the addition of a color parameter for the data label:
plotOptions: {
    bar: {
        dataLabels: {
            color: '#999',
            enabled: true
        }
    }
}

You can see the result here: http://jsfiddle.net/wgLnuft5/
This makes the labels effectively unreadable.
Can you prevent this, while still specifying a data label color?

A: Yes, you can remove the shadow completely, or specify a specific shadow color instead.
Removing the shadow (by overwriting the default textShadow style) (JSFiddle):
plotOptions: {
    bar: {
        dataLabels: {
            color: '#E0E0E0',
            enabled: true,
            style: {
                textShadow: ''
            }
        }
    }
}

Setting a specific textShadow color (JSFiddle):
plotOptions: {
    bar: {
        dataLabels: {
            color: '#E0E0E0',
            enabled: true,
            style: {
                textShadow: '0 0 6px #FF3399, 0 0 3px #FF3399'
            }
        }
    }
}

The default value for the textShadow is (API reference):
"textShadow": "0 0 6px contrast, 0 0 3px contrast"

The reason your specific color value is problematic is that when the color is set to contrast it tries to get the contrasting color of the text color. In this particular case the contrasting color is really similar to the text color, which makes it unreadable.
According to the API this style has been in use since version 4.1.0 of Highcharts.


text:
Q: loadComplete event gets fired on each filter operation in jqGrid? According to jqGrid wiki page, "This event is executed immediately after every server request."
In my grid, I've a filter toolbar on top.
$(table_data_obj).jqGrid('filterToolbar', {stringResult:true, searchOnEnter:true, autosearch:true, defaultSearch:'cn'});

and loadComplete function like:
loadComplete: function(data) {
 data_processing(data);
}

Whenever, I filter grid data locally (no new server request), data_processing(data) is being called. And I do not want this behavior. How can I make sure that data_processing(data) gets called only with new server requests.
Edit
I want to do some data processing, everytime new data is fetched from server. Is there a better place for that ?

A: You don't posted the jqGrid definition and not describes why you have sometime data from the server and sometime locally. I suppose that you use loadonce:true option and sometime reset datatype parameter of jqGrid to the original value 'json' or 'xml' if you need to reload data from the server. If it is your case I would recommend you to test whether the datatype parameter are 'local' or not. You can use either the if like if ($("#list").jqGrid('getGridParam','datatype') !== 'json') {/* local data */} or use just $("#list")[0].p.datatype instead of $("#list").jqGrid('getGridParam','datatype').  If the data are loaded from the server the datatype will be 'json' (or 'xml'). After processing of loadComplete event the datatype will be changed to the 'local' if you use loadonce:true option.

A: use firebug to watch the request to server. check params, u'll get idea which values are being posted. use alerts in events to figure out the specific event throwing server request


text:
Q: Displaying and switching between ViewControllers in another ViewController I'm basically trying to create a custom UITabBarController since I need some specific functionality. The TabBar itself is done and working, but I don't quite know how to display ViewControllers in this CustomTabBarViewController itself.
Assuming i have the following method:
func tabSelected(_ index: Int) {}

and  knowing the height of my TabBar through tabbar.frame.size, how do I instantiate two ViewControllers above the TabBar and switch between them when the tabSelected method is called? A transition animation would be even nicer, but not really necessary.
NOTE: my TabBar doesn't inherit from UITabBarController, only from the regular UIViewController, to avoid further confusion.

A: Here I created sample project:
CustomTabBarViewController

*

*You should have container view for child ViewControllers

*Then you should have array with embed ViewControllers

*You should call method in
CustomTabBarViewController which change ViewController inside
container view to ViewController from array of VCs at index which you pass as parameter of this method

Start with declaring outlet collection for your TabBar buttons and also get reference for container view where your ViewControllers will be showed
@IBOutlet var tabBarButtons: [UIButton]!
@IBOutlet weak var container: UIView!

then create array for your tab bar items
var items: [UIViewController]?

next create lazy variables for your controllers
private lazy var aVC: A = {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    return storyboard.instantiateViewController(withIdentifier: "a") as! A
}()

private lazy var bVC: B = {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    return storyboard.instantiateViewController(withIdentifier: "b") as! B
}()

.... this can be simplified by creating method which returns ViewController depending on VC's identifier
After that append ViewControllers to your items array and also each add as child of your TabBarViewController
override func viewDidLoad() {
    super.viewDidLoad()
    items = [aVC, bVC]
    items!.forEach { addChild($0) }
}

continue with declaring method for setting ViewController
private func setViewController(_ viewController: UIViewController) {
    items!.forEach { $0.view.removeFromSuperview(); $0.willMove(toParent: nil) }
    container.addSubview(viewController.view)
    viewController.view.frame = container.bounds
    viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    viewController.didMove(toParent: self)
}

now add action for your tab bar buttons and get index of button. Then with this index call your tabSelected method
@IBAction func buttonPressed(_ sender: UIButton) {
    if let index = tabBarButtons.index(of: sender) {
        tabSelected(index)
    }
}

inside tabSelected set VC from items depending on index of sender tab bar button
func tabSelected(_ index: Int) {
    if let item = items?[index] {
        setViewController(item)
    }
}

finally in viewDidLoad set first item
override func viewDidLoad() {
    ...
    tabSelected(0)
}

Now you can fully customize your ViewController and make other epic stuff which you know from UITabBarController

A: Here's another approach:
1. In your CustomTabBarViewController define an array to hold the ViewControllers:
var viewControllers: [UIViewController]

Instantiate the view controllers and add them to the array:
// If you're not using storyboard:
let homeViewController = HomeViewController()
// If using storyboard:
let searchViewController = storyboard.instantiateViewController(withIdentifier: "SearchViewController")

viewControllers = [homeViewController, searchViewController, ...]

2. Define a variable to keep track of the tab button that is selected:
var selectedIndex: Int = 0

3. Implement your tabSelected method like so. I've explained each line in code:
func tabSelected(_ index: Int) {
    let previousIndex = selectedIndex

    selectedIndex = index

    // Use previousIndex to access the previous ViewController from the viewControllers array.
    let previousVC = viewControllers[previousIndex]

    // Remove the previous ViewController
    previousVC.willMove(toParentViewController: nil)
    previousVC.view.removeFromSuperview()
    previousVC.removeFromParentViewController()

    // Use the selectedIndex to access the current ViewController from the viewControllers array.
    let vc = viewControllers[selectedIndex]

    // Add the new ViewController (Calls the viewWillAppear method of the ViewController you are adding)
    addChildViewController(vc)
    vc.view.frame = contentView.bounds

    // contentView is the main view above your tab buttons
    contentView.addSubview(vc.view)

    // Call the viewDidAppear method of the ViewController you are adding using didMove(toParentViewController: self)
    vc.didMove(toParentViewController: self)
}


text:
Q: Переопределить страницу добавления в админ-панели Django Мне нужно добавить на страницу js-скрипт, который будет рисовать и удалять HTML-элемент. Нужно, чтобы, когда я выбирал элемент в выпадающем списке, рисовался другой выпадающий список или, наоборот, исчезал. Я знаю, как переопределять страницы в Django, но не могу найти нужную, которая отвечает за добавление новых объектов. Помогите найти её.

A: Если вы используете Django Debug Toolbar, то вы можете просто перейти на нужную страницу админ-панели и во вкладке шаблоны посмотреть откуда загружается страница.
После того как вы нашли где находится эта страница (наиболее вероятно, что путь следующий venv/Lib/site-packages/django/contrib/admin/templates/admin/base_site.html) :
По сути, вы можете внести изменения прямо в этот файл и это будет работать.
Но обычно для более качественной архитектуры приложения все файлы сформированные Django для админ-панели оставляют нетронутыми и делают следующим образом:

*

*В корне проекта создаем папку templates.

*В этой папке templates создаем подкаталог admin

*В файле settings.py в переменной TEMPLATES в поле DIRS прописываем путь к нашему шаблону: 'DIRS': [os.path.join(BASE_DIR, 'templates')]
Теперь, если в этом подкаталоге разместить файл base_site.html, то он уже будет переопределять файл, который использует Django по дефолту.
Также дополнительная полезная информация:
Файл base_site.html расширяет файл base.html ({% extends "admin/base.html" %}), это значит, что в нем вы можете переопределить некоторые стили, которые используются в base.html прямо внутри файла base_site.html, например подгрузить ваш css файл со стилями.
В интернете можно найти много различных ресурсов, которые предоставляют измененный вид админки, который как раз получается за счет переопределения файла стилей CSS.
Выглядит это так:
{% load static %}
{% block extrastyle %}
<link rel="stylesheet" href="{% static 'css/admin.css' %}">
{% endblock %}

Этот файл уже помещается в каталоге static вашего приложения, а не проекта.
Подробно со всеми нюансами это написано в документации, если остались вопросы, то советую ознакомиться.


text:
Q: Show SKU on cart and checkout pages in Woocommerce 3 I would like to display SKU on cart (Under product column ) and checkout page.
I searched SO, but all answers are for old versions of WooCommerce and non of them is for 3.x.
How can I show SKU on cart and checkout pages in Woocommerce 3?

A: You'll need to do some template overrides.
Cart
Copy plugins/woocommerce/templates/cart/cart.php into your theme file at my_theme/woocommerce/cart/cart.php if it isn't already there. Then add the following at approx line #85
// Meta data
//  (this is already in cart.php; look for it for where to place the next snippet)
echo WC()->cart->get_item_data( $cart_item );

// Add SKU below product name
if ( !empty($_product->get_sku()) ) { ?>

    <?php echo "SKU: ". $_product->get_sku(); ?>

<?php }

Checkout
Copy plugins/woocommerce/templates/checkout/review-order.php into your theme file at my_theme/woocommerce/checkout/review-order.php if it isn't already there. Then add the following at approx line #43
<?php
//  (this is already in review-order.php; look for it for where to place the next snippet)
echo WC()->cart->get_item_data( $cart_item ); ?>

<?php
// Add SKU below product name
if ( !empty($_product->get_sku()) ) { ?>

    <?php echo "SKU: ". $_product->get_sku(); ?>

<?php } ?>

A: 2021 Update
You can do it with a custom unction hooked in woocommerce_cart_item_name action hook, this way:
// Display the sku below cart item name
add_filter( 'woocommerce_cart_item_name', 'display_sku_after_item_name', 5, 3 );
function display_sku_after_item_name( $item_name, $cart_item, $cart_item_key ) {
    $product = $cart_item['data']; // The WC_Product Object

    if( is_cart() && $product->get_sku() ) {
        $item_name .= '
'. $product->get_sku() . '';
    }
    return $item_name;
}

// Display the sku below under cart item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'display_sku_after_item_qty', 5, 3 );
function display_sku_after_item_qty( $item_quantity, $cart_item, $cart_item_key ) {
    $product = $cart_item['data']; // The WC_Product Object

    if( $product->get_sku() ) {
        $item_quantity .= '
'. $product->get_sku() . '';
    }
    return $item_quantity;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce 3+. You will get:

And

Related similar: How to Show SKU with product title in Order received page and Email order

A: You can do it with this way:
/**
 * @snippet       Show SKU @ WooCommerce Cart
 * @author        Khalid Almallahi
 */

add_action( 'woocommerce_after_cart_item_name', 'abukotsh_sku_below_cart_item_name', 11, 2 );

function abukotsh_sku_below_cart_item_name( $cart_item, $cart_item_key ) {
    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    $sku = $_product->get_sku();
    if ( ! $sku ) return;
    echo '
SKU: ' . $sku . '
';
}


text:
Q: Powershell Script using for each to export only Valid AD Users to csv and suppress Users it cannot find in AD Good day all, I'm trying to write a script that will check if a User is valid and export the results to a .csv file. I'm using the "for each"  and erroraction -silentlycontinue cmdlet to check a list of Users from a .csv file and then verify on the Microsoft Teams admin center if that is a Valid User.
The problem I'm having is if I add the "$errorActionpreference" cmdlet which suppresses errors (or Users Not Found on Screen) the results in the CSV File are empty, If I remove the $errorAction cmdlet (hashed out in the script below), then it works fine by exporting the valid Users BUT it spits out a lot of errors on the screen.
The scripts just need to suppress error messages for invalid Users, Move to the next User in the csv file, and finally export the results of the valid Users to another csv file.
$path = Read-Host -Prompt "`nEnter the path of .csv file:"
if (Test-Path -Path $path) { break }
Write-Host "Wrong file or path specified. Please enter the correct
path to file!" -ForegroundColor Red

Write-Host "File has been located in the path specified!" -
ForegroundColor Green
$CsvFilePath = Import-CSV -Path $path

# $ErrorActionPreference = "silentlycontinue"

     $results = foreach ($Users in $CsvFilePath) {
     $User = $Users.UserPrincipalName
     Get-CsOnlineUser $User | Select-Object  UserPri*, LineURI,
     TeamsUpgradeE*,IsSipEnabled, Enterprise*,
    @{l="AssignedPlan";e={$_.AssignedPlan
     - join "; "}}, @{l="FeatureTypes";e={$_.FeatureTypes -join ";
    "}}
     }
    # $ErrorActionPreference = "silentlycontinue

  #Export Results: Prompt for Path, If file does not exist, create it!#
  $resultspathfilelocation = Read-Host -Prompt "`nEnter file path
  to export results of
  the Post Checks: "
  $FileName = "$resultspathfilelocation"
    if(Get-Item -Path $FileName -ErrorAction Ignore){
      Write-Host "File found in directory specified!"
      }
     else{
      New-Item -Verbose $FileName -ItemType File
     }
   $results | Export-Csv $resultspathfilelocation

A: Instead of trying to ignore the errors, why not just handle them properly?
$Results = foreach ($Users in $CsvFilePath) {
    Try {
        $User = $Users.UserPrincipalName
        $ThisUser = Get-CsOnlineUser $User -ErrorAction Stop
    # Output as custom object
        [pscustomobject]@{UPN = $User
                    TeamsUpgradeEffectiveMode = $ThisUser.TeamsUpgradeEffectiveMode
                    IsSipEnabled = $ThisUser.IsSipEnabled
                    AssignedPlan = ($ThisUser.AssignedPlan -join "; ")
                    FeatureTypes = ($ThisUser.FeatureTypes -join "; ")
                    Error = ''}
    }
    Catch {
    # User not found or error, output object with blank fields except for error
        [pscustomobject]@{UPN = $User
                    TeamsUpgradeEffectiveMode = ''
                    IsSipEnabled = ''
                    AssignedPlan = ''
                    FeatureTypes = ''
                    Error = $_.Exception.Message}
    }
}


text:
Q: Pandas: How to convert rows into one string? I have the following Pandas DataFrame that I want to convert into a concatenated string after iterating through but with each on new line.
Input:
    str_col
0      This
1        is
2       one
3  sentence

Output:
This
is
one
sentence

Code:
import pandas as pd

data = {"str_col" : ["This", "is", "one", "sentence"]}
df = pd.DataFrame(data)

A: df.to_string(header=False, index=False, index_names=False)


text:
Q: Provide value to JSON's attribute I have a JSON structure inside my code, I would like to pass a value to one of the attributes. Problem is I do not know how to do this? Since it is one whole string in C#, what is the possible way to achieve this?
For example, I want to pass the string appName to the JSON's AppName. How do I do this?
IEnumerator Start(){
  var appName = "Testing001";

  var json = @"{
        'values': {
        'AppName': '',
        'Time': '23:15',
        }
            }";

        var jsonBytes = Encoding.UTF8.GetBytes (json);

        using (var www = new UnityWebRequest (url, "POST")) {
            www.uploadHandler = new UploadHandlerRaw (jsonBytes);
            www.downloadHandler = new DownloadHandlerBuffer ();
            www.SetRequestHeader ("Content-Type", "application/json");
            www.SetRequestHeader ("Accept", "text/plain");

            yield return www.SendWebRequest ();

            if (www.isNetworkError || www.isHttpError) {
                Debug.Log (www.error);
            } else {
                Debug.Log (www.downloadHandler.text);
                Debug.Log (www.error);
            }
        }

    }
}

A: Disclaimer I'm not familiar with the peculiarities of Unity
So you want to create some JSON using variable values do you?
As others (and myself) have said in the comments, you should never create JSON manually as it is so easy to make a small mistake and end up with invalid JSON.
You will either want to use rigid model classes, or in a pinch, an anonymous type.
var appName = "Testing001";

// create our model as an anonymous type using the `appName` variable value.
var model = new {
    values = new {
        AppName = appName,
        Time = "23:15"
    }
};

// Generate valid JSON
var json = JsonSerializer.Serialize(model);

The resulting, valid, JSON is
{"values":{"AppName":"Testing001","Time":"23:15"}}

As you see, property names and strings have double quotes and AppName has the  desired value.
UPDATE - Using A Model Class
If, for whatever reason, you need/have a model class instead of an anonymous type, you should instantiate that with the necessary values and pass that to the serializer...
Given the model classes MyModel and MyModelValues
using System;

[Serializable]
public class MyModel
{
    [SerializeField]
    public MyModelValues values;
}

[Serializable]
public class MyModelValues
{
    [SerializeField]
    public string AppName;

    [SerializeField]
    public string Time;
}

Then you can substitute the creation of model using the model classes.
// create our model as an anonymous type using the `appName` variable value.
var model = new MyModel
{
    values = new MyModelValues
    {
        AppName = appName,
        Time = "23:15"
    }
};


text:
Q: Finding more than one occurence using a regular expression Is it possible to capture all of the information in href using one regular expression?
For example:

book1

book2

book3

I want to get book, book-2 and book-3.

A: Short and simple:
html = '

book1

book2

book3

'
result = re.findall("href='(.*?)'", html)

EXPLANATION:
Match the character string "href='" literally (case sensitive) «href='»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character "'" literally «'»

A: You can do that with the following regex:
<a id='\d+' href='([\w-]+)'

import re

s = '''

book1

book2

book3

'''

>>> print re.findall(r"<a id='\d+' href='([\w-]+)'", s)
['book', 'book-2', 'book-3']

A: Using custom class extends HTMLParser:
class MyHTMLParser(HTMLParser):
    def __init__(self,*args,**kw):
        super().__init__(*args,**kw)
            self.anchorlist=[]

    def handle_starttag(self,tag,attrs):
        if tag == 'a':
            for attribute in attrs:
                if attribute[0] == 'href':
                    self.anchorlist.append(attribute[1])

This will put all of the URLs in anchorlist.
By the way, it's in Python 3.x


text:
Q: AdMob: is Test Device Id included in AdRequest? I use this code to build an AdRequest:
AdRequest request = AdRequest.Builder().
addTestDevice(AdRequest.DEVICE_ID_EMULATOR).
addTestDevice(id1).
addTestDevice(id2).
build();

Are those device Id's transmitted to ad server every time an ad request is executed?
(Or are they only used locally in order to decide whether live ads or test ads are requested?).

A: They are only used locally. You will see test ads only when you add test device, if you remove the code of adding test device before calling build() the ad will load normal.
Admob first generates your device id before loading ad, and if your device id is listed in test devices then test ad is loaded.


text:
Q: execlp fails if I don't flush the buffer I'm trying to run a command in a child process in C:
int main()
{
    if (fork()) {
        wait(0);
    } else {
        fflush(stdout);
        execlp("ls", "ls");
        printf("Command not found: \"%s\"\n", "ls");
    }
}

My understanding is that the call to fork() will create a clone of the process (the child). The parent here will wait(0), because fork() doesn't return null, and wait for the child process to be done.
I understand the child process' image essentially "becomes" ls after the call to execlp("ls", "ls");.
At this point, if ls exists in the path, the ls program takes over and the printf() on line 8 should never be called.
This works as expected with the snippet I posted above, and I get the output of ls in the current directory.
However if I comment out fflush(stdout), the printf() gets called!
Command not found: "ls"

Why does the printf() get called if I comment out fflush(stdout)?

A: the following proposed code:

*

*cleanly compiles

*performs the desired functionality

*properly checks for errors

*for any error, properly passes 'your' error message and the text reason the system thinks the error occurred to stderr

*passes a valid parameter list to execlp()

*documents why each header file is included

*uses a valid signature, as defined in the C programming language standard, for the main() function

*does not make assumptions about the value returned from fork()

*follows the axiom: only one statement per line and (at most) one variable declaration per statement.
and now, the proposed code:
#include <stdio.h>    // perror(), printf()
#include <stdlib.h>   // exit(), EXIT_FAILURE
#include <unistd.h>   // execlp(), fork(), pid_t
#include <sys/wait.h> // wait()

int main( void )
{
    pid_t pid = fork();

    if ( pid < 0 )
    {   // then error
        perror( "fork failed" );
        exit( EXIT_FAILURE );
    }

    if( pid == 0 )
    {   // then child
        execlp("ls", "ls", NULL );
        perror( "execlp failed" );
        exit( EXIT_FAILURE );
    }

    else
    {   // then parent
        wait(0);
    }
}


text:
Q: How to deploy with PM2 and Grunt I am using angular-fullstack for my application. I want to start my apps using pm2.
Angular-fullstack starts prodcution mode by grunt serve:dist, it runs several tasks including setting environment variables.
PM2 seems to start an application with a js file. like pm2 start server.js
My question is:
How do I use PM2 to start my application in production mode with Grunt?
I know my main application file is server/app.js, but I cannot simply do pm2 start server/app.js, because those environment variables are not properly set.

A: I finally got pm2 work with grunt. just use /usr/bin/grunt as starting script and pm2 works well, the argument is passed by the args section.
Here is my ecosystem.json config file. (I am using pm2 deploy)
{
  "apps" : [{
    "name"      : "myapp",
    "script"    : "/usr/bin/grunt",
    "args"        : "['serve:dist']"
  }],
  "deploy" : {
    "production" : {
      "user" : "user-name",
      "host" : "server-address",
      "ref"  : "origin/develop",
      "repo" : "git-url",
      "path" : "/opt/deploy",
      "post-deploy" : "npm install && bower install && pm2 startOrRestart ecosystem.json --env production"
    }
  }
}

A: An alternative is to launch grunt directly using pm2:
cd /path/to/fullstack
pm2 start grunt --name website -- serve


text:
Q: modular cipher d is negative how do I make it positive? my e=131 and p=18181
to find by d I must solve the linear diophantine equation 131*d=1 mod 18180
LDE to solve:
131d+18180y=1
after solving this I get d=-1249 and y=9
the problem is if I take my cipher text C which is say 9805 and try to decipher it with d=-1249 i get a massive error because d has to be positive to use it for deciphering. How can I find a d or make this d positive so I can use it for deciphering?
I think I got the answer, I need to write my solution for d,y in the form which gives all solutions and plug in a number and find a positive d that works

A: Let $(x_0,y_0)$ be a particular solution of the linear Diophantine equation
$$131x+ 18180y=1.$$
Then all integer solutions are given by
$$x=x_0+18180t,\qquad y=y_0-131t,$$
 where $t$ ranges over the integers.
In your  problem,  the variable I called $x$ is called $d$. You want the "multiplier" of $d$ to be positive. Take, for example, $t=1$.
Remark: In general, suppose that you have found a solution in $(x_0,y_0)$ in integers, not necessarily positive, of the  equation $ax+by=k$. Let $d$ be the greatest common divisor of $a$ and $b$, and let $a=da'$, $b=db'$. Then all integer solutions of $ax+by=k$ are given by $x=x_0+b't$, $y=y_0-a't$, where $t$ ranges over the integers. Thus if you have found one solution, all the solutions are fairly straightforward to describe.

A: Remember that you are not solving an equation but a congruence, so when you write the answer $d=-1249$ what you really meant to write was $d\equiv -1249\pmod{18180}$. Do you know how to get a positive $d$ satisfying that congruence?


text:
Q: Updating cocoapods to latest version doesn't do anything I'm currently using cocoapods 0.26.2 (output from pod --version). I want to update it to 0.29.0.
I ran sudo gem update which didn't appear to do anything with the cocoapods gem. So, following suggestions on cocoapods.org I tried:
sudo gem uninstall cocoapods
sudo gem install cocoapods

That did appear to install cocoapods 0.29.0. However, when I run pod --version it still tells me I'm on 0.26.2.
$ which pod
/usr/bin/pod

I tried renaming /usr/bin/pod to something else then trying the uninstall / reinstall again, but it doesn't put a pod binary in /usr/bin. It DOES however put a pod binary in /usr/local/Cellar/ruby/2.0.0-p247/bin. Do I really need to add that odd and version hard coded path to my $PATH?? Why did cocoapods previously install into /usr/bin?
My gem environment:
RubyGems Environment:
  - RUBYGEMS VERSION: 2.1.9
  - RUBY VERSION: 2.0.0 (2013-06-27 patchlevel 247) [x86_64-darwin12.5.0]
  - INSTALLATION DIRECTORY: /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /usr/local/Cellar/ruby/2.0.0-p247/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/Cellar/ruby/2.0.0-p247/bin
  - SPEC CACHE DIRECTORY: /Users/michael/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-12
  - GEM PATHS:
     - /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0
     - /Users/michael/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/bin
     - /usr/local/sbin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/bin
     - /opt/X11/bin

I'm running OS X 10.9.1.

A: Ok, this answer about ruby and homebrew solved the problem. Had to add /usr/local/opt/ruby/bin to my $PATH. Not sure how I ever had a version of the pod binary in /usr/bin, it's possible I used the OS X provided version of ruby to install the earlier version of cocoapods, not the version installed by homebrew.


text:
Q: Can I use Telerik Metro Controls Beta in a production app? So far they're the only people I can find that are doing a chart control...
What happens when the beta expires?  How does it expire?  (Does it expire?).  They look great but there is no pricing information or expiry information.

A: Here is a direct quote from the EULA:
"You may distribute the Programs as embedded in Your Integrated Products to Your end-users only pursuant to an end-user license that meets the requirements of this Section."
So, yes, you can ship Apps built with Telerik Windows 8 Controls Beta to the Store.

A: "Beta," by definition, suggests not ready for production use.
There are at least a couple of things you should think about before moving forward:

*

*Does the license agreement for the controls allow use in a production app (you did read the license, right?)

*Are you willing to risk the possibility that the app might suddenly stop working for any and all users who have downloaded it, until such time as you replace the controls with working versions (and get the updated version of your app submitted to the store)?

As long as the controls fit the Windows 8 app design, and don't cause performance or crashing issues, they may not have any impact on whether or not the app gets through certification.
But the larger issue is one of risk. Betas are for testing. IMO, unless the beta includes a "go-live" license, you should probably stick with using beta software for evaluation and testing only.
To be clear, that's no knock on Telerik's beta quality (or anyone else's, for that matter). Just a reminder that beta software isn't finished yet.


text:
Q: Calling Win32 EnumThreadWindows() in C# I'm trying to get a call to EnumThreadWindows working, but I always get a Wrong Parameter-Error, although my code is nearly the same as this example on pinvoke.net.
I don't know why this doesn't work:
public static IntPtr FindMsgBoxFrom(IntPtr MainHWND)
{
    SetLastError(0);
    uint ThreadID = GetThreadID(MainHWND);
    EnumThreadWindows(ThreadID, new WNDENUMPROC(decoder.FindMsgBox), IntPtr.Zero);
    int last = Marshal.GetLastWin32Error();
    if (last != 0)
        MessageBox.Show("EnumThreadWindows-Error:\n" + GetLastErrorString());

    return MSGHWND;
}

and this is decoder.FindMsgBox:
public static bool FindMsgBox(IntPtr hwnd, IntPtr lparam)
{
    if (IsMsgBox(hwnd))
    {
        MSGHWND = hwnd;
        return false;
    }
    else
        return true;
    }
}

What's the problem with this?

A: I believe your EnumThreadWindows call should work fine, the problem seem to be in the
uint ThreadID = GetThreadID(MainHWND);

call; it looks like you're trying to pass window handle in there and this is not exactly what it expects to get from you, more details here: http://msdn.microsoft.com/en-us/library/ms683233(VS.85).aspx
I've tried to change the line above to the following code:
[DllImport("kernel32.dll")]
static extern uint GetCurrentThreadId();

<...>

uint ThreadID = GetCurrentThreadId();

and the rest of your code worked fine for me
Also if you're looking to get thread ID for the given window handler, the code below might give you an idea on how to do it:
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

public static uint GetThreadIdForForegroundWindow()
{
   IntPtr hwnd = GetForegroundWindow();
   return (hwnd!=IntPtr.Zero) ? GetWindowThreadProcessId(hwnd, IntPtr.Zero) : 0;
}

<...>

uint ThreadID = GetThreadIdForForegroundWindow();

regards


text:
Q: To replace internet acronyms in a dataframe using dictionary I'm working on a text mining project where I'm trying to replace abbreviations, slang words and internet acronyms present in text (In a dataframe column) using a manually prepared dictionary.
The problem I'm facing is the code stops with the first word of the text in the dataframe column and does not replace it with lookup words from dict
Here is the sample dictionary and code I use:
abbr_dict = {"abt":"about", "b/c":"because"}

def _lookup_words(input_text):
    words = input_text.split()
    new_words = []
    for word in words:
        if word.lower() in abbr_dict:
            word = abbr_dict[word.lower()]
        new_words.append(word)
        new_text = " ".join(new_words)
        return new_text
df['new_text'] = df['text'].apply(_lookup_words)

Example Input:
df['text'] =
However, industry experts are divided ab whether a Bitcoin ETF is necessary or not.

Desired Output:
df['New_text'] =
However, industry experts are divided about whether a Bitcoin ETF is necessary or not.

Current Output:
df['New_text'] =
However

A: You can try as following with using lambda and join along with split:
import pandas as pd

abbr_dict = {"abt":"about", "b/c":"because"}

df = pd.DataFrame({'text': ['However, industry experts are divided abt whether a Bitcoin ETF is necessary or not.']})

df['new_text'] = df['text'].apply(lambda row: " ".join(abbr_dict[w]
                             if w.lower() in abbr_dict else w for w in row.split()))

Or to fix the code above, I think you need to move the join for new_text and return statement outside of the for loop:
def _lookup_words(input_text):
    words = input_text.split()
    new_words = []
    for word in words:
        if word.lower() in abbr_dict:
            word = abbr_dict[word.lower()]
        new_words.append(word)
    new_text = " ".join(new_words) # ..... change here
    return new_text # ..... change here also
df['new_text'] = df['text'].apply(_lookup_words)


text:
Q: jQuery doesn't work. Why? You can find the website I am building at here.
There is a menu.js with some jQuery code. It should color the parts of the menu (<li>) when the mouse is hovered over that part of the menu (this). But it appears not to work. I linked the file that is necessary for jQuery (jQuery.min.js) to my home.php and I did the same with the jquery.animate-colors.js, but it won't work. Does anybody know why?
PS: if you look at the style.css and remove the /* and */ around the ul#avmenu a:hover{} part, you will see what should happen, but I want to use jQuery because I want a smooth animation.

A: that is beacuse you are loading animate.js first and jquery second.. and since animate.js depends on jquery.. your error says jQuery is not defined...load jquery.js first
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"</script>
<script src="jquery.animate-colors.js"></script>

A: In your jQuery code change ('this') to (this) without quotes.

A: You're loading the animate-colors js file before you're loading jquery, thus the animate colors can't access Jquery functions...
So, instead of:
<script src="jquery.animate-colors.js">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">

make it like this:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script src="jquery.animate-colors.js">

You can debug that btw by looking at the Console tab in Firebug. When reloading the page, you can see a ReferenceError: jQuery is not defined is been given.

A: Got it! But there is another problem now. One of the li s in the menu has an class="active" atribute. In my css was a line of code which said that the one with the class active a different color had (no matter if it is a hover). Right now, my jQuery code takes over everything with ul#avmenu a, so the one with class="active" also reacts on a mouseover and is never the color it should be, not on mouseover and not without it. How do I exclude the ul#avmenu a.active at my jQuery (menu.js)?


text:
Q: How to do the same in JavaScript? I have this jQuery that automaticali calculate when is focus out of the field. I need to the the same this in JavaScript and to call the function after each page refresh. Now after each validations my calculation from the fields get lost.
<script language="javascript">
    $(function () {
        $(document).on("blur", "input[type=text]", function () {
            var imekontrolebase = $(this).attr('id');
            var ime = ($(this).attr('id')).substr(12, $(this).attr('id').length);
            var n = ime.indexOf("_");
            var red = ime.substr(n+1);

            var imekol1 = "txt_OBR_P_1_1_" + red;
            var imekol2 = "txt_OBR_P_1_2_" + red;
            var imekol3 = "txtKOL3_" + red;

            var txt_OBR_P_1_1 = parseFloat($('#' + imekol1).val().replace(/\,/g, '')) || 0
            var txt_OBR_P_1_2 = parseFloat($('#' + imekol2).val().replace(/\,/g, '')) || 0

            var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;

            if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
                txtKOL3 = $('#' + imekol3).val("");
            }
            else {
                var ukupnoID3 = ("" + txtKOL3).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "," });
                $('#' + imekol3).val(ukupnoID3);
            }
        })
    })
</script>

I need to create some function like this:
<script language="javascript">
    function startCalc() {
    }
</script>

And call it from server side after each validation.
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Script", "startCalc()", True)

A: If you want Vanilla JavaScript solution you can try this:
function startCalc() {
    var root = document.documentElement || document.body;
    root.addEventListener('blur', function(e) {
        var node = e.target;
        if (node.nodeName == 'input' &&
            node.getAttribute('type') == 'text') {
            var imekontrolebase = node.getAttribute('id');
            var ime = imekontrolebase.substr(12, imekontrolebase.length);
            var n = ime.indexOf("_");
            var red = ime.substr(n+1);

            var imekol1 = "txt_OBR_P_1_1_" + red;
            var imekol2 = "txt_OBR_P_1_2_" + red;
            var imekol3 = "txtKOL3_" + red;

            var txt_OBR_P_1_1 = parseFloat(document.getElementById(imekol1).value.replace(/\,/g, '')) || 0
            var txt_OBR_P_1_2 = parseFloat(document.getElementById(imekol2).value.replace(/\,/g, '')) || 0

            var txtKOL3 = txt_OBR_P_1_1 + txt_OBR_P_1_2;

            if (txtKOL3 === 0 || txtKOL3 === Infinity || isNaN(txtKOL3)) {
                txtKOL3 = document.getElementById(imekol3).value;
            }
            else {
                var ukupnoID3 = ("" + txtKOL3).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "," });
                document.getElementById(imekol3).value = ukupnoID3;
            }
        })

    });
}

basically

*

*$('#name') -> document.getElementById('name'); or

*document.querySelector('#name') that return single element or

*document.querySelectorAll('#name') that return array like object

*jqueryObject.val() -> htmlNode.value

*$(document).on('blur' -> node.addEventListener('blur' and you need to check for the correct node using event.target


text:
Q: all csv export data is in one column I have code of csv export,which is using by me but the problem is all data is exporting on csv in one column.but i need data must be column separated,

 <?php
 $results= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"));
 $column = array("name","cname","agency","phone");
  $writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
  $csv_export='';
  for($i = 0; $i < count($column); $i++)
  {
      $csv_export.= $writecolumn[$i]."\t" ;
  }
  $csv_export.= "\n";
  for($j = 0; $j < count($results); $j++)
  {
      for($i = 0; $i < count($column); $i++)
      {
   $csv_export.= $results[$j][$column[$i]]."\t";
      }
      $csv_export.= "\n";
  }

     $categoryname=$results[0]['cname'];
     $filename = $categoryname."-Category-Artist-Data.csv";
     header('Content-type: application/csv');
     header('Content-Disposition: attachment; filename='.$filename);
     echo $csv_export;
     exit;
    ?>

.

A: Use array_reduce, which reduces array to a single value, by applying function to each element, with initial value passed as third parameter, something like that:
$result= array(0=>array(name => "anil",agency=>"",phone=>"234235",cname=>"Atleta"),1=>array(name => "name_anil",agency=>"agency2",phone=>"234235",cname=>"Atleta_2"));
$csv_export = array_reduce($result, function($acc,$row) {
    foreach($row as $key => $value) {
        $acc .= $value;
        $acc .= "\t";
        }
    $acc .= "\n";
    return $acc;
    },
    "Nome do Artista\tCategoria\tAgencia\tTelefone\n")
$categoryname=$results[0]['cname'];
$filename = $categoryname."-Category-Artist-Data.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $csv_export;
exit;

A: Your code has delimiter (value separator) is 'tab' ('\t'). May be your CSV reading software need some configuration to start using 'tab' ('\t') as delimiter. I updated your code below and use ',' as delimiter. Microsoft Excel use ',' as default delimiter. Please try code below,

 <?php
                $results= array(0=>array('name' => "anil",'agency'=>"",'phone' =>"234235",'cname'=>"Atleta"),1=>array('name' => "anil",'agency'=>"",'phone'=>"234235",'cname'=>"Atleta"));
                $column = array("name","cname","agency","phone");
  $writecolumn = array("Nome do Artista","Categoria","Agencia","Telefone");
  $csv_export='';
  for($i = 0; $i < count($column); $i++)
  {
      $csv_export.= $writecolumn[$i]."," ;
  }
  $csv_export.= "\r\n";
  for($j = 0; $j < count($results); $j++)
  {
      for($i = 0; $i < count($column); $i++)
      {
   $csv_export.= $results[$j][$column[$i]].",";
      }
      $csv_export.= "\r\n";
  }

     $categoryname=$results[0]['cname'];
     $filename = $categoryname."-Category-Artist-Data.csv";
     header('Content-type: application/csv');
     header('Content-Disposition: attachment; filename='.$filename);
     echo $csv_export;
     exit;
    ?>