text:
Q: Get IP address of Android device using API I am trying to get the IP address of the android device using an API from ipify.  I tried using the API suggested in https://www.ipify.org/.  It is simple.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.ramesh.getipaddress">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

    </application>

</manifest>

import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public void onClick(View v) {

        Log.i("Test", "End");

        new networkingTask().execute();

        //getContents("http://localhost:8080");

        Log.i("Error", "Error1");
    }

}

 class networkingTask extends AsyncTask<String, String,String> {
    protected String doInBackground(String... urls) {
        //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

        //getContents("http://localhost:8080");

        getipify();

        return null;
    }

     public void getipify() {

        try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("https://api.ipify.org").openStream(), "UTF-8").useDelimiter("\\A")) {
            System.out.println("My current IP address is " + s);
        } catch (java.io.IOException e) {
            System.out.println("======");
            System.out.println(e);
            System.out.println("======");

        }

         Log.i("Test","====TEST====");
     }

}

For some reason it wont open the stream.  I get the error
java.lang.IllegalStateException: Could not execute method for android:onClick                                                                                at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
I have used this method in swift and it works just fine.  I have looked at all other methods but this appears easy.
Error section from Android Studio:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.ramesh.getipaddress, PID: 2381
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ramesh.getipaddress/com.example.ramesh.getipaddress.MainActivity}: android.os.NetworkOnMainThreadException
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                   Caused by: android.os.NetworkOnMainThreadException
                      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
                      at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
                      at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
Any help will be greatly appreciated.
Thanks
Ramesh

A: Going through your full code looks like your acitivty is crashing because you are attempting to perform a network call on the main thread. You must do the networking in a background thread. You can and should use async task to achieve this:
You code will look like this:
Update: For the second error: do this:
 // just make sure to replace button with the id of your button
 Button b = (Button) findViewById(R.id.button);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        new networkingTask().execute();
        }
    });

public void onClick(View v) {

        Log.i("Test", "End");
        Log.i("Error", "Error1");

new networkingTask().execute();

    }

//create a asynctask class:
private class networkingTask extends AsyncTask<String, String,String> {
     protected String doInBackground(String... urls) {
       //now call your ipify method which is doing the networking or calling a method that might be doing the networkign

        //getContents("http://localhost:8080");

                   getipify();

      return null;
     }

}


text:
Q: Recharts - Set domain without axis in BarCharts I'm currently using Recharts to implement our Bar Chart. Something like this.

const {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} = Recharts;

const data = [
  { name: "Page A", uv: 4270 },
  { name: "Page B", uv: 17 },
  { name: "Page C", uv: 2 },
  { name: "Page D", uv: 3 },
  { name: "Page E", uv: 1 },
  { name: "Page F", uv: 2 },
  { name: "Page G", uv: 1 }
];

const SimpleAreaChart = () => {
  return (
    <ResponsiveContainer>
      <BarChart
        layout="vertical"
        data={data}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <YAxis type="category" dataKey="name" />
        <XAxis type="number" domain={[0, 5000]} />
        <Tooltip />
        <Legend />
        <Bar dataKey="uv" fill="#82ca9d" />
      </BarChart>
    </ResponsiveContainer>
  );
};

const rootElement = document.getElementById("container");
ReactDOM.render(<SimpleAreaChart />, rootElement);
#container {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  width: 100%;
  height: 400px;
  background-color: #fff;
}
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
<script src="https://unpkg.com/recharts/umd/Recharts.min.js"></script>
<div id="container" />

I do not want to show XAxis.
But without XAxis, the maximum bar is just about 70% of the BarChart
I can not find any way to make the maximum bar to get about 90% of BarChart but setting domain in Axis.
Is there any way I can still set domain and not show XAxis?
Thanks in advance.

A: You can set hide in Axis component.
<XAxis type="number" domain={[0, 5000]} hide />

redpajama_set_name: RedPajamaStackExchange


text:
Q: What do I use as selector when styling dialog boxes? In CSS, I want to change the title bar color of a dialog box but it isn't working. This is the dialog box in html and the css.

     CSS
     #picture1Dialog.ui-dialog-titlebar{
     background-color: #f00;
     }

A:   #picture1Dialog{
      background-color: #f00;
  }

Right click on your element and use the inspect element tool to get more details about your Styles rules. Also we could use more details on what this is:
 .ui-dialog-titlebar

http://jsfiddle.net/CVEqr/

A: Your selector expects the ui-dialog-titlebar class to be added directly to the pictureDialog element. But the dialog is actually a DIV that wraps around your pictureDialog DIV, and the title bar is another DIV within it.
When you create the dialog, you can specify the class of that dialog, and then use that in your CSS:
$("#pictureDialog").dialog({
    dialogClass: 'picture-dialog',
    ...
});

Then you can use this CSS:
.picture-dialog .ui-dialog-titlebar {
    background-color: #f00;
}

A: Why don't you just use the ui-dialog-titlebar in selector?
 .ui-dialog-titlebar{
     background-color: #f00;
 }


text:
Q: React-Native run-android command cannot find Android Studio and SDK I am building a React-Native project on Mac OS. My Mac is Mac Mini which is using the new Apple M1 chip. I can build and run my project on iOS simulator using "react-native run-android" command. But when I run "react-native run-android" command, it is not working.
I downloaded and installed the Java JDK. When I type in "java -version" in the terminal, I can see the following output.
openjdk version "17" 2021-09-14 LTS
OpenJDK Runtime Environment Zulu17.28+13-CA (build 17+35-LTS)
OpenJDK 64-Bit Server VM Zulu17.28+13-CA (build 17+35-LTS, mixed mode, sharing)

Then I downloaded and installed the latest version of Android Studio. It is installed and Android SDK is located in the following path.
/Users/waihein/Library/Android/sdk

I have the following content in the ~/.hash_profile file.
export PATH="/usr/local/bin:$PATH"
export ANDROID_HOME=/Users/waihein/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:/Users/waihein/Library/Android/sdk/platform-tools/

Within my react-native project folder, when I run "react-native run-android", I got the following output.
* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/6.8/userguide/gradle_daemon.html
Process command line: /Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home/bin/java -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.invoke=ALL-UNNAMED --add-opens java.prefs/java.util.prefs=ALL-UNNAMED -Xmx2048m -Dfile.encoding=UTF-8 -Duser.country=GB -Duser.language=en -Duser.variant -cp /Users/waihein/.gradle/wrapper/dists/gradle-6.8-all/9emh0d32e025cam7aasxcw002/gradle-6.8/lib/gradle-launcher-6.8.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.8
Please read the following process output to find out more:
-----------------------
Unrecognized VM option 'MaxPermSize=512m'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

I tried using "sudo react-native run-android" too, I got the same error.
When I run "react-native doctor" command, I got the following output.

But I installed the Android studio correctly. What is wrong with my configuration or installation and how can I fix it?

A: Although the react native docs don't specify a range of JDK versions that work with RN, I personally haven't been able to get anything but OpenJDK8 to work. Try installing that and setting the JAVA_HOME environment variable to its path.
I think the package for it got renamed recently in Homebrew - you'd run 'brew install temurin8' now.


text:
Q: What does continuity of inclusion means? If $A,B,C$ are three spaces such that $A\subset B\subset C$ and $A$ is dense in $C$. Now my teacher said that the inclusion between three spaces are continuous and so you can directly say that $B$ is dense in $C$ .
When i asked  him why can't you directly conclude this, he said that the topologies are different and so you need the condition that the inclusions are continuous. I didn't understand what he meant by that?

A: Edit: Just to make things more precise, let's say that we're dealing with spaces $\langle A,\tau_A\rangle,$ $\langle B,\tau_B\rangle,$ and $\langle C,\tau_C\rangle,$ where $A\subseteq B\subseteq C$. In that case, you are quite correct that there is no need to know anything about the continuity of the inclusions. In fact, we don't even need to know anything at all about the topologies $\tau_A$ or $\tau_B$.
Given a topological space $\langle X,\tau\rangle$ and any $S\subseteq X$, observe that there is at least one $V\in\tau$ such that $S\cap V=\emptyset$--for example, $V=\emptyset$--and we denote/define the closure of $S$ in $\langle X,\tau\rangle$ by $$\text{cl}(S,X,\tau):=\bigcap\{X\smallsetminus V:V\in\tau,S\cap V=\emptyset\}.$$ This has the following properties (that you should verify):

(i) $S\subseteq\text{cl}(S,X,\tau)\subseteq X.$
(ii) $\text{cl}(S,X,\tau)$ is closed in $\langle X,\tau\rangle.$
(iii) If $F\subseteq X$ with $F$ closed in $\langle X,\tau\rangle$ and $S\subseteq F$, then $\text{cl}(S,X,\tau)\subseteq F$.

Putting (i)-(iii) together, it means that $\text{cl}(S,X,\tau)$ is the smallest subset of $X$ containing $S$ that is closed in $\langle X,\tau\rangle.$ Another property that you should verify is that $S\subseteq X$ is dense in $\langle X,\tau\rangle$ if and only if $\text{cl}(S,X,\tau)=X$.
By way of contradiction, suppose that $B$ is not dense in $\langle C,\tau_C\rangle,$ so that there is some $c\in C$ such that $c\notin\text{cl}(B,C,\tau_C),$ meaning by definition of $\text{cl}(B,C,\tau_C)$ that there is thus some $V_0\in\tau_C$ with $B\cap V_0=\emptyset$, such that $c\notin C\smallsetminus V_0$. Now, since $B\cap V_0=\emptyset$ and $A\subseteq B$, then $A\cap V_0=\emptyset$. But then by definition of $\text{cl}(A,C,\tau_C),$ we have that $$\text{cl}(A,C,\tau_C)\subseteq C\smallsetminus V_0,$$ so $c\notin\text{cl}(A,C,\tau_C),$ contradicting our assumption that $A$ is dense in $\langle C,\tau_C\rangle.$ Another way to approach it is to show that if $A\subseteq B\subseteq C$, then $\text{cl}(A,C,\tau_C)\subseteq\text{cl}(B,C,\tau_C),$ so if $A$ is dense in $\langle C,\tau_C\rangle,$ then $$C=\text{cl}(A,C,\tau_C)\subseteq\text{cl}(B,C,\tau_C)\subseteq C,$$ so $\text{cl}(B,C,\tau_C)=C$, as desired.

It is possible that, instead, your teacher meant that $A,B,C$ are spaces and that there exist injections $\iota_1:A\hookrightarrow B$ and $\iota_2:B\hookrightarrow C$, with $A$ densely imbedded into $C$ by $\iota_2\circ\iota_1$. That means that $\iota_2\circ\iota_1(A)$ dense in $C$, and that $\iota_2\circ\iota_1$ maps $A$ homeomorphically to $\iota_2\circ\iota_1(A)$, with the latter considered as a subspace of $\langle C,\tau_C\rangle.$ Since $$\iota_2\circ\iota_1(A)=\iota_2\bigl(\iota_1(A)\bigr)\subseteq\iota_2(B),$$ we can through the same sort of arguments conclude that $\iota_2(B)$ is dense in $C$, and we already know that $\iota_2:B\hookrightarrow C$ is an injection, but to be able to conclude that $B$ is densely imbedded into $C$, then we also need to know that $\iota_2$ is continuous (among other things). That may have been what was meant.

A: Any inclusion of sets $X\subseteq Y$ can be seen as an injective map $\iota: X\to Y$ (simply given by $\iota(x) = x$ which makes sense since $x$ is also an element of $Y$).
The condition mentioned then is that this map is continuous, ie that we have chosen a topology on the subset such that this holds (typically, we will pick the subset topology, since this will make it hold).

A: Cameron here made me realize that there are two valid answers to this question depending of which is your conceptual definition of density.
Let $X$ be a topologycal space
First definition:

A subspace $A$ of $X$ is called dense in $X$ if the closure of $A$ respect $X$ is all of $X$.

This definition probably use your teacher. In this case we need considering a subset $A'\subset X$ equipped with a subspace topology, namely, that the inclusion map between topological spaces $i:A'\to X$ be continuous. Let $A=i(A')$ and you must show that $\overline{i(A')}=X$ (closure respect $X$).
In this case your teacher is right.
Second definition:

A subset $A$ of $X$ is called dense in $X$ if the closure of $A$ respect $X$ is all of $X$.

This definition differs from the preceding only in a conceptual fact. Given the subset $A\subset X$. You only must to show that $\overline{A}=X$ (closure respect $X$). And you are right.

In practice both definitions bring same consequences and do not change any topological facts. All topology is the same in both cases since you can always identify a subset of a topological space with the respective induced subspace topology.

A: Teacher is right. If $A\subset B$ then $i_{A\to B}\colon A\to B$ is continuous iff $A$ is subspace of $B$.


text:
Q: Sql Pivot and Unpivot a newbie here..Actually I have a table in Oracle vw_summary as
Onum | Uacheck |  Uadesc  | AU11  |  AU12 | BD10  |
----------------------------------------------------------
 1   |   5.1   |  VENDOR  |  0    |   0   |    0  |

 2   |   5.2A  |  CUST    |  0    |   0   |    0  |

and I need data displayed as:-
Onum  |  PLant |   5.1 - VENDOR  |  5.2A - CUST
---------------------------------------------------

1     |   AU11   |   0             |   0

2     |   AU12   |   0             |   0

3     |   BD10   |   0             |   0

i.e. I need the columns AU11, AU12, BD10 to become rows of my Plant column
and each concatenation of UACHECK || UADESC TO BECOME ROWS.

A: Try this:
WITH T1 AS (SELECT *
             FROM vw_summary UNPIVOT (plantvalue
                             FOR plant
                             IN (AU11, AU12, BD10))),
     T2
        AS (SELECT UACHECK,
                   UADESC,
                   PLANT,
                   PLANTVALUE,
                   ROW_NUMBER () OVER (PARTITION BY UADESC ORDER BY UADESC)
                      AS NUM
              FROM T1)
SELECT *
  FROM t2 PIVOT (MIN (PLANTVALUE)
          FOR (UADESC, UACHECK)
          IN  ( ('VENDOR', '5.1') AS "5.1 - VENDOR",
              ('CUST', '5.2A') AS "5.2A - CUST"));


text:
Q: How to write a AWS lambda function with S3 and Slack integration I have a use case where i want to invoke my lambda function whenever a object has been pushed in S3 and then push this notification to slack.
I know this is vague but how can i start doing so ? How can i basically achieve this ? I need to see the structure

A: There are a lot of resources available for both integrations (s3+lambda and lambda+slack) so if you can put these together you can make it work.
You can use S3 Event Notifications to trigger a lambda function directly:
http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
Here are some blueprints to integrate lambda with slack:
https://aws.amazon.com/blogs/aws/new-slack-integration-blueprints-for-aws-lambda/
Good luck!

A: You can use S3 Event Notifications to trigger the lambda function.
In bucket's properties, create a new event notification for an event type of s3:ObjectCreated:Put and set the destination to a Lambda function.
Then for the lambda function, write a code either in Python or NodeJS (or whatever you like) and parse the received event and send it to Slack webhook URL.


text:
Q: Create XML structure with PHP from HTML form I am creating a system where a user can enter an ingredient and then save its quantity, I use PHP to save it as XML.
It currently saves like this.
 <ingredients>
    <ingredient quantity="2">Apple</ingredient>
    <ingredient quantity="4">Banana</ingredient>
  </ingredients>

Instead i would like to save it like this but i can't figure out how.
  <ingredient>
            <quantity_amount>2</tns:quantity_amount>
            <quantity_name>teaspoons</tns:quantity_name>
            <ingredient_name>baking powder</tns:ingredient_name>
        </ingredient>

for each ingredient added
Here is my PHP and HTML i currently use.
HTML

                <input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient"/>
                <input type="text" id="quantity_1" name="quantity[]"  value="" placeholder="Quantity"/>
                Add

PHP
// Start for loop, from 0 to ingredientName
for ($i = 0; $i < count($ingredientName); $i++) {
    // Select current item
    $element = $ingredientName[$i];

    // Updated used ingredients list ONLY
    // if the ingredient wasn't added yet
    $temp = search($upIngreds, 'value', $element);
    if (empty($temp)) {
        $upIngreds[] = array('value' => $element, 'label' => $element, 'image' => 'images/products/default.jpg');
    }

    // Select current item quantity
    $qty = $quantity[$i];
    // Create ingredient element and fill with $element
    $ingredient = $xml->createElement('ingredient', $element);
    // Set quantity attiribute to $qty value
    $ingredient->setAttribute('quantity', $qty);
    // Append it to ingredients element
    $ingredients->appendChild($ingredient);
}

A: to create a new ingredient according to your desired XML structure:
// creating the document and its root
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('ingredients','');
$dom->appendChild($root);

// create new ingredient and link it to root
$ingredient = $dom->createElement('ingredient','');
$root->appendChild($ingredient);

// create children and link them to ingredient
$q_amount = $dom->createElement('quantity_amount',"1");
$q_name = $dom->createElement('quantity_name',"spoon");
$i_name = $dom->createElement('ingredient_name',"PHP");
$ingredient->appendChild($q_amount);
$ingredient->appendChild($q_name);
$ingredient->appendChild($i_name);

echo $dom->saveXML();

see it working: https://eval.in/85654
Be sure to sanitize user input from your form prior to inserting it into the XML.


text:
Q: gitlab-ci does not display environnement variable I am working with gitlab-ci.
I have set an Environment variable: MY_ENV_VAR (in Project CI/CD Settings menu)
I see a message with says the environnement variable is prefixed by K8S_SECRET_
Here is my .gitlab-ci.yml:
deploy:
  only:
    - prod
  script:
    echo ${K8S_SECRET_MY_ENV_VAR}

It does not display the value in job... I see the echo command in green but i have something blank bellow.
I have tried echo $K8S_SECRET_MY_ENV_VAR or echo $SECRET_MY_ENV_VAR. It is the same.
Thanks

A: The K8S_SECRET_ prefix is to target variables for the Auto Devops feature. Normal variables need no such prefix, so in your example simply reference $MY_ENV_VAR


text:
Q: Using hashing algorithm in CAPL (CANoe) I want to implement a hashing algorithm like md5 in CAPL (CANoe). Is there any built-in hashing function in CAPL?

A: I would suggest to create a CAPL Dll which implements your hash-algorithm in C++ and include it via #pragma library() in your code.
There is an example in "CANoe Sample Configurations\Programming\CAPLdll". For more infos take a look at the chapter "CAPL DLL" in your CANoe help.

A: There is not a built in hash function in CAPL, the closest I've been able to find is a checksum calculation function. (J1939CalcChecksum) Anyhow you can use the CANoe .NET API, once you are using .NET you can call its hashing libraries.
The reference for CANoe .NET API is in Vector's page in the provided link.


text:
Q: How to create site wise custom evaluator to show or hide Create menu Doclib Actions How to create site wise custom evaluator to show or hide "Create" MENU Doclib Actions for specific site.
I have two options in create menu. now my requirement is,  i want to show first option for one site and second option for other site.
for that i need to write site wise custom evaluator.
so can anyone please help me, how can create that custom evaluator and how can i apply it to my custom configuration in custom model.
Thanks in advance.


text:
Q: Failure of twice-differentiation with numDeriv R package How would you explain this failure of numerical twice-differentiation with the numDeriv package ?
Below is a function Y and its first derivative dY.
Y <- function(x, A=1, B=1, a=1){
  A*cos(a*x) + B*sin(a*x) - x/2/a*cos(a*x)
}
dY <- function(x, A=1, B=1, a=1){
  -a*A*sin(a*x) + a*B*cos(a*x) - cos(a*x)/2/a + x/2/a*sin(a*x)
}

And below is a successful illustration of the grad function of the numDeriv package:
library(numDeriv)
x <- c(0.2,0.4,0.6)
grad(Y, x)
## [1] 0.31123 0.14900 0.01742
dY(x)
## [1] 0.31123 0.14900 0.01742

Twice-differentiation below works fine too:
dYnum <- function(x) grad(Y, x)
d2Ynum <- function(x) grad(dYnum, x)
d2Ynum(x)
## [1] -0.8820 -0.7368 -0.5777
grad(dY, x)
## [1] -0.8821 -0.7368 -0.5777

But when replacing Y with a sharp approximate, twice-differientation fails:
xx <- seq(0.01, 0.99, by=0.01)
Yapprox <- approxfun(xx, Y(xx))
dYnum <- function(x) grad(Yapprox, x)
dYnum(x) # first-order derivative is OK
## [1] 0.31124 0.14901 0.01743
d2Ynum <- function(x) grad(dYnum, x)
d2Ynum(x) # not the good result
## [1] -2698 -1127  -589
grad(dY, x)  # this is the good result
## [1] -0.8821 -0.7368 -0.5777

However when replacing dYnum with an approximate, it works again:
xx <- seq(0.1, 0.9, by=0.01)
dYnumapprox <- approxfun(xx, dYnum(xx)) # approxfun(xx, grad(Yapprox, xx))
d2Ynum_ <- function(x) grad(dYnumapprox, x)
d2Ynum_(x)
## [1] -0.8820 -0.7368 -0.5777

A: You forgot the inner derivative in the last term. The a in the denominator cancels with the inner derivative. So it should be
  -a*A*sin(a*x) + a*B*cos(a*x) - cos(a*x)/2/a + x/2*sin(a*x)

As for the error, I would suspect that the culprit is the approximation. Depending on the type of the approximation, the error between the sample points in the function values can be arbitrarily large, which only magnifies when computing derivatives. You might get better results by using far less sample points, 6 instead of 99.

RTFM: Per R-manual approxfun only provides piecewise constant or linear approximations. Both are not differentiable. This means that the derivative of the piecewise linear approximation is piecewise constant with jumps and the second derivative is piecewise zero with delta peaks at the sample points. Re-interpolating the first derivative via a piecewise linear function will, while not the most mathematical procedure, lead back to reasonable results.
Use R-manual splinefun to get an interpolating function that actually is twice differentiable.

A: Not sure what you expect: not for nothing is numerical differentiation called "error magnification" . The fact that your dYnum values are not identical to the non-approxfun values should be a huge red flag to warn you that the data you're feeding to your second numerical differentiation has got noise in it.   the grad (or any other numerical differentiator) function then dutifully differentiates the high-frequency components caused by the noise in the data.


text:
Q: Create a new column that displays multi column matches in R I want to make a new column, where factors from column 'a' that have one match (value == 1) with column 'b' are assigned by TRUE.
a <- c(555, 555, 555, 666, 666, 666, 777, 777)
b <- c(1, 0, 0, 0, 0, 0, 1, 0)
df <- data.frame(a, b)

The result i want is
    a   b   c
1  555  1   1
2  555  0   1
3  555  0   1
4  666  0   0
5  666  0   0
6  666  0   0
7  777  1   1
8  777  0   1

Thanks in advance,

A: We can use the dplyr package.
library(dplyr)
df2 <- df %>%
  group_by(a) %>%
  mutate(c = max(b))
df2
# A tibble: 8 x 3
# Groups:   a [3]
      a     b     c
  <dbl> <dbl> <dbl>
1   555     1     1
2   555     0     1
3   555     0     1
4   666     0     0
5   666     0     0
6   666     0     0
7   777     1     1
8   777     0     1

Or the data.table package.
library(data.table)
dt <- as.data.table(df)
dt2 <- dt[, c := max(b), by = a]
dt2
     a b c
1: 555 1 1
2: 555 0 1
3: 555 0 1
4: 666 0 0
5: 666 0 0
6: 666 0 0
7: 777 1 1
8: 777 0 1

A: We can use base R split
df$c <- unsplit(lapply(split(df$b, df$a), max), df$a)
df$c
#[1] 1 1 1 0 0 0 1 1


text:
Q: Match all GNU C SIMD vector extension types in clang/gcc The objective is to write a type trait with the following signature:
template<typename T>
struct is_vector : std::true_type / std::false_type

such that you can use is_vector<T>::value in SFINAE signatures. How do I properly detect whether a type is __attribute__((__vector_size(<some_vector_width>)) <some_built-in_type> in GCC/clang?
I looked through the LLVM documentation but couldn't see any built-ins to detect this.  The GNU C documentation similarly only documents it as a C extension, not mentioning C++.
The backup plan is to specialize the template for each permutation but that really doesn't sound nice.

A: You could create a type trait to check if it's one of these vector types. It was a bit tricky finding a way to do it, but using one of the built-in functions that operates on the vectors seems to work.
In this gcc example, I use __builtin_convertvector to try to convert the vector type to the same vector type. If it's not a vector type, SFINAE will select the test() function that returns false_type. If it is one of the vector types, it'll select the test() function that returns true_type.
#include <type_traits>

template<class T>
struct is_vector {
    static std::false_type test(...);

    template<class B>
    static auto test(B) ->
        decltype(__builtin_convertvector(std::declval<B>(), B), std::true_type{});

    static constexpr bool value = decltype(test(std::declval<T>()))::value;
};

template<class T>
static constexpr bool is_vector_v = is_vector<T>::value;

Demo


text:
Q: CheckBoxListRow many-to-many in view I trying a create in my view, a CheckBoxListRow of YiiBooster, but this error showing:
Property "CModelCollection.cd_perm_per" is not defined.

In my _form.php I set a property this:
<?php
    $perms = CHtml::listData(Permission::model()->scopeDeleted()->findAll(), 'cd_perm_per', 'ds_titulo_per');
    echo $form->checkBoxListRow($model, 'permission.cd_perm_per',$perms);
    //echo $form->dropDownListRow($model, 'permission.cd_perm_per',$perms);
?>

My relations in Model is:
public function relations(){
    return array(
        'permission' => array(
              self::MANY_MANY,
              'Permission',
              'tb_group_perms(cd_group_grp, cd_perm_per)',
              'together' => false
         ),
    );
}

Apparently its OK, but not work! Any ideas?

A: Well, I managed to solve the above problem as follows:
I created a variable called $options in my model which would be stored CheckBoxListRow options. This variable is not in the database it is local.
After this, in my view, I configured my CheckBoxListRow getting this variable $options. Thus the values were correct.
When saving, you must configure the method afterSave() to be saved in the relationship database.


text:
Q: Is there any work around to launch screen flow from Process builder I have  a requirement where I need to provide a modal window to user when Case status changes to Revise Invoice status .
He can then select Account and a child case gets created under that account .
Now I want to use OOB feature to achieve this .
Having a screen and creating a child case ,can be achieved by Screen flow .
But now I am stuck as how to call screen flow from process builder or an auto triggered flow .
Is there any way that can make my screen flow connect with process builder or to have this requirement without writing any code
Thanks in advance


text:
Q: How does postgreSQL structure Django Array Fields in database How does PostgreSQL structure an ArrayField like:
class House(models.Model):
    people_ids = ArrayField(models.IntegerField(), default=list, blank=True)

in database? Does it generate an auxiliary table with the numbers as Ids and then another table with the Id pairs? Like:
House

Id
Name

1
MyHouse

People

Id

1

2

House_People

House_Id
Person_Id

1
1

1
2

So as to have, for example, people 1 and 2 in house "MyHouse"?


text:
Q: Converting "R.id.myID" from a String to the int value R.id.myID? The text on my views represent an id. So when clicked I would like to get a reference to that resource. The following incorrect code represents what I'm trying to do
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.categories);

    Bundle bundle = getIntent().getExtras();
    int myArrayID = bundle.getInt("category_id", 0);
    String [] myArray = getResources().getStringArray(myArrayID);

    setListAdapter(new CategoryAdapter(this, android.R.layout.simple_list_item_1, R.id.categoryText, myArray));
    ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            String myIdString = (String) ((TextView) view.findViewById(R.id.categoryText)).getText();
            int myIdInt = // convert to the correct id that is represented by this string myIdString
            Intent intent = new Intent(Categories.this, Categories.class);
            intent.putExtra("category_id", myIdInt);
            startActivity(intent);
        }
      });
}

I understand why this method doesn't work.  For example the view would have the text "example1" and then there would be an R.id.example1 value that I need to get a reference to. Obviously I am approaching this the wrong way, and would like some guidance.
Edit - more code as requested.
Edit2 - Poor description. So my activity is a custom list. When one of the views is clicked, the title of that item will correspond to a string-array I have in my strings.xml. So if "example1" is pressed, there will be a string-array with the id R.array.example1. I want my code to extract the text of the view, and use it to find the correct string-array. This string-array would then be used to populate a new activity, with the custom list items the items in the array

A: I didn't get exactly what your code is supposed to do. But to get a resource id out of the resource name, use the following
getResources().getIdentifier(<resource name>, "id", getPackageName())

Read more here.

A: The best solution to store the resource Id would probably be using the Tag property of the TextView (If I understand correctly, the TextView from your code is part of a custom list item, correct ?)


text:
Q: Adding event listeners dynamically Suppose I want to create a single button. This should be easy enough - just create a square, addChild to add it to the screen  and an event listener for mouse.CLICK event
add_btn_listeners():void
 {

   btn[0].addEventListener(MouseEvent.CLICK, btn_clc1);
 }
public function btn_clc1(event:Event):void
 {
   action1();
 }

Suppose though that you wanted to create twenty buttons. You would then need twenty functions similar to the above btn_clc1 function with an event listener for the appropriate click.
But suppose you wanted the action to very slightly such as by index. For example, btn[0] calling action1, btn[1] calling action2, etc. in the same listener btn_clc1 listener.
A very common example of this would be mouse rollover. On rollover to highlight a square for instance, increasing the alpha layer to highlight a menu selection. The highlighted layer would depend on the index, something like: btn[index].alpha = .9;
Is there a way to reduce the number of event listeners, or code more optimally in cases like this? Most of the example's I've seen seem kind of shallow for larger cases.

A: One thing you can do is within the event object in the event handler, there is a 'target' property. This refers to the object that dispatched the event. You can cast it back in to whatever you assigned the event listener to and access it, or can just use a loop/if block to compare to figure out which button it was.
import flash.display.Sprite;

var aButton:Sprite = new Sprite();

function clicked(inputEvent:MouseEvent):void {
    var theButton:Sprite = (Sprite) (inputEvent.target);
    trace(theButton); // traces out the sprite

    // can compare
    trace(theButton == aButton); // traces out true

    // if the had any (custom) properties, you could also access them, such as:
    trace(theButton.visible);
}
aButton.addEventListener(MouseEvent.CLICK, clicked, false, 0, true);

A: This is exactly the type of problem that object oriented programming is designed to solve. Just create a class with the event handlers in it - then you can create as many of them as you like.
Class example:
public class MyButton extends Sprite
{
    public function MyButton()
    {
        graphics.beginFill(0);
        graphics.drawRect(0, 0, 50, 30);
        graphics.endFill();

        addEventListener(MouseEvent.CLICK, _mouse);
        addEventListener(MouseEvent.ROLL_OVER, _mouse);
        addEventListener(MouseEvent.ROLL_OUT, _mouse);
    }

    private function _mouse(e:MouseEvent):void
    {
        switch(e.type)
        {
            case MouseEvent.CLICK:
                trace("click");
            break;

            case MouseEvent.ROLL_OVER:
                alpha = 0.9;
            break;

            case MouseEvent.ROLL_OUT:
                alpha = 1;
            break;
        }
    }
}

Then you can create them like so:
for(var i:int = 0; i < 5; i++)
{
    var btn:MyButton = new MyButton();

    btn.x = i * 60;
    addChild(btn);
}


text:
Q: Git - get list of all commits which changed a file I try to get a list of all commits which made changes to a certain file. Is this possible? It should be sorted by date.
git showAllChanges /path/to/file.xy

Output:
d9fc62dba13069fc281e9d09b698ba2e32f6dafd
2625eb741618dae7004b3d23a5894ae7a91df698
cfae25eced932c1375b3bc56ae8399ca88513d94

A: You can use git log:
git log --pretty=format:"%h" -- path/to/file.xy

The --pretty=format:"%h" allows you to get only minified commit hash. If you want the full hash, you can use %H. If you want more you can take a look at the pretty-formats documentation.
If you want to take filename change into account, you can use the --follow option.

A: Yes, it is possible, you have the git log command, as reported in the official documentation
By default, with no arguments, git log lists the commits made in that repository in reverse chronological order; that is, the most recent commits show up first.
You can also pretty print the output with $ git log --pretty=oneline or $ git log --pretty=format:"%h - %an, %ar : %s"
Or limit time interval with git log --since=2.weeks.
There are a lot of parameters, check out the manual page. Here is the full documentation


text:
Q: Cascading with CSS :not pseudo-class I'm confused as to why this example doesn't work:
CSS:
p {
  color: red;
}

div:not(.exclude) p {
  color: green;
}

HTML:

I should be red

I should be green

The end result is that both
 are green, but I would have expected the first one to be red. Here's a JSFiddle.
Interestingly, I found three different ways to make it work:

*

*Remove the top-level
 from the HTML

*Change the top-level
 to a different element (e.g.
)

*Add an extra div to the beginning of the second CSS selector (div div:not(.exclude) p)

And another weird way to break it:

*Using solution 2 as a basis, wrap another
 around the

According to MDN:

This selector only applies to one element; you cannot use it to exclude all ancestors. For instance, body :not(table) a will still apply to links inside of a table, since
 will match with the :not() part of the selector.

That makes sense, but I don't think that this is happening here. Since there is nothing between
 and its direct child
, it should trigger the rule regardless of what it is nested inside. What am I missing? I'd really appreciate if someone could help me understand this.

A:
Since there is nothing between
 and its direct child
, it should trigger the rule regardless of what it is nested inside. What am I missing?

The
 is a descendant of both the top-level
 and
. So while the latter doesn't match the selector, the former does, and therefore you have a match. It doesn't matter either that the ancestor that fails to match the selector is closer to the
 than the one that does.
Solutions 1 and 2 work by eliminating that match altogether.
Solution 3 works when no other
s exist in the
's ancestry, because then you restrict your selector to those exact criteria, in that exact order. Which means if you swapped the class attribute from the inner
 to the outer one, it would no longer match the selector, and conversely if you swapped the class selector from the inner div to the outer one, the selector would not match the original HTML structure (again, assuming no other
s exist in the hierarchy).
Wrapping another
 around the
 just causes the selector to be matched again by that
. The
 is ignored, in much the same way as
.
See also:

*

*CSS negation pseudo-class :not() for parent/ancestor elements

*Why doesn't this CSS :not() declaration filter down?

*Is the CSS :not() selector supposed to work with distant descendants?

A: You have an overriding
 even higher than
.
In your styles, you have indicated that - as far as the :not pseudo-class is concerned - any ancestor
 will do. (ie. a grandparent
 is just as good as a parent
.)
To focus on the immediate parent, your CSS needs to employ the direct child selector (>):

p {
color: red;
}

div:not(.exclude) > p {
color: green;
}

I should be red

I should be green

A: You have discovered a common pitfall in using :not, as well described by the other answers. The classic approach in CSS to dealing with this problem, and the way we did it before CSS3 provided us with the ability to shoot ourselves in the foot with :not, is to write several rules, one dealing with the general case, the second with the exception. In your case, this would look like:
p             { color: red;   }
div p         { color: green; }
div.exclude p { color: red;   }


text:
Q: Simple distance query is not working I have latitude and longitude defined as decimal(9, 6) in my zip code table, per the zip code database company's instructions.
I take a lat/lon feed it to a function in my c# program and it gives me lat/lon in boundaries for getting a list of lat/lon from the database (radius distance)
The sql code does not work with the longitude.
SELECT TOP(10) * FROM USZipCode WHERE (Latitude BETWEEN 34.7600283409472 AND 37.6513716590528)
AND (Longitude BETWEEN -76.383333 AND -76.818238)
But if I skip the longitude then it works, or at least returns records even if they are the wrong ones.
SELECT TOP(10) * FROM USZipCode WHERE (Latitude BETWEEN 34.7600283409472 AND 37.6513716590528)
The only thing I can think of; is that since the longitude is negative that the sql ain't working?
This is SQL SERVER 2008 R2 and I've also tried the Lat > x and Lat > y etc.

A: Flip your upper and lower negative limits:
-76.818238 is **less than** -76.383333

A: -76.818238 is less than -76.383333.
Try:
 AND (Longitude BETWEEN -76.818238 AND -76.383333)

A: The lower value needs to be first in the BETWEEN expression...  Not the lower absolute value.
DECLARE @MyTable TABLE
(
  ID int PRIMARY KEY
)

DECLARE @i int
SET @i = -10
WHILE @i < 11
BEGIN
  INSERT INTO @MyTable (ID) SELECT @i
  SET @i = @i + 1
END

SELECT * FROM @MyTable
WHERE ID between 3 AND 6

  -- no records because there is no value which is greater than -3 and less than -6
SELECT * FROM @MyTable
WHERE ID between -3 AND -6

SELECT * FROM @MyTable
WHERE ID between -6 AND -3

SELECT * FROM @MyTable
WHERE ID between -3 AND 3

Fun fact, Sql Server's query optimizer detects the bad range in that second query and does not even perform IO on @MyTable.

A: try
SELECT TOP(10) * FROM USZipCode WHERE (Latitude BETWEEN 34.7600283409472 AND 37.6513716590528) AND (Longitude BETWEEN -76.818238 AND  -76.383333)
It IS because of negative numbers.  -76.3 is a larger number than -76.8, so you need to reverse them.

A: If you want to compute with a radius it's more complicated, use this function
    CREATE FUNCTION [dbo].[getDistance]
(
@lat1 float,
@lon1 float,
@lat2 float,
@lon2 float
)
RETURNS float
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result float

    -- Add the T-SQL statements to compute the return value here
    SET @result = (SQRT((69.1*(@lat2-@lat1)) * (69.1*(@lat2-@lat1)) + (53.0*(@lon2 - @lon1))*(53.0*(@lon2 - @lon1)))/0.621369949495)

    -- Return the result of the function
    RETURN @result

END

And like this
SELECT * FROM myTable
WHERE dbo.getDistance(latitue,longitude,@lat,@long) <= @radius

A: Run this query and see if you have any records in this range -
SELECT TOP(10) * FROM USZipCode
WHERE (Longitude BETWEEN -76.818238 AND -76.383333)

My guess is that you do not have any data in the longitude range specified
and also -76.818238 is less than -76.383333


text:
Q: Resolve bindings after setting DataContext of control created with DataTemplate.LoadContent() Given a XAML-declared data template:
<DataTemplate x:Key="MyDataTemplate">
    <TextBlock Text="{Binding DataValue}"/>
</DataTemplate>

And a class:
public class Model
{
    public string DataValue
    {
        get { return "TheDataValue"; }
    }
}

The following code does not do what I need:
var model = new Model();
var template = FindResource("MyDataTemplate") as DataTemplate;
var textBlock = template.LoadContent() as TextBlock;
textBlock.DataContext = model;

Eventually the binding from the DataTemplate gets resolved and the Text of the TextBlock shows "TheDataValue".  But it does not happen quickly enough for some more code that needs to inspect the property.  A breakpoint immediately after the last line of code shows textBlock.Text as having a value of "".
I have tried textBlock.UpdateTarget() and textBlock.InvalidateProperty(TextBlock.TextProperty) but neither seem to help.

A: Clearing and re-applying the databinding for the property on the dependency object seemed to do the trick:
public static void Rebind(DependencyObject target, DependencyProperty property)
{
    var binding = System.Windows.Data.BindingOperations.GetBinding(target, property);
    if(binding != null)
    {
        System.Windows.Data.BindingOperations.ClearBinding(target, property);
        System.Windows.Data.BindingOperations.SetBinding(target, property, binding);
    }
}

Calling that on the textBlock immediately after setting the DataContext immediately causes the binding to evaluate and property queries then return the expected, post-binding value "TheDataValue".


text:
Q: maximal subgroup $H(e)$ of semigroup $S$ Let $e$ be an idempotent in a semigroup $S$. The union of all subgroups of $S$ containing $e$ is called the maximal subgroup of $S$ containing $e$ and is denoted by $H(e)$. We know that $H(e)$ is actually a subgroup of $S$ with idedntity $e$. I want to prove:
$$H(e)=\{t\in eSe: e\in St\cap tS\}$$
I think I should prove the right hand side is a group containing $H(e)$.

A: To show the RHS is a group, suppose that $t \in $RHS. Then $e \in St \cap tS$ implies that there exist $s_1,s_2 \in S$ with $s_1t =ts_2 = e$ and then $s_1e = s_1ts_2=es_2$.
Also $t \in eSe \Rightarrow te = et =t$, so $tes_2 = s_1et = e$ and hence $s_1e=es_2$ is a $2$-sided inverse to $t$.
For closure, clearly $t,u \in eSe \Rightarrow tu \in eSe$, and $tu$ has inverse $u^{-1}t^{-1}$.


text:
Q: AspNet + IE8: auth cookie not always set Background:

*

*AspNet C# 3.5 Web App

*IIS 7

*Forms Authentication

*in web.config, no "domain" in <forms /> settings

*name of cookie: .exampleAuth

Sometimes, and only with IE8, session auth cookie is not set in browser. The user logs in, he can see the default.aspx page of the web app, but if he clicks anywhere he is disconnected. No  auth cookie. AspNet_SessionId cookie is well created, as another one managed by our app.
It looks like it's happening since we removed the "domain" attribute in Web.Config to allow example.com and example2.net url for the web app.
Cookie is created using FormsAuthentication.GetAuthCookie(user.Id, true); as before.
IE7, IE9, FF, Chrome are ok. IE8 sometimes (let's say 95% of the time it's ok, 5% user is disconnected). For some users, closing IE8 (without flushing cookie and cache) solves the problem.
One more thing: if we enable IE8 "cookie alert popup", we can see that auth cookie is sometimes set twice after login. First with Expiration=Session, then with Expiration=Now+1h20 (session is set to 200 !)


text:
Q: How can I access programming class globally in vuejs I want to declare a class like below
class Customer{
 constructor(){
    this.id;
    this.name;
    this.email;
    this.username;
    this.password;
   }
}

I want to create its instance in any component in vuejs like this
export default {
  name: 'TestCompotent',
  data()
  {
    return{
      MainCutomer: new Customer()
    }
  },
}

Please advice me, how can I do that?

A: Here is a WORKING DEMO.
/src/class/Customer.js:
class Customer {
  constructor(id, name, email, username, password) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.username = username;
    this.password = password;
  }
}

export default Customer;

/src/components/HelloWorld.vue:
<template>

{{ msg }}

TEST PAGE

Main Customer

ID: {{ MainCustomer.id }}

Name: {{ MainCustomer.name }}

Username: {{ MainCustomer.username }}

E-mail: {{ MainCustomer.email }}

</template>


text:
Q: Link error with name mangling declspec mismatch in Visual C++ 2008 application at link time I have a DLL and a main executable, and the main executable is not linking in the symbols from the import library of the DLL anymore, and the declspec in the DLL .map file is not matching, nor is the mangled C++ name matching. I can't figure out why although I have done the usual things you do when you can't get C++ stuff to link.
My headers define something like this:
#ifdef MY_MODULE
#undef CLASS_EXPORT
#define CLASS_EXPORT __declspec(dllexport)
#else
#undef CLASS_EXPORT
#define CLASS_EXPORT __declspec(dllimport)
#endif

My classes seem to be exporting properly, but the .map file indicates some strange thing I think is wrong:
    6    ?CreateDataArea@@YAKPAGPBD111PAVCObject@@K@Z (unsigned long __cdecl
    CreateDataArea(unsigned short *,char const *,char const *,char const *,
    char const *,class CObject *,unsigned long))

The mangled name above has @@YAK...
The link error is:
1>Device.obj : error LNK2019: unresolved external symbol
"__declspec(dllimport) public: unsigned long __thiscall
CCommonMemory::CreateDataArea(unsigned short *,char const *,char const *,
char const *,char const *,class CObject *,unsigned long)"
(__imp_?CreateDataArea@CCommonMemory@@QAEKPAGPBD111PAVCObject@@K@Z) referenced
in function "public: __thiscall CDevice::CDevice(void)" (??0CDevice@@QAE@XZ)

So why is the mangled name @@QAEK different when I have the declspec macro configured and why is the .map file showing  __thiscall calling convention when the macro defines __declspec(dllexport)?
It's exactly like I forgot to do the  __declspec(dllimport/dllexport) macro, yet I did it.
I tried putting CLASS_EXPORT on EACH method exported, and I tried it in the first line of the class declaration with no change.

A: It looks like the definition for CreateDataArea() isn't being scoped to the class (ie., you've left off a CCommonMemory:: when defining the function).
If you look at what's getting into the map file, you'll see that it's a __cdecl function without the class name 'attached'.


text:
Q: How to run multiple Docker Containers in different terminals using Docker compose or with Shell? I have to pull docker image from Docker Hub and start running multiple peers as containers.
now, I am manually opening terminal and executing my docker run command on downloaded image but I am planning to automate this process like if I/user want 2 peers to run then I should be able to provide IP Address and Port information to Docker run command and start these peers in different terminals without manual step.
After executing these commands I should be able to store these IP address and port numbers in a JSON file further transactions.
Could you please help me!!! Thanks!!

A: Got quick solution for the above problem.. Below is the command I have applied docker run -d IMAGE NAME /bin/bash above command runs the container in background process. Also, I am taking network credentials by applying docker inspect <Container Id>


text:
Q: Why isn't mupdf displaying borders for hyperref links? I don't know if this is a bug to report to Artifex, maker of mupdf, or it's an issue with hyperref package.  If it's the latter, is there a workaround?
If I run the following code through pdflatex, I get what's expected when viewing the pdf output with, say, Firefox.  Further down is a screen capture which shows what I'm seeing.  For comparison, I'm also including a screen capture for mupdf.  Boxes are gone. Why?  In my experience, mupdf is extremely good at rendering PDFs.
In hyperref documentation and other posts, I've read something to the effect:  "borders aren't for printed output".  Hmmm.  Is that how mupdf is treating them, whereas other programs are rendering the PDF for the screen?  I don't know how the rendering program could be making this distinction.  (By the way, I've tried this with mupdf from version 1.7 to current version 1.21.  No difference.)
The following code is borrowed from Switch between box and color links with hyperref
\documentclass{article}
\usepackage{xcolor}
\usepackage[colorlinks]{hyperref}

\AtBeginDocument{%
  \hypersetup{pdfborder={0 0 1}, urlcolor=.}%
}

\begin{document}
\href{www.google.com}{The Google}

\hypersetup{pdfborder={0 0 0}, urlcolor=blue}
\href{www.google.com}{The Google}

\hypersetup{pdfborder={0 0 1}, urlcolor=.}
\href{www.google.com}{The Google}

\textcolor{red}{\href{www.google.com}{The Google}}
\end{document}

Firefox rendering:

mupdf rendering:

A: It appears to be a mupdf bug going back many years.  See https://bugs.ghostscript.com/show_bug.cgi?id=695159


text:
Q: How do I call TryParse from within a Predicate How do I use the TryParse method within a Predicate?  TryParse requires an out parameter.  In the example below, I would like to call TryParse to determine if x can be converted to an integer.  I really don't care for the out parameter--I just want to get this to compile.
        string[] nums = num.Split('.');
        PexAssume.TrueForAll(nums, x => int.TryParse(x, out (int)0));

A: string[] nums = num.Split('.');
PexAssume.TrueForAll(nums, x => { int result; return int.TryParse(x, out result); });

The "expression" part of a lambda can be wrapped in braces, allowing a full function body with multiple statements. So long as the result of that body is the same as the return value of the implied function you are implementing, you can do whatever you need to do between those braces.

A: If you don't care about the output, you can do it like this:
string[] nums = num.Split('.');
int unused;
PexAssume.TrueForAll(nums, x => int.TryParse(x, out unused));


text:
Q: How to make a Disabled Input also Required with Angular Reactive Form? I have an input which will be populated when the user clicks on a dialog. So for this I had to make it disabled, because I don't want the user to manually input the value.
The only problem is that this input must be required, and I couldn't make it so far.
I have tried to add 'required' directive in the input and also tried adding Validator.required on the form creation, but none of these made the field required for the form.
createUnityForm(): FormGroup {
    return this._formBuilder.group({
        id      : [this.unity.id],
        description: [this.unity.description],
        floor: [{value: this.unity.floor, disabled: true}, Validators.required]
    });
}

<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
    <mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
    <input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
        name="floor"
        formControlName="floor"
        required>
</mat-form-field>

<button *ngIf="action === 'edit'"
    mat-button
    class="save-button"
    (click)="matDialogRef.close(['save',unityForm])"
    [disabled]="unityForm.invalid"
    aria-label="save">
        {{'GENERAL.SAVE' | translate}}
</button>

unityForm is valid even when there's nothing in the input

A: Try readonly instead of disabled.

A: If you set a FormControl to disabled its validators will be ignored.
More info: https://angular.io/api/forms/AbstractControl#disabled

A: Radoslaw has it. Try readonly in the HTML instead of disabled in the model. This provides a similar UI to a disabling a control in the model but the validation remains operative. This can be useful (for example pulling in records from elsewhere to commit to another db, not allowing any user changes, but only committing if original data are valid)

A: You can't, reactive forms don't use validators on disabled fields.
I think it's a good way to do like this:
-HTML
<input
type="text"
formControlName="controlName"
[ngClass]="{ 'is-invalid':
(c.controlName.errors || c.controlName.disabled)
&& submited }"/>

-TypeScript
submited = false;

form: FormGroup = this.formBuilder.group({
    controlName: [{ value: '', disabled: true }, Validators.required]
});

get c(): { [key: string]: AbstractControl } {
    return this.form.controls;
}

save(): void {
    this.submited = true;
    if (this.form.invalid
       || this.formControl.controlname.value === '') {
     return;
}

-CSS
.is-invalid {
  border: 1px solid #dc3545;
}

When you click on button for SAVE, required field will get red border if there is no value

A: When it sets the disabled attribute, the validators will be ignored.

Disabled controls are exempt from validation checks and are not included in the aggregate value of their ancestor controls.

See: https://angular.io/api/forms/AbstractControl#disabled
If you want to make it disabled with the required or consider the validation, you have to make it readonly.
this._formBuilder.group({
    ...
    name: ['Your value here', Validators.required]
});

<input formControlName="name" readonly/>


text:
Q: Visualize Apriori Algorithm I'm trying to find the purchasing pattern from a certain dataset. Now I'm doing a visualization of the result I get from Apriori, Association rules. However, I'm having this TypeError issue with the codes.
I try to define a draw_graph function, then call the graph function to draw my rules.
def draw_graph(rules, rules_to_show):
import networkx as nx
G1 = nx.DiGraph()

color_map = []
N = 50
colors = np.random.rand(N)
strs=['R0','R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11']

for i in range(rules_to_show):
    G1.add_nodes_from(["R"+str(i)])

    for a in rules.iloc[i]['antecedants']:
        G1.add_nodes_from([a])
        G1.add_edge(a,"R"+str(i),color=colors[i],weight = 2)

    for c in rules.iloc[i]['consequents']:
        G1.add_node_from([c])
        G1.add_edge("R"+str(i),c,color=colors[i], weight = 2)
for node in G1:
    found_a_string=False
    for item in strs:
        if node==item:
            found_a_string = True
    if found_a_string:
        color_map.append('yellow')
    else:
        color_map.append('green')

edges = G1.edges()
colors = [G1[u][v]['color'] for u,v in edges]
weights = [G1[u][v]['weight'] for u,v in edges]

pos = nx.spring_layout(G1, k=16, scale=1)
nx.draw(G1, pos, edges = edges, node_color = color_map, edge_color = colors, width=weights, font_size=16, with_labels=False)

for p in pos:
    pos[p][1] += 0.07
nx.draw_networkx_labels(G1,pos)
plt.show()

support = rules.values(columns=['support'])
confidence = rules.values(columns=['confidence'])

import seaborn as sns1

for i in range (len(support)):
    support[i] = support[i]
    confidence[i] = confidence[i]

plt.title('Association Rules')
plt.xlabel('support')
plt.ylabel('confidence')
sns1.regplot(x=support,y=confidence,fit_reg=False)

plt.gcf().clear()
draw_graph(rules,10)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-279d477166f6> in <module>
----> 1 support = rules.values(columns=['support'])
      2 confidence = rules.values(columns=['confidence'])
      3
      4 import seaborn as sns1
      5

TypeError: 'numpy.ndarray' object is not callable

If any help on this it would be great. Thanks

A: Instead of
support = rules.values(columns=['support'])
confidence = rules.values(columns=['confidence'])

Try
 support = rules['support'].values
 confidence = rules['confidence'].values


text:
Q: Identifiability of ordered regression cutpoints I have an ordered regression model as described in ?polr:

The ordered factor which is observed is which bin Y_i falls into with
  breakpoints
zeta_0 = -Inf < zeta_1 < … < zeta_K = Inf
This leads to the model
logit P(Y <= k | x) = zeta_k - eta

(?polr documents a logit, but in my particular example I'm using a probit.)
I don't understand how the cutpoints zeta are identified in that model. It seems like you should be able to stretch them out as much as you like. (And the coefficients beta would follow suit.) How are these parameters identified mathematically? I know that in some models linear constraints are specified, such as setting one of the coefficients to 0, or stating that they sum to 1. Is that the technique used in ordered probit regression?
Part 2: How does the R package polr in particular identify these parameters? It doesn't seem like any of them is set to 0, and they don't sum to 1. I don't see any answers in ?polr.

A: Whether using polr or the R rms package's lrm and orm functions, there is one cutpoint for every unique value of $Y$ except for the first.  This is automatic.  Printed output of lrm and orm fit objects uses a notation that is a bit more clear.  The intercepts are constrained to be in order automatically, and if you compute the correct individual probabilities (see predict.lrm in rms) they will sum to one.  But we usually deal with exceedance probabilities.


text:
Q: python - log the same thing in two files twisted I'd like to know if there's a way to log the same thing in two files in twisted.
Let's say this is the code, now I'd like the same output going to "logs.log" to be redirected to sys.stdout.
if __name__ == "__main__":
    log.startLogging(open("logs.log", 'a'))
    log.startLogging(sys.stdout)

A: This is absolutely possible and easier than ever before if you're on the latest version of Twisted.
from sys import stdout
from twisted.logger import Logger, textFileLogObserver, globalLogBeginner

# start the global logger
logfile = open('log.log', 'a')
globalLogBeginner.beginLoggingTo([
    textFileLogObserver(stdout),
    textFileLogObserver(logfile)])

log = Logger()
log.info('hello world')
log.debug('hello world')

You can also implement you own logger if you want custom messages.


text:
Q: Should I dispose copies of StreamReaders/Writers So I have a class that has a StreamReader as a variable. The StreamReader is set through the constructor. When I use this class, I make a StreamReader outside of the class and pass it through. I then dispose the StreamReader instance that I passed through the constructor of the class. Do I need to dispose the StreamReader instance inside the class?
Code:
private class Class1
{
    private StreamReader Reader;

    public Class1(StreamReader Reader)
    {
        this.Reader = Reader;
    }
}

private class Class2
{
    public void Test()
    {
        StreamReader Reader = new StreamReader(@"");
        Class1 Test = new Class1(Reader);
        Reader.Dispose();
        //Do I need to dispose the Reader in Class1 aswell?
    }
}

A: You are passing the 1 instance of StreamReader into your Class1 instance. It does not create a copy, it passes a reference of that existing StreamReader. If you were to call this.Reader.Dispose(); in your instance of Class1 you would be calling it on the exact same instance of StreamReader that you can created in the Test() method.
So the answer for this block of code is No, there is no need to call Dispose again on that same instance.

A: There is only one StreamReader instance in your code, which is referenced from different variables (3 including the argument in the constructor), and disposing it once is enough.
However, your code won't work if you need the StreamReader inside Class1 after you call Reader.Dispose(); because the one inside Class1 is the same one, and will have been disposed as well.

A: If you have a method that uses an IDisposable, which is no longer required once the method terminates, then you should use a using { ... } block within that method, but if you pass the IDisposable to your method, then you either need to wrap the call to the method with a using { ... } block, or manually call .Dispose().


text:
Q: How to find my network and database access Our company gets audited pretty regularly and I was wondering if there's an easy way to find out which accounts have access to what on our network?
We're an all windows development shop, so all our servers are Win 2003-2008 and our databases are all Sql server 05/08. Is there any software I can run that will show for each entity (ie: Windows server or SQL database), which AD accounts/groups have what type of access?
Thanks!
Andrew

A: you can run this script against all registered servers in SSMS:
SELECT loginname AS NAME, dbname, denylogin, hasaccess,
sysadmin, securityadmin, setupadmin, processadmin, diskadmin,
dbcreator, bulkadmin
FROM sys.syslogins

Does a pretty decent job. I used this for a Ernst & Young security audit at our shop.


text:
Q: Does upvoting a duplicate comment do anything? When a question is initially flagged as a duplicate, there is a comment. If the duplicate flag gets enough votes, the question is closed as a duplicate, and the comment is deleted.  Does upvoting the duplicate comment count as a close vote? Does it do anything at all?

A: No, it just counts as another upvote on the comment (it increases the vote count).
Additional "close as exact duplicate flags" will also increase the vote count on a "possible duplicate" comment (if it exists).  But the comment score itself has no effect on closing a question.


text:
Q: How to check fscanf errors in C I have a table like this;
01 01 02 00 01 02 00 01
01 02 00 01 02 00 01 02
02 00 11 04 04 04 04 04
00 01 10 03 03 03 03 03

I am reading this file like this:
FILE *map = open_file("lazy.map");
if (map == 0)
    return 0;

for (i = 0; i < TOTAL_TILES; ++i) {
    int ttype;
    fscanf(map,"%i",&ttype);
    // do other stuff here...
}

Is there a way that I can check if fscanf failed or not?

A: Check the return value.
Another option is to use %n format:
int n = -1;
int ttype;
fscanf(map, "%i%n", &ttype, &n);
if(-1 == n)
    // failed to parse

This way you can check how many symbols have been consumed by fscanf. It doesn't make difference in the above, but in:
int count = fscanf(map, "%i abc %n", &ttype, &n);

count may be greater than one even if abc part of the format didn't match. On the other hand, n will be set only if the whole format matched.

A: Yes: you can examine its return-value. Per http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html:

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error.

(That page marks that last part, "and errno shall be set to indicate the error", as being POSIX-specific, meaning that the C standard itself doesn't require that errno be set; but the rest of it is all required by the C standard.)

A: Yes. From C++ reference:

Return Value
On success, the function returns the number of items
successfully read. This count can match the expected number of
readings or be less -even zero- in the case of a matching failure. In
the case of an input failure before any data could be successfully
read, EOF is returned.


text:
Q: Exposing Sass file from Meteor package for Meteor App importing I'm working on building a package for meteor 0.9+ that exposes a library off sass mixins called 'Bourbon' and am trying to sort out the best way to provide access to '@import' a stylesheet from the package into a Meteor project.
https://github.com/wolvesio/meteor-bourbon/
Pre Meteor 0.9 this used to be done via something along the lines of:
@import "packages/wolves:bourbon/bourbon";
Since the package system changed though this no longer works. Any help as to the best way to do this moving forward would be greatly appreciated.

A: I've managed to accomplish what you want, it's a bit hacky but it works at last.
First, you need to add the .less files as server assets in your package :
Package.onUse(function(api){
  api.addFiles([
    "bourbon/style1.less",
    ...
    "bourbon/styleN.less"
  ],"server",{
    isAsset:true
  });
});

Then run meteor to trigger the building of your application : this will copy over the server assets to the .meteor directory of your application. More precisely, your .less files will now live in ".meteor/local/build/programs/server/assets/packages/wolves:bourbon/bourbon/*".
Now you can reference these .less files in your application using this super unfriendly path.
I recommend hiding this stuff from your package users by defining an import.less directly in the package :
packages/wolves:bourbon/bourbon.import.less
@bourbon-root: ".meteor/local/build/programs/server/assets/packages/wolves:bourbon/bourbon/";

@import "@{bourbon-root}style1.less";
//
@import "@{bourbon-root}styleN.less";

Then in the package README, invite your users to simply copy bourbon.import.less in their client directory and reference it from there.
client/lib/config/style.less
@import "bourbon.import.less";

There is one drawback to this approach that I was unable to solve at the moment : the .less files are copied in the .meteor directory when your application is built (a process that happens when triggering meteor run).
However, the build process will try to compile your application .less files FIRST, before copying the server assets (in this case our package .less files) to the .meteor dir.
So the very first time you add the package to an app, it will complain that it is unable to find the package .less files, triggering a rebuild (either by killing and relaunching meteor or touching your application .less files) will fix this though.


text:
Q: Lebesgue Integrable functions I am in need of guidance for the following question: Let $f:X\to\mathbb{R}$ be an integrable function. Show that $\mu(\{x:|f(x)|\geq n\})\leq 1/n\int |f|\mu(dx)$ for each $n>0$.

A: Notice that for any $n$,
$$\int_X |f| d\mu \geq \int_{\{x: |f(x)|\geq n \}} |f| d\mu \geq \int_{\{x: |f(x)|\geq n \}} n \;d\mu = n \cdot \mu (\{x: |f(x)|\geq n \})$$
This is just Markov's inequality: http://en.wikipedia.org/wiki/Markov%27s_inequality#Statement


text:
Q: Set Ignored/Interesting tags based on basic regular expressions? On Stack Overflow I have set up around 150 ignored tags. And this list is growing every day. But I still see new questions with tags I want to ignore that are very similar to my ignored ones.
For example, I don't care about SQL. Not at all, not in any context. I'm just not interested.
So I have set up the following ignored tags: sql, sqlserver, sql-server, mysql, sqlite, sqlexpress, sqlserver2005, sqlserver2008, sql-server-2005, postgresql...
Then a new question might come up with the tag 'linq-to-sql' and I think "oh darn I'm gonna have to add that one too". It is really tedious to have to do this all the time (and it fuels my OCD :o)
I would like to add something like *sql* as an ignored tag, and that should be the end of it.

A: You can use wildcards as you can see here.


text:
Q: passing auto incremented id through forms I'm trying to do a simple login with a SQLServer database, and I'd like to know how I can pass the user_id once the confirmation works.
private void login_button_Click(object sender, EventArgs e)
    {
        SqlConnection con=new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='D:\Visual Studio\Test 3\Database\users.mdf';Integrated Security=True;Connect Timeout=30");
        String sqlquery = "select username,password from user_creds where username='"+username.Text+"' and password='"+pass.Text+"'";

        SqlDataAdapter adp = new SqlDataAdapter(sqlquery, con);
        DataSet ds = new DataSet();

        adp.Fill(ds);

        DataTable dt = ds.Tables[0];

        if (dt.Rows.Count >=1)
        {
            home fl = new home();
            this.Hide();
            fl.Show();
        }

        else
        {
            MessageBox.Show("Invalid login credentials.");
        }


text:
Q: Python Pandas - How to get group by counts by values from multiple columns with multiple values My data includes a few variables holding data from multi-answer questions. These are stored as string (comma separated) and aren't ordered by value.
I need to run different counts across 2 or more of these variables at the same time, i.e. get the frequencies of each combination of their unique values.
I also have a second dataframe with the available codes for each variable
df_meta['a']['Categories'] = ['1', '2', '3','4']
df_meta['b']['Categories'] = ['1', '2']

If this is my data
df = pd.DataFrame(np.array([["1,3","1"],["3","1,2"],["1,3,2","1"],["3,1","2,1"]]),
                  columns=['a', 'b'])

index  a      b
1      1,3    1
2      3      1,2
3      1,3,2  1
4      3,1    2,1

Ideally, this is what the output would look like
a  b   count
1  1   3
1  2   1
2  1   1
2  2   0
3  1   4
3  2   2
4  1   0
4  2   0

Although if I it's not possible to get the zero-counts, this would be just fine
a  b   count
1  1   3
1  2   1
2  1   1
3  1   4
3  2   2

So far, I got the counts for each of these variables individually, by using split and value_counts
df["a"].str.split(',',expand=True).stack().value_counts()
3    4
1    3
2    1

df["b"].str.split(',',expand=True).stack().value_counts()
1    4
2    2

But I can't figure how to group by them, because of the differences in the indexes.
df2 = pd.DataFrame()
df2["a"] = df["a"].str.split(',',expand=True).stack()
df2["b"] = df["b"].str.split(',',expand=True).stack()
df2.groupby(['a','b']).size()

a  b
1  1    3
3  1    1
   2    1

Is there a way to adjust the groupby to only count the instances of the first index or another way to count the unique combinations more efficiency?
I can alternatively iterate through all codes using the df_meta dataframe, but some of the actual variables have 300-400 codes and it's very slow, when I try to cross 2-3 of them and, if it's possible to use groupby or another function, it should work much faster.

A: First we make your dataframe to start with.
df = pd.DataFrame(np.array([["1,3","1"],["3","1,2"],["1,3,2","1"],
     ["3,1","2,1"]]),columns=['a', 'b'])

Then split columns to separate dataframes.
da = df["a"].str.split(',',expand=True)
db = df["b"].str.split(',',expand=True)

Loop through all rows and both dataframes. Make temporary dataframes of all compinations and add them to a list.
ab = list()
for r in range(len(da)):
    for i in da.iloc[r,:]:
        for j in db.iloc[r,:]:
            if i != None and j != None:
                daf = pd.DataFrame({'a':[i], 'b':[j]})
                ab.append(daf)

Concatenate list of temporary dataframes into one new dataframe.
 dfn = pd.concat(ab)

Groupby with 'a' and 'b' columns and size() gives you the answer.
 print(dfn.groupby(['a', 'b']).size().reset_index(name='count'))

   a  b  count
0  1  1      3
1  1  2      1
2  2  1      1
3  3  1      4
4  3  2      2


text:
Q: Parse RSS  to use as a source OK so im trying to have a webpage that rotates every 30 seconds now i have what i need for this but instead of using an array like in what i have now see code below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rotating Page</title>

where in MY-LINK-HERE for the pages array i would like to use my rss link and get the list of links and add them to the pages array or something similar
my rss link is http://directitpros.com/cbm/wp/?feedpages
so i just want to load the  text in the pages variable

A: It took me some time but I got it (tested and working)

*

*This example uses jQuery and jGFeed.

*jGFeed is a plugin for jQuery to do anything you want with RSS feeds.

*In the HTML source you can get the URL of the plugin to save it.

Observations:
1. Your RSS link is not working properly, please check it!
(http://directitpros.com/cbm/wp/?feedpages)
When using your link I receive this error from the plugin I am using in browser console:
"Uncaught TypeError: Cannot read property 'feed' of null"

2. Make sure the links you want to use in iframe are able to browse by iframe:
Example:
If URLs are not able to browse by iframe you will get this message in your browser console and your iframe will be empty:
"Refused to display document because display forbidden by X-Frame-Options."

3. If you find a working RSS url and links from it fit the above requirements, use this live example I made to test:
http://jsfiddle.net/oscarj24/qWdqc/
(Check browser console and check messages that will appear)

Let's go with the code :-)
HTML:

CSS:
html, body, iframe {
    height:100%;
    width:100%;
    overflow:hidden;
}

JS:
// Array containing pages
var pages = new Array();

// Time in seconds to rotate pages
var time = 30;

// Variable for loop purpose
var i = 1;

$(function(){

    $.jGFeed('http://working-rss-url',
      function(feeds){

        // Check for feeds
        if(!feeds){
          // There was an error, remote url not ok or no feeds
          return false;
        }

        // Do whatever you want with feeds here
        for(var i=0; i<feeds.entries.length; i++){
          var entry = feeds.entries[i];
          // Fill array with RSS entries
          pages.push(entry);
        }

        // If array contains urls
        if(pages.length != 0){
            // Rotate pages every 'x' seconds
            setInterval(function() {
                if(i == pages.length){
                   i = 0;
                }
                // Replace iframe scr with RSS entry link every 'x' seconds
                $('#holder').attr('src', pages[i].link);
                i++;
            }, time * 1000);
        }

    }, 5); // Number of feeds you want to recover

});

Hope this helps.


text:
Q: Angularjs injector error after grunt uglify I'm working on uglifying my angularjs project.
I'm having issue after uglification process. The following function doesn't work.
app.factory('Showmenusheet', function($rootScope){
return {

    //Custom pop up sheet for activities completed notification
    openNativePopup: function(imageUrl, title, para, buttonText, buttonLink){

        $('#popupTitle').html(title);
        $('#popupPara').html(para);
        $('#popupButton').html(buttonText);

        var imageElement = angular.element(document.querySelector('#popupImage'));
        var goToButton = angular.element(document.querySelector('#goToButton'));
        var closeButton = angular.element(document.querySelector('#closeButton'));

        goToButton.removeAttr("ng-show");
        closeButton.removeAttr("ng-show");
        goToButton.removeAttr("go-click");

        if(buttonLink == false) {
            goToButton.attr("ng-show", false);
            closeButton.attr("ng-show", true);
            $('#closeButton').html(buttonText);
        } else {
            goToButton.attr("ng-show", true);
            goToButton.attr("go-click", buttonLink);
            closeButton.attr("ng-show", false);
            $('#goToButton').html(buttonText);
        }

        imageElement.attr("src", 'assets/images/app_icons/'+imageUrl);
        compile(goToButton);
        compile(closeButton);
        compile(imageElement);

        setTimeout(function(){$('#nativePopup').addClass("showNativePopup");},350);
        setTimeout(function(){$('#deletemenu').addClass('delete-menu-active');},0);

    }
}
});

This is the error I get in console.

So basically if I don't uglify the code, the popup function works well without any problem however after uglify, I get the error in screenshot above.
Am I doing anything wrong in the above function which is against the standards?

EDIT
After adding various console log testings, I found the control is showing error with compile() function. I want the compile function to update the HTML everytime the 'openNativePopup' function is called from AngularJS.
What alternate can be used instead of compile()?

A: Usually minification errors on AngularJS errors are comes from missing full annotation that the dependency injection uses.
Think of it like that, lets say we have a service
angular
.module('MyModule', [])
.service('myService', function($rootScope) {
  $rootScope.title = 'my title';
});

Angular injects $rootScope into your function.
Whenever this code goes through minification, it become something like
angular
.module('MyModule', [])
.service('myService', function(a) {
  a.title = 'my title';
});

This make AngularJS dependency injection mechanism to throw, cause there is no such a that is registered to angular.
In order to solve this issue, there is $inject Property Annotation.
So the code should looks like that in order to support minification.
angular
.module('MyModule', [])
.service('myService', ['$rootScope', function($rootScope) {
  $rootScope.title = 'my title';
}]);

There is a tool that does this annotation automatically


text:
Q: Is it grammatically correct to put "to" and "within" together in sentence "this is confirmed by experiment to within strict limits"? a post says

the photon is a massless particle.  According to theory it has energy and momentum but no mass, and this is confirmed by experiment to within strict limits.

Is it grammatically correct to put "to" and "within" together like sentence above? If yes, which part of the sentence does "to" serve with?

A: Yes, as unusual as it is to have two prepositions in a row, this sentence is grammatically correct and natural.
The "to..." in the context of "confirmed by experiment" means "to some degree/precision/etc.", for example:

This result is accurate to five decimal places.

Expressions that describe the degree of accuracy are often not simple nouns:

about/around/within/over/less than... a millimetre

"Within strict limits" is a prepositional phrase, but here it acts as a noun representing the degree of accuracy.


text:
Q: How to handle null DateTimes in .NET and convert them to specified DateTime? In the last line, it will give an error "Year, Month, and Day parameters describe an un-representable DateTime." when dr.item("t$ltdt") is equal to null.
How can I handle null DateTimes and convert them into specified DateTime?
Dim sqlCur As String = "SELECT * FROM baan.ttiitm001800  WHERE (t$kitm ='1' or t$kitm='4') " & ItemCondtion & "  ORDER BY t$item"

    Dim cmd As New OracleCommand(sqlCur, connBaan)
    Dim dr As OracleDataReader = cmd.ExecuteReader()

    If dr.HasRows Then
        While dr.Read()
            Dim ChkItmCd As String = "SELECT Item_Code FROM MPC_Item_Master WHERE Item_Code='" & Trim(dr.Item("t$item")) & "' "
            db.OpenTable(ChkItmCd)

            If db.Eof Then
                ItmType = Trim(dr.Item("t$kitm"))

                If (Trim(dr.Item("t$kitm")) = "1") Then
                    ItmType = "PURCHASED"
                ElseIf (Trim(dr.Item("t$kitm")) = "4") Then
                    ItmType = "COST"
                End If

                Dim ltdt As Date = dr.Item("t$ltdt")

A: You probably want to use the Convert.ToDateTime method. It takes in a large variety of formats and converts it to a DateTime.
Also, make sure your input is not null:
Dim ltdt As Date
If dr.Item("t$ltdt") IsNot Nothing Then
    ltdt = Convert.ToDateTime(dr.Item("t$ltdt"))
End If