text:
Q: SpringBoot + Docker - ClassNotFoundException I'm trying to Dockerize an existing maven SpringBoot project and I cannot get it to start the application in the container. The application works perfectly outside it (with my IDE and with java -jar target/app-1.0-SNAPSHOT.jar) so I'm not sure what the issue is.
My Dockerfile:
# syntax=docker/dockerfile:1
FROM maven:3.6-jdk-11 AS build
WORKDIR /build
COPY src /src
COPY pom.xml .
RUN mvn clean package -DskipTests

FROM openjdk:11-jre-slim AS runtime
WORKDIR /app
COPY --from=build /build/target .
CMD ["java" ,"-jar", "app-1.0-SNAPSHOT.jar"]

My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<!--    <groupId>com.example</groupId>-->
    <artifactId>app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Backend</name>
    <description>Backend</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <start-class>com.example.Application</start-class>
        <log4jdbc.log4j2.version>1.16</log4jdbc.log4j2.version>
        <rest.assured.version>2.3.3</rest.assured.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
    </parent>

    <dependencies>
        <!--        Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.5.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.4.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.4.4</version>
        </dependency>
        <!--        -->

        <!--        Runtime -->
        <dependency>
            <groupId>com.ibm.db2</groupId>
            <artifactId>jcc</artifactId>
            <version>11.5.5.0</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--        -->

        <!--        Optional -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!--        -->

        <!--        Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.4.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <version>5.3.5.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>[3.2.2,)</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
        <!--        -->

        <!--        Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.4.7</version>
        </dependency>
        <!--        -->

        <!--        Utilities -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>

        <!--        Java Table implementation-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
        </dependency>
        <!--        -->

        <!--        Package to convert words to sentence case -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.9</version>
        </dependency>
        <!--        -->

        <dependency>
            <groupId>net.sf.jt400</groupId>
            <artifactId>jt400</artifactId>
            <version>10.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>

        <!--        Maths functions for player generation -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.6</version>
        </dependency>
        <!--        -->

        <!--        JSON Stuff -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <!--        -->

        <!--        Implementing and defining cmdline arguments -->
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.4</version>
        </dependency>
        <!--        -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.6</version>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.example.Application</mainClass>
                    <layout>ZIP</layout>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <reportSets>
                    <reportSet>
                        <reports>
                            <!-- select non-aggregate reports -->
                            <report>report</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
        </plugins>
    </reporting>
</project>

To build:
docker build -t app .

Which works successfully.
And to run:
docker run --rm -it -p 8100:8100 app

Which throws the following:
Exception in thread "main" java.lang.ClassNotFoundException: com.example.Application
    at java.base/java.net.URLClassLoader.findClass(Unknown Source)
    at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
    at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:151)
    at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Unknown Source)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:107)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
    at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:467)

I have also tried the Apache Maven Shade Plugin which did not help me.
To me, there doesn't seem to be anything wrong with the Dockerfile, is there perhaps an issue with the dependencies?
I tried copying the source files into the runtime stage and still no luck.

A:
COPY src /src

I am no Docker expert but I am surprised the build doesn't fail there. src is copied on / but "mvn package" runs on /build. I am not sure how this succeeds so maybe I'm wrong but I'd try with a relative path.


text:
Q: How can I find and replace only if a match forms a whole word? My script is:
n="y"
while [ "{n}" = "y" ]
if [ $n == "n" ];
then
  break;
fi
echo "n is $n"
do
        read -p "Enter the word to find = " word
        read -p "Enter word to replace = " replace
        echo "$word n $replace"
        #sed -i r.text.bak 's/$word/$replace/g' r.txt
        sed -i "s/$word/$replace/g" "test.txt"
echo "do you have further replacement? n or y"
read temp
n=$temp
done

My problem is that I am also replacing partial matches. For example, for a line like this:
1.1.1.14 1.1.1.14567

I get this output:
1.1.1.3  1.1.1.3567

but I expected:
1.1.1.3 1.1.1.14567

How can I solve this?

A: You need to write your regular expression in a way that only matches whole words. With GNU sed, you can use \b which matches at word boundaries:
sed -i "s/\b$word\b/$replace/g"

If you know there will always be a space there, you could just add a space:
sed -i "s/ $word /$replace/g"

Now, there are also some issues with your script. Your if ... break statement is useless, the while is already taking care of that. All you need is:
#!/usr/bin/env bash
n="y"
while [ "$n" = "y" ]
do
    echo "n is $n"
    read -p "Enter the word to find = " word
    read -p "Enter word to replace = " replace
    echo "$word n $replace"
    sed -i "s/\b$word\b/$replace/g" test.txt
    echo "do you have further replacement? n or y"
    read temp
    n="$temp"
done

A: Replace the following line in the script
sed -i "s/$word/$replace/g" "test.txt"

with
sed -i "s/$\bword\b/$replace/g" test.txt

Please refer following link.
http://www.rexegg.com/regex-boundaries.html#wordboundary

A: Here, I'd use perl.
WORD=$word REPLACE=$replace perl -pi -e '
  s/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' file

sed (even GNU sed) has no equivalent for \Q\E which you need here for the $word not to be taken as a regexp. And most sed implementations don't support -i (or they support it with different syntax) or \b.
\b matches a transition between a word and non-word character.
So \b\Q1.1.2.3\E\b would still match in 1.1.2.3.4 as . is a non-word.
You could also do:
WORD=$word REPLACE=$replace perl -pi -e '
  s/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' file

To match on $word as long as it's not preceded nor followed by a non-spacing character. (using (?<!) and (?!) negative look behind/forward operators).
Note that perl will by default work with ASCII characters. For instance, a word character would only be _a-zA-Z0-9 (\b\Q1.2.3\E\b would match in 1.2.3é and \S would match individual bytes of an extended unicode spacing characters). For non-ASCII data, you'd probably want to add the -CLSD option to perl.
Some examples:
$ export WORD=1.1.1.3 REPLACE=REPLACE
$ printf '1.1.1.3-x 1.1.1.3\u2006 1.1.1.3.4 1.1.123 1.1.1.3\u20dd 1.1.1.3\ue9\n' > f
$ cat f
1.1.1.3-x 1.1.1.3  1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -pe 's/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' f
REPLACE-x REPLACE  REPLACE.4 1.1.123 REPLACE⃝ REPLACEé
$ perl -CLSD -pe 's/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' f
REPLACE-x REPLACE  REPLACE.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -pe 's/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' f
1.1.1.3-x 1.1.1.3  1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -CLSD -pe 's/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' f
1.1.1.3-x REPLACE  1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é

$ sed "s/\b$WORD\b/$REPLACE/g" f
REPLACE-x REPLACE  REPLACE.4 REPLACE REPLACE⃝ 1.1.1.3é

A: sed -i "s/\s$word\s/$replace/g" "test.txt"

sed also support metacharacter \s
example
var=world

echo "hello world"|sed -r "s/\s$var(\s|$)/.../g"

results
hello...

Note is it is necessary to put (\s|$) pattern since a line can end with a word followed by an end of line character instead of  a space

redpajama_set_name: RedPajamaStackExchange


text:
Q: Original source of "precise" ε-δ (epsilon-delta) formal definition of a limit? I frequently see Karl Weierstrass credited for formulating the precise definition of a limit. But what I'd like to know is the origin of the formal definition so common in textbooks, that given a continuous function $f : ℝ → ℝ$, for all $x$ of its domain within the neighbourhood of a constant c (i.e., any point limit of $x$),
\begin{align*}
(\lim_{x→\textrm{c}} f(x) = \textrm{L})  &≜ ∀\, ε \in ℝ_{>0} : ∃\, δ \in ℝ_{>0} : ∀\, x ∈ \textrm{DOMAIN}\ f : \\
&\qquad 0 < \left|x - \textrm{c}\right| < δ ⇒ \left|f(x) - \textrm{L}\right| < ε
\end{align*}
The Stanford Encyclopedia of Philosophy's "Continuity and Infinitesimals" credits Weierstrass but cites Heine, and then only for the formal definition of a $\textit{continuous}$ function.
Anyone know more history on this or Weierstrass's original publication? Did he use Gottlob Frege's notation or some other kind?

A: *

*In the paper On the history of epsilontics by G.I. Sinkevich we can read:
Unfortunately, Weierstrass himself had never published or edited his lectures. In most cases, they came down to us in notes of his students.
...
The earliest known Weierstrass' text where the $\varepsilon$-$\delta$ technique is mentioned are differential calculus lecture notes made at a lecture read in the summer term of 1861 in Königlichen Gewerbeinstitut of Berlin. "The lecture notes were made by Weierstrass' student, H.A. Schwarz, and are now kept in Mittag-Leffler Institute in Sweden. Schwarz was 18 then, and he wrote these notes solely for himself, not to be published" [Yushkevich, 1977, p. 192].

Schwarz' notes were found and published by P. Dugac [Dugac, 1972]. It is in these notes that the definition of continuous function in the language of epsilontics appears for the first time:
"If $f(x)$ is function $x$ and $x$ is a defined value, then, on conversion of $x$ into $x+h$, the function will change and will be $f (x+h)$; difference $f (x+h) – f (x)$ is used to be called the change received by the function by virtue of the fact that the argument convers from $x$ to $x + h$. If it is possible to determine such boundary $\delta$ for $h$ that for all values of $h$, the absolute value whereof is still smaller than $\delta$, $f(x+h) – f(x)$ becomes smaller than any arbitrarily small value of $\varepsilon$, then infinitesimal changes of function are said to correspond to infinitesimal changes of argument. Because a value is said to be able to become infinitely small, if its absolute value can become smaller than any arbitrary small value. If any function is such that infinitesimal changes of function correspond to infinitesimal changes of argument, then it is said to be a continuous function of argument or that it continuously changes along with its argument" [Yushkevich, 1977, p.189].

*Yushkevich A. 1977. Chrestomatija po istorii matematiki. Matematicheskij analis (Reading book on the history of mathematics. Analysis), edited by A.Yushkevich.- Moscow: Prosveschenije. – 224 p.

*Dugac, P. 1972. Elements d`analyse de Karl Weierstrass. – Paris.


text:
Q: phpmyadmin frame contents not loading after port change, have changed PmaAbsoluteUri I had phpmyadmin all set up and working on port 8080. I remember changing quite a few things but it was a while ago :(
Due to ugly :8080s in the URL, I'm now changing everything back to port 80. the rest of the server after the port change works fine.
I've already changed PmaAbsoluteUri back to the non-port version.
I can load the index.php, the login part loads with images and I log in with root and password fine, meaning (I think) that mysql is working ok.
The index page loads from looking at the source, but the frames are blank.
When I change the address bar to point directly to the main.php or navigation.php they load ok, but without images.
I have a feeling I made a change to common.inc.php which I believe was something to do with images, but can't remember what!
I'm the queen of making stupid mistakes and spending the longest time on the most obvious ones, so even the most basic suggestions are welcome!
System is mac osX, server is tomcat (for the jsps), wordpress/phpmyadmin 3.5.8.2 run using quercus-4.0.37

A: OK, so after seeing some similar things going on for the newer versions of phpMyAdmin to do with a content-security problem in Safari, I commented out some lines in libaries/header_http.inc.php:
/*if (!$GLOBALS['cfg']['AllowThirdPartyFraming']) {
header('X-Frame-Options: SAMEORIGIN');
header("X-Content-Security-Policy: allow 'self' ;
options inline-script eval-script;
frame-ancestors 'self';
img-src 'self' data:");
if (PMA_USR_BROWSER_AGENT == 'SAFARI' && PMA_USR_BROWSER_VER < '6.0.0') {
    header("X-WebKit-CSP: allow 'self'; options inline-script eval-script");
} else {
    header("X-WebKit-CSP: default-src 'self';
    script-src 'self' 'unsafe-inline' 'unsafe-eval';
    style-src 'self' 'unsafe-inline'");
}*/

this seems to have worked - php index loading correctly with images. Not sure if I've just duffed up some major security though!


text:
Q: How do I pass in an explicit parameter to a Range object? I'm trying to get the cell of the first row of where the Range object is set. Also avoiding using Activate, Select as well. The range is dynamic (being updated to a new row in a loop) so using Offset won't work.
Here's what I have:
Set curr_ws = Worksheets("Data")
Dim data_curr_rng As Range
tool_sel = curr_ws.Range(data_curr_rng.Address(0, 0)).Offset(-4).Value
'Regardless of the column number of `data_curr_rng`, I need the cell in that column's Row 1

I've been playing around with the variable data_curr_rng but can't seem to figure out the right functions/properties to use.

A: You can use the Cells() function of the Worksheet
my_row = 1
my_column = 5
Set my_range = Application.ThisWorkbook.Sheets(1).Cells(my_row, my_column)

If you need to select a range of more than one cell you can wrap it in the Range like this
start_row = 1
start_column = 5
end_row = 10
end_column = 5
Set start_cell = Application.ThisWorkbook.Sheets(1).Cells(start_row, start_column)
Set end_cell = Application.ThisWorkbook.Sheets(1).Cells(end_row, end_column)
Set my_range = Application.ThisWorkbook.Sheets(1).Range(start_cell, end_cell)

A: The Cursor is located have an code for this , ActiveCell ,
you can use ActiveCell combined with Row and .End()
The code below returns the first cell UP (Ctrl+UpArrow)
   ActiveCell.End(xlUp)

The code below

A: Your original code is:

Set curr_ws = Worksheets("Data")
Dim data_curr_rng As Range
tool_sel = curr_ws.Range(data_curr_rng.Address(0, 0)).Offset(-4).Value
'Regardless of the column number of `data_curr_rng`, I need the cell in that column's Row 1

What you are asking is to take the selected range, identified the full column, and then took the first cell (which will be Row 1).
Set curr_ws = Worksheets("Data")
Dim data_curr_rng As Range
Set data_curr_rng = [Something] ` your example does not note how you set this.
' *** The solution to your question is below
Dim firstCellInColumn as Range ` could be cell etc. - using this to illustrate the concept
Set firstCellInColumn = data_curr_rang.EntireColumn.Cells(1,1)
' *** The back to your code
tool_sel = firstCellInColumn.Value

The EntireColumn method returns a range, and then in my example above, I just took the first cell in that range.


text:
Q: Declaration of class inside header file without initialization I want to declarate a class object of Class B inside of Class A in a header file, like:
// test.h

class A {
public:
    B b;

};

but lets say B has no default Constructor and the required parameters are not known yet (in header file). Which possibilities in c++ exist to declarate a class instance in another class without initializing it at that moment.

A: You need to initialize it. You need to, at least, declare it: class B.

A: Your example lacks any declaration of B, so you will get a compiler error. You must either add or include B's declaration, or you will need to forward declare it, e.g.
class B;

class A {
public:
    B b;  // Compiler error
};

However, this will still not work, since A needs to know the space to set aside for B. You may work around this, by making b a reference, pointer or smart pointer to B:
class B;

class A {
public:
    A();
    B* b1;
    B& b2;
    std::unique_ptr<B> b3;
};

For b1, b2 and b3, it is enough that you include the declaration of B in A's .cpp file and initialize the B's there:
// A.cpp

#include "A.h"
#include "B.h"

A::A() : b1(new B(<params>)), b2(<from a reference>), b3(make_unique<B>(params)
{}

Note that b1 is bad, since it uses new and needs to delete the object later, and that b3 will need a destructor defined in A.cpp (the default is fine).


text:
Q: Xcode 14.2 - Archive succeeds but does not appear anywhere(In Organizer) I have an Ionic Project(Hybrid Mobile Application) with Angular and Capacitor.
The App has Facebook and Google login. On development, all things and build are working fine. Problem: When I am making a release build for production then build and archive is showing success, but not showing anywhere in Organizer.
Has anyone has the same issue before or has any idea what can be wrong or how to fix?
#PFA
(https://i.stack.imgur.com/kAycc.png)(https://i.stack.imgur.com/I8T0I.png)(https://i.stack.imgur.com/pCdQE.png (https://i.stack.imgur.com/TRbBK.png)(https://i.stack.imgur.com/M34gF.png)
I have checked all permissions and other things but have not solved the issue.


text:
Q: netsuite site navigation setup Trying this again.
First of all, I apologize for my ignorance-I have never used Netsuite before. I recently started at a company that has been using Netsuite. Their site is already set up and in my job I have to edit the site on a daily basis. The hardest thing I have discovered so far is the lack of instructional information online for Netsuite and the organization. I am trying to change out or delete an rollover image on the side navigation bar. I can find all of the images for the initial navigation and their corresponding rollover image, but cannot find any of the subcategory images that come off these. I cannot find where these are set up either in Netsuite.
If I delete the image, will it disappear from the navigation bar or cause an error?
I've tried looking through the source code of the home page, but no luck there. Any suggestions on how to figure this out on a site already set up?


text:
Q: What database documents is more optimal searching only by key? MongoDB or Couchbase? Why? I need to search database documents only by their key, wich database engine would you prefer? MongoDB or Couchbase?
I don't know which is better in this case.
What database is more optimal searching by key?

A: Couchbase employee here,
Here are some reasons why Couchbase might be a better option:

*

*Couchbase's SDK is "cluster-aware", which means that just with the key of the document it knows exactly where the document is located, so for a KV use case the SDK will talk directly to the node which has the document (Instead of going to master and then to slave in Mongo's case)

*Couchbase has a cache layer on the top of the database, so if you need to load the same documents often, they will be automatically cached. (On mongo's case, you might need to use Redis for caching)

*Couchbase is highly scalable, so you can literally scale to dozens of nodes in a single cluster.

*It is strong-consistent by default

*If you ever need to explore your data, Couchbase supports SQL 92 (Select, group by, order, join, sort, etc). The query language is an extension of SQL (https://query-tutorial.couchbase.com/tutorial/#1)

*Sharding in Couchbase is transparent for the developer, so scaling out is a very simple operation. (Mongo requires resharding sometimes)
There are some other important factors that should be considered and weren't specified in your question.


text:
Q: R Language NaN + NA behaviour I have a question about arithmetic behaviour in R.
Regard the following piece of code
> NaN + NA
[1] NaN
>
>
> NaN + as.integer(NA)
> NA

So, I am confused that these two additions give different results.
Does anybody know if this is really wanted behaviour or just some kind of bug?
Thanks in advance

A: From ?NaN:

Computations involving NaN will return NaN or perhaps NA: which of those two is not guaranteed and may depend on the R platform (since compilers may re-order computations).


text:
Q: Second Order Differential Equation / Algebra Coefficient Problem - Arms Race Model I am working on a differential equations problem using Richardson's Arms Race Model (this isn't homework - I'm just curious). I am trying to work through the examples in the lecture located here. However, I am having trouble finding $y$ in the step at the end of the slide (below):

I was able to get to the step where $x'' + 4x -5x = 0$. Then, using an integrating factor of $x= e^{rt} $ , I was able to find that $x_1=e^{-5t}$ and $x_2={e^t}$.
This means that $x = Ae^{-5t} + Be^t$.
Now, I am trying to solve for y, and can't get the coefficients straight. So, I am not sure if my approach to solving the equation is wrong or if I am doing something silly algebraically.
Here is what I tried:
If $x = Ae^-{5t} + Be^t$, then $x'=-5Ae^{-5t}+Be^t$.
To find y, I need to plug x and x' into the the equation $ y=\frac12 x'+\frac12 x$.
This gives me:
$y = \frac12 (-5Ae^{-5t}+Be^t+Ae^{-5t}+Be^t)$
$y = \frac12 (-4Ae^{-5t}+2Be^t)$
$y = -2Ae^{-5t}+Be^t$
This is different from the equation found for y in the slides. From a differential equations, should I be taking a different approach to find y? I thought I should just be able to plug in x and x'. How did they get
$y = -4Ae^{-5t}+Be^t$?

A: Semi-independent verification: The matrix
$$
A=\begin{bmatrix}-1&2\\4&-3\end{bmatrix}
$$
has the characteristic polynomial
$$
z^2-tr(A)z+\det(A)=z^2+4z-5=(z+5)(z-1)
$$
with the roots $-5$ and $1$. The eigenvector for $z=-5$ has to solve $4v_x+2v_y=0$ which has as one non-trivial solution $v_x=1,\;v_y=-2$. The eigenvector for $z=1$ has to satisfy $-w_x+w_y=0$ which has as a solution $w_x=1=w_y$.
Thus the solution can be written as
$$
\begin{bmatrix}x(t)\\y(t)\end{bmatrix}
=
A·\begin{bmatrix}1\\-2\end{bmatrix}·e^{-5t}
+
B·\begin{bmatrix}1\\1\end{bmatrix}·e^t
$$
which coincides with your solution.


text:
Q: flutter_widget_from_html tags cannot using custom Styles Builder I am using flutter_widget_from_html: 0.9.0+1. Faced a problem, some widgets do not use customStyleBuilder and do not use TextStyle. Who creates a solution to the problem. Thanks in advance.
Its HTML string doesnt work
String value1 = '''

    Hello World Not Working

But this HTML string is working
String value = '''

       Hello World Working

''';

Flutter Widget Code
HtmlWidget(
        value,
        textStyle: TextStyle(
          fontFamily: 'Arial',
          fontSize: 20,
        ),
        customStylesBuilder: (element) {
          return {
            'font-size': '20px',
          };
        },

`
Thanks everyone for the help
I tried many different solutions but nothing worked. But i need use only flutter_widget_from_html, flutter_html not suitableю


text:
Q: Image rounded button JavaFX I´m working with rounded buttons and I want to have an image inside. The problem is that the image is in the center and not on the left even having called
loadButton.setAlignment(Pos.BASELINE_LEFT);
What I get is the button above and what I would need is the below button. Do you know any ways of displaying the png under the rounded corner?

   final Label response = new Label();
    final ImageView imageView = new ImageView(
            new Image("recordbutton.png")
    );
    imageView.setFitHeight(40);
    imageView.setFitWidth(40);

    loadButton.setGraphic(imageView);
    loadButton.setStyle("-fx-base: coral;");
    loadButton.setContentDisplay(ContentDisplay.LEFT);
    loadButton.setStyle(
             "-fx-background-radius: 100em; " +
                    "-fx-min-width: 60px; " +
                    "-fx-min-height: 60px; " +
                    "-fx-max-width: 130px; " +
                    "-fx-max-height: 60px;"
    );

Many thanks!

A: Instead of :
loadButton.setContentDisplay(ContentDisplay.LEFT);

use :
loadButton.setAlignment(Pos.CENTER_LEFT);


text:
Q: momentjs wrong date returned Im using momentjs in nodejs app and trying to parse timestamp string with momentjs to compare two dates. My code is:
moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss')

and the output is:
{ _date: Fri Nov 04 2016 00:00:00 GMT+0000 (GMT Standard Time) }

But with the given format im expecting the return date to be Sun Apr 10 2016.
Seems like the format option is not working or im missing something

A: It works for me (moment version: 2.12.0)
var moment = require('moment')
var m = moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss')
console.log(m.format('LLL')) // April 11, 2016 1:00 AM

Also changing days with months in both arguments works:
var m = moment('04/11/2016 01:00:00', 'MM/DD/YYYY HH:mm:ss') // same date as above

What version of moment are you using and how did you import it? How did you generate the output date? Is it just console.log?
(this should be a comment, but I wanted to add the code snippet)

A: Here's a sample code to return a string in your output format
var moment = require('moment');

var now = moment();
var date = moment('11/04/2016 01:00:00', 'DD/MM/YYYY HH:mm:ss');

console.log(now.format('ddd MMM D YYYY'));
console.log(date.format('ddd MMM D YYYY'));

A: Sorry it was my mistake. I've installed momentjs which is not the official moment package. After installing the moment package instead momentjs all is working as expected.


text:
Q: Want Func parameter name not the value, stored in dictionary I am having dictionary which store Funct.
While storing Func ( testDir.Add(1, p => p.Id) )its fine. When i get the Func from dictionary i want the name of property (Id) which i am stored in Func.
I had tried Retrieving Property name from lambda expression
Get property name and type using lambda expression this links. It works in simple Func.  But with dictionary i am getting member = null in GetMemberInfo.
 public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
    {
        var member = expression.Body as MemberExpression;
        if (member != null)
            return member.Member;

        throw new ArgumentException("Expression is not a member access", "expression");
    }

static void Main(string[] args)
        {
            Dictionary<int, Func<Soure.Employee, int>> testDir = new Dictionary<int, Func<Soure.Employee, int>>();
            testDir.Add(1, p => p.Id);
            var testDirValue = testDir[1];
            Expression<Func<Soure.Employee, int>> expr1 = mc => testDirValue(mc);
            MemberInfo member = Program.GetMemberInfo(expr1);
            Console.WriteLine(member.Name);
        }

A: The expression you have in expr1 does not actually hold the expression tree for p => p.Id. It holds the expression tree for the lambda mc => testDirValue(mc), which is an expression consisting of a call to an opaque delegate. There is no way to derive information about which property was accessed from this second lambda.
The information you want is encoded into the lambda literal syntax. Once it is stored and retrieved as an arbitrary delegate, this information is no longer available. What you actually want to do is store Expression<Func<Soure.Employee, int>> in your dictionary, so that an expression tree is built from the lambda you add to your dictionary:
var testDir = new Dictionary<int, Expression<Func<Soure.Employee, int>>>();
testDir.Add(1, p => p.Id);
MemberInfo member = GetMemberInfo(testDir[1]);
Console.WriteLine(member.Name); // Id


text:
Q: If I am told to reparameterize a curve by arc-length, what is the curve originally parameterized by? In differential geometry, you are often asked to reparameterize a curve using arc-length. I understand the process of how to do this, but I don't understand what we are reparameterizing from.
What is the curve originally parameterized by (before we REparameterize it by arc-length)?

A: It is parameterized by the parameter that appears in the parametric equations given to you !
It is often the case that there is a natural way to define a curve, be it from its geometric definition or from a convenient coordinate system, and the parameter stands out.
In the case of trajectories, it can be time.

Let's take the case of Viviani's curve: the intersection of a sphere and a cylindre of half the diameter, tangent to it.
In Cartesian coordinates, we have an implicit system of equations
$$\begin{cases}x^2+y^2+z^2=4,\\(x-1)+y^2=1.\end{cases}$$
Then letting $x-1=\cos t,y=\sin t$ by educated guess, we have
$$z=\pm\sqrt{4-x^2-y^2}=\pm\sqrt{2-2\cos t}=2\sin\frac t2.$$

A: It's completely arbitrary.
For example the "standard" parameterization of the unit circle is $\gamma(t) = [\cos(t),\sin(t)]$. But you could also sweep out a circle using the curves

*

*$\gamma(t) = [\cos(t^2), \sin(t^2)]$, which "speeds up" as you draw it;

*$\gamma(t) = [\cos(\sqrt{t}), \sin(\sqrt{t})]$, which "slows down" as you draw it;

*$\gamma(t) = [t, \sqrt{1-t^2}]$, which moves at constant speed in the $x$ direction while speeding up and slowing down in the $y$, etc etc etc.

If you have an arbitrary curve $\gamma(t):\mathbb{R}\to\mathbb{R}^n$, nothing is generally known in advance about the parameterization; the "speed" at which changing $t$ sweeps out the curve, measured by $\|\gamma'(t)\|$, could be arbitrary fast in some places in arbitrarily slow in others. The only assumption that's relatively common is to assume that the curve is regular: $\|\gamma'(t)\|>0$, which rules out some pathologies like cusps in the curve.


text:
Q: System.out redirection to JTextPane package htmlconsole;

import java.awt.BorderLayout;

public class HTMLConsole extends JFrame {

    private JPanel contentPane;
    private JTextPane textPane;

    public class Interceptor extends PrintStream
    {
        public Interceptor(OutputStream out)
        {
            super(out,true);
        }
        @Override
        public void print(String s)
        {
            super.print(s);
            textPane.setText(textPane.getText()+s);
        }

        @Override
        public void println(String s)
        {
            super.println(s);
            textPane.setText(textPane.getText()+"\n<br>");
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HTMLConsole frame = new HTMLConsole();
                    frame.setVisible(true);

                    System.out.println("Hello");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public HTMLConsole() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JTextPane textPane = new JTextPane();
        textPane.setEditable(false);
        textPane.setContentType("text/html");
        textPane.setText("");

        contentPane.add(textPane, BorderLayout.CENTER);

        //redirect stream
        PrintStream interceptor = new Interceptor(System.out);
        System.setOut(interceptor);
    }
}

Output:
Hellojava.lang.NullPointerException
    at console.Console$Interceptor.print(Console.java:29)
    at java.io.PrintStream.println(Unknown Source)
    at console.Console$Interceptor.println(Console.java:35)
    at console.Console$1.run(Console.java:47)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

How should I correct this program? It's very confusing that the exception is being thrown inside "print" method which hadn't been used!
UPDATE:
Exception disappeared after replacing JTextPane textPane = new JTextPane(); by textPane = new JTextPane();, but now nothing is being shown inside the window.

A: Your constructor calls
JTextPane textPane = new JTextPane(); // local variable declaration and initialization

instead of calling
this.textPane = new JTextPane()

So the textPane field, used by the interceptor, is null.
Also note that, as the stack trace shows, super.println() calls print(). That will cause every String passed to println() to be appended to the text pane twice.

A: You can implement your requirements using swing's MVC capabilities. Since a JTextPane has a document model you should think about adapting the model to the stream.
public class DocumentPrintStream extends PrintStream {

    public DocumentPrintStream(Document document, OutputStream delegateStream) {
        super(delegateStream);
        this.document = document;
    }

    @Override
    public void print(String string) {
        int offset = document.getLength();
        try {
            document.insertString(offset, string, null);
        } catch (BadLocationException e) {
        }
        super.print(string); // write to the delegate stream
    }
}

public Console() {
    ...
    JTextPane textPane = new JTextPane();
    contentPane.add(textPane, BorderLayout.CENTER);

    // redirect stream
    Document document = textPane.getDocument();
    DocumentPrintStream documentPrintStream = new DocumentPrintStream(
            document, System.out);
    System.setOut(documentPrintStream );
}

It has also the befefit that you can reuse the DocumentPrintStream with every component that is based on a Document model.
For example:

*

*JEditorPane

*JTextArea

*JTextField

*JTextPane

A: You're shadowing the variable textPane in the constructor of Console. Replace
JTextPane textPane = new JTextPane();

with
textPane = new JTextPane();


text:
Q: How to optimize the web speed of a Leaflet map I'm trying to optimize the speed of a web page, where a Leaflet map is included. According to GTMetrix and Google PageSpeed Insight, I should:

*

*Optimize the following images to reduce their size [several images served from 'https://services.arcgisonline.com/ArcGIS/rest/services/...'], serving them in next-gen formats

*Defer parsing of the JavaScript https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js

*Serve 'leaflet.js' and 'leaflet.css' inline

I would appreciate any similar experiences optimizing Leaflet maps. Is it worth serving JS and CSS of Leaflet inline? Can I modify the code to call 'arcgisonline.com' images in other lighter formats?
The code of my simple webpage
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css'>

Thank you very much.

A: this is quite old and may come a bit general to your question, but regarding geodata:

*

*you should decrease the amount of data that is loaded (i.e. do you really need all observations?)

*you should simplify the geometries if you work with polygons. The incredible mapshaper does a lot there for your speed. You can use it e.g. in R with the rmapshaper package to preprocess your data before.

*you could think of using vector tiles and implement a tileserver between backend and frontend that preloads your data for different zoom levels (use.e.g. geoserver) or alternatively tile the data dynamically inside your database (postgis is able to do that with st_AsMV()) and serve tiles to your leaflet interace which then needs  a plugin to create dynamic requests for the server based on the current bounding box of the map or alternatively use a webmapframework that supports tiling in the frontend (e.g. openlayers).

A: Most of the speed "optimizations" you refer to are general to webpages, there is little specific to Leaflet in particular.
Deferring is usually approached by simply placing your JS (including the Leaflet script tag) just before the end of your page body, so that it does not delay rendering of the rest of your HTML.
You can implement true deferring but then it becomes more complex ensuring your script executes after Leaflet is done loading; the easiest would be in that case to indeed inline Leaflet JS together with your script. But then you lose the potential cache of Leaflet asset, in case your visitor had browsed to other websites which have used these exact same assets.
In the case of Leaflet, you can also use a "skeleton" as a placeholder for your map, so that your visitor sees a static image while Leaflet and your script are loading. Make sure you have the right to host the static image.


text:
Q: Changing hour and NonExistentTimeError: 2019-03-31 01:50:24.455000 Here is my code
data = result["Document"]
df = pd.DataFrame(data)

df["Created"] = pd.to_datetime(df["Created"])

df["Created"] = pd.to_datetime(df["Created"],errors='coerce').dt.tz_localize('Europe/London').dt.tz_convert('Europe/Paris')
#print(df)hour
df['Created'] = df['Created'].dt.date

df["Barcode"] = df["Barcode"].astype(str)
fig, ax = plt.subplots()

myFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
ax.xaxis.set_major_formatter(myFmt)

df1 = df.groupby(["Created"])["Tag"].count().reset_index()
df2 = df[df["Tag"] == "DISPLAY"].groupby(["Created"])["Tag"].count().reset_index()
plt.plot(df2['Created'],df2['Tag'])
plt.plot(df1['Created'],df1['Tag'])
plt.gcf().autofmt_xdate()
plt.figure(figsize=(30,20))
plt.show()

The problem is that i have an hpur that don't exist :
 2019-03-31 01:50:24.455000

With the changing hour this timedate does not exist in france.
So that's why it crash.
How to convert the date taking that in count ?
Regards

A: Solution: update to pandas 0.24.2, then use the nonexistent argument to tz_localize, as in here:
df = pd.DataFrame()
df['Created'] = ["2019-03-31 01:50:24.455000"]
df["Created"] = pd.to_datetime(df["Created"],errors='coerce').dt.tz_localize('Europe/London', nonexistent='shift_forward').dt.tz_convert('Europe/Paris')

See here for more nonexistent shifting options:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.tz_localize.html


text:
Q: Stream no esta escuchando cuando escaneo un codigo qr Buenas esto creando un plugin para flutter nativo usando kotlin el cual su propósito es escanear códigos de barras y qr usando una librería especifica. Cree un eventchannel para poder escuchar cuando se escanea un código pero este no esta escuchando de nada.
Lam manera en que funciona mi aplicación es que tengo un initstate donde mando a llamar el método de initScanner(), ya una vez que se ha cargado el estado de la aplicación tengo un onPress el cual primero ejecuta la función openScanner() el cual esta me regresa un status 1 que de acuerdo con la librería que uso significa OPEN_SCANNER_ISDECODING. A después de que corre la funcion openScanner() mando a llamar mi stream de la siguiente manera:  _scannerPlugin.qrCodeStream?.listen((event) => log('QR code: $event'));, pero mi problema es que nunca entra al stream e imprime el log.
Antes de hacer el listen hago un inspect de qrCodeStream y me regresa la siguiente información:

El siguiente es mi código en kotlin.

private var method : MethodChannel ?= null
  private var event : EventChannel ?= null
  private var mEventSink : EventChannel.EventSink ?= null

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    ScannerManager.init(flutterPluginBinding.applicationContext)
    method = MethodChannel(flutterPluginBinding.binaryMessenger, "scanner")
    event = EventChannel(flutterPluginBinding.binaryMessenger, "scanner_stream")
    method!!.setMethodCallHandler(this)
    event!!.setStreamHandler(this)
  }

override fun onMethodCall(call: MethodCall,  result: Result) {
    val instance : ScannerManager = ScannerManager.getInstance()
    when (call.method) {
      "init" -> {
        scannerListener()
        result.success(instance.initScanner())
      }
      "open" -> {
        result.success(instance.OpenScanner())
      }
      else -> result.notImplemented()
    }
  }

  private fun scannerListener() {
        ScannerManager.getInstance().addScannerManagerListener(object : ScannerManagerListener {
          override fun Error(errcode: Int, msg: String?) {
            val result = object {
              var status = errcode
              var msg = msg
            }
             mEventSink!!.success(result)
          }

          override fun decodeResult(statusCode: Int, msg: String?) {
            val result = object {
              var status = statusCode
              var msg = msg
            }
             mEventSink!!.success(result)
          }
        })
  }

  override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
    mEventSink = events
  }

  override fun onCancel(arguments: Any?) {
    mEventSink = null
  }

Ya después en la parte de código donde mando a llamar mi methodchannel y event channel
class MethodChannelScanner extends ScannerPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  static const methodChannel = MethodChannel('scanner');
  static const eventChannel = EventChannel('scanner_stream');

  @override
  Future<int?> initScanner() async =>
      await methodChannel.invokeMethod<int?>('init');

  @override
  Future<int?> openScanner() async =>
      await methodChannel.invokeMethod<int?>('open');

  @override
  Stream<dynamic>? get qrCodeStream {
    return eventChannel.receiveBroadcastStream();
  }
}

El siguiente enlace lleva a la documentación de la librería que estoy usando:
https://sistemas.cruzperez.com/felipe/Hytera%20Scanner%20API%20Reference%20V00.pdf


text:
Q: Having more than one schema configured in Prisma in a nodeJS project Is it possible to have more than one schema configuring for the prisma?
I know you can configure a schema in package.json, I would like to know if you can do this with two different bases.

A: I do not know if I understood well, but I think that you are looking for something like this


text:
Q: Not showing the updated DataTable after removing the row with ajax in ASP.NET MVC need to reload the page I have a DataTable to display the book data. After clicking the delete button, the book record is successfully deleted from the database. However, I have to reload the page for the updated the DataTable.
How can I delete the row in UI?
View:

        ...

        @foreach (var book in model)
        {

                @Html.ActionLink(book.Name, "Details", "Books", new { id = book.Id })
                @book.Author
                @book.Type.Type
                @book.NumberInStock

                    //Delete Button
                    <button data-book-id="@book.Id" class="btn btn-danger js-delete book-delete">Delete</button>

        }

Ajax call: I don't want to use location.reload(); to reload the page
$(document).ready(function () {
        var myDataTable = $("#books").DataTable({
            "drawCallback": function (settings) {
                $("#books .book-delete").on("click", function (e) {
                    var button = $(this);
                    var result = confirm('Are you sure you wish to delete this book?');
                    if (result) {
                        var form = $('#__AjaxAntiForgeryForm');
                        var token = $('input[name="__RequestVerificationToken"]', form).val();
                        $.ajax({
                            url: "/Books/Delete/" + button.attr("data-book-id"),
                            method: "POST",
                            data: {
                                __RequestVerificationToken: token,
                                someValue: "Your Custom Secret String"
                            },
                            success: function () {
                                location.reload();
                            },
                            statusCode: {
                                500: function () {
                                }
                            }
                        });
                    }
                });
            }
        });
    });

A: Can you try this? I can't try it my self.
   $(document).ready(function () {
      var myDataTable = $("#books").DataTable({
        "drawCallback": function (settings) {
            $("#books .book-delete").on("click", function (e) {
                var button = $(this);
                var result = confirm('Are you sure you wish to delete this book?');
                if (result) {
                    var form = $('#__AjaxAntiForgeryForm');
                    var token = $('input[name="__RequestVerificationToken"]', form).val();
                    $.ajax({
                        url: "/Books/Delete/" + button.attr("data-book-id"),
                        method: "POST",
                        data: {
                            __RequestVerificationToken: token,
                            someValue: "Your Custom Secret String"
                        }
                    myDataTable.row($(this).parents('tr')).remove().draw();
                   // you can also try this
                   // $('#books').DataTable().ajax.reload();
                    });
                }
            });
        }
    });
});


text:
Q: Unity3d Facebook SDK 6.2.2 Error ![Xcode screen][1]
XCode Error, how to fix this problem? FBSDKLoginKit present in library list. Maybe unity3d 5 doesn't support Facebook SDK 6.2.2 version?

Ld
  /Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Intermediates/Unity-iPhone.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/slotspanther
  normal armv7
      cd /Users/Arahis/Builds/Build1
      export IPHONEOS_DEPLOYMENT_TARGET=7.0
      export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
      /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
  -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk
  -L/Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Products/Release-iphoneos
  -L/Users/Arahis/Builds/Build1 -L/Users/Arahis/Builds/Build1/Libraries -L/Users/Arahis/Builds/Build1/Libraries/Plugins/IOS -F/Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Products/Release-iphoneos
  -F/Users/Arahis/Builds/Build1 -filelist /Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Intermediates/Unity-iPhone.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/slotspanther.LinkFileList
  -Xlinker -map -Xlinker /Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Intermediates/Unity-iPhone.build/Release-iphoneos/Unity-iPhone.build/slotspanther-LinkMap-normal-armv7.txt
  -dead_strip -weak_framework CoreMotion -weak-lSystem -stdlib=libc++ -fobjc-arc -fobjc-link-runtime -miphoneos-version-min=7.0 -framework Security -framework Social -framework GameKit -framework Accounts
  -framework CoreTelephony -framework MobileCoreServices -framework StoreKit -framework CoreText -framework Foundation -framework UIKit
  -framework OpenGLES -framework QuartzCore -framework OpenAL -liconv.2 -framework AudioToolbox -framework CFNetwork -framework MediaPlayer -framework CoreLocation -framework SystemConfiguration -weak_framework iAd -framework CoreMedia -framework CoreVideo -weak_framework
  AVFoundation -framework CoreGraphics -weak_framework CoreMotion
  -liPhone-lib -lFlurry -lOneSignal -framework FBSDKLoginKit -framework FBSDKShareKit -framework Bolts
  /Users/Arahis/Builds/Build1/Libraries/Plugins/IOS/MobileAppTracker-3.9.1.a
  -framework FBSDKCoreKit -Xlinker -dependency_info -Xlinker /Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Intermediates/Unity-iPhone.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/slotspanther_dependency_info.dat
  -o /Users/Arahis/Library/Developer/Xcode/DerivedData/Unity-iPhone-ciwadoyxuyddvuagqxleasaxynhi/Build/Intermediates/Unity-iPhone.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/slotspanther

ld: framework not found FBSDKLoginKit
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: Starting with version 7 the "Facebook SDK for Unity" will supports Unity 5 fully.
You can download 7.0.2, which is currently in beta at the bottom of this page:
https://developers.facebook.com/docs/unity/downloads


text:
Q: "Algorithm negotiation fail" error in JSch when trying to connect to Symantec NetBackup - grabing reports remotely I have been searching online and found similar posts but could not find a solution reading them.
I am trying to connect to NetBackup servers using ssh from my computer and run a report and create graphs based on them. I am doing this using java and JSch library. The problem is that I get:
"Algorithm negotiation fail" at com.jcraft.JSch.Session.recieve_kexinit(...
I know very little about negotiations and keys and different methods such as diffie-hellman etc. Could you please tell me:
1. How can I find out what methods does the server accept?
2. If I need to set up a negotiation method, how would I do that?
The logger only tells me this:
The remote version string: SSH-2.0-OpenSSH_5.1
The local version string: SSH-2.0-JSCH-0.1.31
SSH_MSG_KEXINIT received
SSH_MSG_KEXINIT sent
PS. I am working under a restricted system, meaning that I cannot make changes on the server. Please let me know if you need additional information.
Thanks

A: After doing a lot of research, I figured that to be able to have an SSH connection with Netbackup, you have to create a local user with access to bash shell, then allow root access to this user, since the netbackup commnands require you to be a superuser. Then, you can have ssh access to that account and run the scripts you want remotely. If you want to use Jsch, you jave to download and install Java criptography Extension in C:\Program Files\Java\jre6\lib\security. But I could not do that since I want not allowed due to company policies. So, I created powershell scripts that my Java program runs in order to connect and run the reports and put the output in a text file.
There are applications such as Opscenter that already create reports for you; however, if you are in a situation like me where you need customized reports, this is the way to go.
Hope this helps.


text:
Q: How to update specific key/values in object efficiently using a sort-type function I am creating a JavaScript game of tic-tac-toe and trying to make it smart enough to make wise moves based on the strategy outlined in Wikipedia article. I.E., if there is a row or column that has two Xs or two Os in it, take the empty spot. So, given a row or column of key value pairs, let's say the values might be:
obj {
  key1: "X",
  key2: "",
  key3: "X",
}
I have been working on a way to do this for a while, and am curious if there are ways to do this other than a series of loops. My first attempt was to try to sort the items alphabetically so I could isolate the blank value: var = "","X","X"
In this case I can easily call the first item and update it, but I cant reverse it to what it was and update it in its original position in the object. However, I can't seem to figure out how to do this in a way that isn't creating a lot of wasteful code. Would it perhaps be better to separate into multiple loops? One to isolate the rows and columns (there are 8 of them) that have one blank spot?
Another idea I had is to give each value in the grid a value of 1, and then look through the grid and if a row is equal to 3 (create var that joins them and uses the .eval() method), then make each item equal to 1, hence updating the blank spot to 1 and updated the other two spots that are already 1.
I tried to be as specific as possible but I am not great at explaining this particular problem, I admit.
Here is a JS fiddle I made:
https://jsfiddle.net/1hup5195/
Here is some of my script for reference:
$(document).ready(function(){
var playerTurn = true;
var buttonStatus = "allowclick"; // Change to inactive once game starts
var player = "";
var machine = "";
var test = "";
var emptyObj = {1: "", 2: "", 3: "",
                4: "", 5: "", 6: "",
                7: "", 8: "", 9: ""};
var gridObj = {1: "", 2: "", 3: "",
               4: "", 5: "", 6: "",
               7: "", 8: "", 9: ""};
var winningObj = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]];

// Check if player is holding a corner
function machineFunction() {
    // Loop through winningObj and check if there are rows/columns with 2/3 taken
    // for(i = 0; i < winningObj.length; i++) {
        var i = 3;
        var alpha = winningObj[i][0];
        var bravo = winningObj[i][1];
        var charlie = winningObj[i][2];
        console.log(alpha);
        console.log(bravo);
        console.log(charlie);
        // After defining alpha/bravo/charlie, fire the fxn
        testFxn(alpha, bravo, charlie);
        // This is my function to sort the 3 different spots within the grid
        function testFxn(a,b,c) {
            // Test would be equal to ["", "X", "X"] or something similar
            var test = [gridObj[a], gridObj[b], gridObj[c]].sort();
            console.log(test);
            console.log(gridObj);
            // If 2/3 spots taken by either X or O, take this spot
            if (test[0] === "" && test[1] === "X" && test[2] === "X") {
                console.log("#" + alpha + "")
                $('#' + alpha + '').html(machine);
                gridObj[alpha] = machine;
                console.log(gridObj);
                $(this).html(machine); // Sends player over to html
                gridObj[this.id] = machine; // Update gridObj object
                playerTurn = true;
            }
            if (test[0] === "" && test[1] === "O" && test[2] === "O") {
                // How do I get the ID I need??
                $('#' + test[0] + '').html(machine);
                playerTurn = true;
            }
        };

A: You can do sth like this ( using some to iterate... ):
var rows = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]];
var gridObj = {1: "", 2: "", 3: "",
           4: "", 5: "", 6: "",
           7: "", 8: "", 9: ""};

rows.some(function(row){//iterate over all rows
   var values=row.map(key=>gridObj[key]);//get the rows values
   if(values.filter(el=>el==="X").length===2){//check if there are two Xses
      gridObj[rows[values.indexOf("")]]="O";//get the field id and add O to the blank field
      return true;//stop iterating the rows
   }
});

http://jsbin.com/miriwuhuce/edit?console

A: I would like to comment, but I can't. So here is my comment as answer...
If you make an object of each "field", you can reference it in different arrays. So you can do an array.copy, sort that one and then change the value in the object.
This will also set the value in the other arrays holding the same objects.
Good luck!

A: Javascript has a great function called map and can be used on arrays. Here is documentation.
What map does is provide a callback that will perform some defined function on each element in an array, (possibly checking winning states against the current state), and returning a new array with those changed, or unchanged, values. For example, you can have an array of winning states like you do now, and do
var winner = winningObj.map((item) => {  // ()=>{} is ES6 syntax. Same as function(){}
    var token = {}
    if currentState[item[0]] != empty
        token.1st = X

    if currentState[item[1]] != empty
        token.2nd = X
    if currentState[item[2]] != empty
        token.3rd = X

    if all tokens are X
        return X        // winner!
    else if all tokens are O
        return O      // check the other winning conditions, or keep playing
    else
        return false
);

if winner.containsValue(X)
    X wins
else if winner.containsValue(O)
    O wins
else
    keep playing

I know this doesn't really answer your question in terms of better efficiency, but this way you can avoid having to write out any loops and let map() do all the work for you.


text:
Q: Comparing characters in MIPS, and doing character arithmetic Basically, I want to compare two characters using a branching statement in MIPS. Although I am not really sure as to what instructions to use for this. Anyways I will show my pseudo code I wrote for it in C.
The array M contains characters.
if(M[i] >= "0" && M[i] <= "9")
{
    ascii_to_bin += M[i] - "0"
}

That is just one of the if statements, but it encapsulates every question I have at the moment. I don't know which instructions to use when making the comparison in the conditional statement. Furthermore, the line $ascii_to_bin += M[i] - "0"; do not really know how to do character arithmetic in MIPS.

A: As you probably know, the only reason you can do arithmetic on characters in C (And C++, Java, etc.) is that char types can be implicitly converted into int types, via their ASCII value.
However, MIPS (And assembly languages more broadly) don't have a notion of types; any notion of a variable containing a "character" is imposed by the programmer, not by the machine.
So what does that mean? It means you're working with the integer value directly. If you pull what you know to be the character a from memory, you're actually working with the ASCII value instead, 97. And you can compare that as if it were any other integer (Because it is any other integer).
So your if-statement will then look roughly like this (In pseudocode):
If M[i] >= 48 and M[i] <= 57 then:
  ascii_to_bin += M[i] - 48


text:
Q: Using field parameters in calculate field I am attempting to make a generic tool to move existing points to an already defined XY.  What I want to do is have the user define the feature class, then the X field and Y field from that feature class, then run the Calculate Field with those X and Y fields.  Below is what I have, but I know I am going about it the wrong way (fairly new to ModelBuilder).  I can't find a way to associate those first Field Parameters with the feature class.

I know I can just use the same X and Y field names every time and it will work, but I want the tool to be as versatile as possible.

A: You basically have everything set up, you just need to connect your X and Y fields (already modelled as input parameters for your model) to the "Calculate Field" process/box.  First, make absolutely sure that these variables are of type "Field" - this is essential.  If this is not the case, you can either adjust the properties or create a new Variable of type Field, then set Display Properties to show them as "X Field" and "Y Field" if desired.  But when these are the correct type, you'll be able to use model builder's Connect tool to click from each field, in sequence, as a modelled parameter, to the Calculate Field process.  At the pop-up option dialog, select "Precondition".  NOTE - this must be done BEFORE you connect your input table to the Calculate Field box, or you can't use these field variables in the calculation.
When you go back into the tool properties after setting this up, you'll have to reference your two new fields as input variables into the Expression function, like this:  Update("%Field%", "%Field (2)%")  assuming the field variables get the default naming, as shown below.
Your code block would be unchanged.  This way, you can use your model as a tool/process as intended where those variable names might change, and would need to be specified each time it is run.


text:
Q: Хранение данных в приложении В приложении должны быть текстовые данные. Пробовал хранить данные в xml, но после того как я их распарсил выводиться сплошной текст без обзацев, табуляций и т.п.
В каком формате еще можно хранить данные в приложении, чтобы отображался на экране в нормальном виде?

A: Если вы хотите хранить данные в приложении iOS, лучше всего использовать SQLite (Core Data) или Realm (он проще для новичка, чем Core Data).
Соответственно вы сможете хранить текст в виде NSString.
Могу предложить еще альтернативный вариант, если у вас не очень много данных. Вы можете хранить текст прямо в NSUserDefaults.
Например вот так:
UserDefaults.standard.setValue(text_my_book, forKey: "book1")
print("\(UserDefaults.standard.value(forKey: "book1")!)")

A: Если данных не много, можно просто выводить их файл (сериализовать). Например, NSArray  и NSDictionary имеют собственные методы записи и восстановления в\из файла
- (BOOL)writeToFile:(NSString *)path
     atomically:(BOOL)useAuxiliaryFile;
- (NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path;

В случае массивов(или словарей) языка Swift ситуация выглядит чуть хуже, но можно использовать plist формат (xml) и пользоваться
NSKeyedArchiver.archiveRootObject(yourArray, toFile: filePath)

и распаковать
let restoredArray = NSKeyedUnarchiver.unarchiveObject(withFile path:filePath)

ничего специально парсить не придется

A: Храни их в JSON. Будет удобно!

A: Для хранения текстовой информации отлично подойдет JSON и Plist файл. Все зависит от того как вы их хотите читать.
Plist файл можно распарсить в Dictionary, вообщем как и JSON, но если хардкодить данные то мне больше нравиться плист т.к. приятный интерфейс работы с ним.


text:
Q: nodejs tls session id I am using TLS to create session using node.js library. Node.js does it provide a way to retrieve session id of TLS connection established. It is part of SSL ctx in openssl.
Can it be done without using connect, express or geddy?

A: Unfortunately I don't think that information is exposed from the SSL context for node connections.
You can access the node object representing the context as follows:
var con = tls.connect(..., ...);

con.pair.credentials.context

Unfortunately, the only methods available on that object are setKey, setCert, addCACert, addCRL, addRootCerts, setCiphers and setOptions.
That said, with a little bit of C++ and SSL know-how and come copy/pasting, you could probably patch node's node_crypto.cc and node_crypto.h files to add that lookup without TOO much work.

A: You can't get the session_id but you can get the session itself for caching / resume purposes by calling conn.getSession() once the connection is established.


text:
Q: I am getting the date and revenue_rates_usd columns, but when I try to get range between two dates, I get and error pd.read_sql("SELECT * FROM usd_rates;", conn)

   id        date                                  revenue_rates_usd
0  93  2021-07-23  {'AED': 3.673, 'AFN': 79.600004, 'ALL': 103.8,...
1  94  2021-07-24  {'AED': 3.673, 'AFN': 79.600004, 'ALL': 103.8,...

pd.read_sql("SELECT date as date, revenue_rates_usd ->> 'SAR' AS SAR FROM usd_rates;", conn)

         date       sar
0  2021-07-23  3.750918
1  2021-07-24  3.750712

pd.read_sql("SELECT date as date, revenue_rates_usd ->> 'SAR' AS SAR WHERE date BETWEEN '2021-07-23' AND '2021-07-24', FROM usd_rates';", conn)

Error = Execution failed on sql 'SELECT date as date, revenue_rates_usd ->> 'SAR' AS SAR WHERE date BETWEEN '2021-07-23' AND '2021-07-24', FROM usd_rates';': syntax error at or near ","
LINE 1: ...R WHERE date BETWEEN '2021-07-23' AND '2021-07-24', FROM usd...

A: Before the "From" you have a comma (,) and the "From" is after that "Where", probably that is the problem.
pd.read_sql("SELECT date as date, revenue_rates_usd ->> 'SAR' AS SAR FROM usd_rates WHERE date BETWEEN '2021-07-23' AND '2021-07-24';", conn)


text:
Q: How to display name from custom attribute in product view page Currently product name (title) is displayed from attribute name.
How to display product name (title) from custom attribute second_name on product view page?

A: Setp 1 :- Go to or override app/design/frontend/Your_CompanyName/Your_ThemeName/Magento_catalog/layout/catalog_product_view.xml and add this code.
<block class="Magento\Catalog\Block\Product\View\Description" name="product.info.demo" template="product/view/demo.phtml" after="page.main.title">
    <arguments>
        <argument name="at_call" xsi:type="string">getProductName</argument>
        <argument name="at_code" xsi:type="string">product_name</argument>
        <argument name="css_class" xsi:type="string">product_name</argument>
        <argument name="at_label" xsi:type="string">ProductName</argument>
        <argument name="add_attribute" xsi:type="string">itemprop="product_name"</argument>
    </arguments>
</block>

Above code attribute name change as per your attribute name. Custom Attribute Just i have shown after main product title.
Step 2 :- Create New file like app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_catalog/templates/product/view/demo.phtml. Add below code
<?php
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_product = $block->getProduct();
$_code = $block->getAtCode();
$_className = $block->getCssClass();
$_attributeLabel = $block->getAtLabel();
$_attributeType = $block->getAtType();
$_attributeAddAttribute = $block->getAddAttribute();
if ($_attributeLabel && $_attributeLabel == 'default') {
$_attributeLabel = $_product->getResource()->getAttribute($_code)->getFrontendLabel();
}
$_attributeValue =$_product->getResource()->getAttribute($_code)->getFrontend()->getValue($_product);
?>
<?php if ($_attributeValue): ?>

    <div class="value" <?php echo $_attributeAddAttribute;?>><?php echo $_attributeValue; ?>

<?php endif; ?>

After you run below one command like:-
- php bin/magento c:f
Output :-

Other thing if you want to show listing page. Follow below setps
Setp 1 :- Go to your custom attribute and To Display, the new attribute in List Page, set the value "YES" to "Used in Product Listing" under storefront Properties while creating the attribute.
Setp 2 :- To display the attribute value in product list page, add the below code in app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_Catalog/templates/product/list.phtml. Add below code.
<?php echo$_item->getDemoLink(); ?>
THANKS.


text:
Q: Vigenere Cipher Encrypt and Decrypt I have written a piece of code that has a Caesars cipher and then a Vigenere Cipher that follows. The code give a choice to encrypt or decrypt and the encrypting works fine however the decrypt doesn't. What have I done wrong?
  playing = True
    string = ""
    Alphabet = ('z','a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')

    def EncryptVigenere():
            plainText = input("Please enter the plain text: ")
            key = input("Please enter the key: ")
            keyList = []
            keyLength = 0
            num = 0
            while keyLength < len(plainText):
                try:
                    char = key[num]
                except IndexError:
                    num = 0
                    char = key[num]
                keyList.append(str(char))
                keyLength += 1
                num+= 1
                CipherText = []
                IndexValue = 0
                keyIncrement = 0
            for plainTextChar in plainText:
                 IndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar)
                 while IndexValue > 26:
                     IndexValue = IndexValue - 26
                 CipherText.append(Alphabet[IndexValue])
                 keyIncrement = keyIncrement + 1
                 print (''.join(CipherText))

            finish = input('Would you like to go again Y or N')
            if finish == 'n' or finish == 'N':
                retry = input ("Would you like to go again? Y or N: ")
                if retry == 'N' or retry == 'n':
                    print ("Please exit the window")
                    import time
                    time.sleep(1)
                    import sys
                    sys.exit()

    def DecryptVigenere():
                plainText = input("Please enter the plain text: ")
                key = input("Please enter the key: ")
                keyList = []
                keyLength = 0
                num = 0
                while keyLength < len(plainText):
                    try:
                        char = key[num]
                    except IndexError:
                        num = 0
                        char = key[num]
                    keyList.append(str(char))
                    keyLength += 1
                    num -= 1
                    CipherText = []
                    IndexValue = 0
                    keyIncrement = 0
                for plainTextChar in plainText:
                     IndexValue = Alphabet.index(keyList[keyIncrement]) - Alphabet.index(plainTextChar)
                     while IndexValue > 26:
                         IndexValue = IndexValue - 26
                     CipherText.append(Alphabet[IndexValue])
                     keyIncrement = keyIncrement + 1
                     print (''.join(CipherText))

                finish = input('Would you like to go again Y or N')
                if finish == 'n' or finish == 'N':
                        retry = input ("Would you like to go again? Y or N: ")
                        if retry == 'N' or retry == 'n':
                                print ("Please exit the window")
                                import time
                                time.sleep(1)
                                import sys
                                sys.exit()

    while playing == True:
        keyIncrement = 0
        string = ""
        eord = input('Type "d" to "decrypt" and "e" to "encrypt": ')

        if eord == 'e':
            texte = input ("Type your word to encrypt: ")
            key1 = int(input("Choose a key between 1-26: "))
            for letter in texte:
                number = (ord(letter)) + (key1)
                letter=(chr(number))
                string = (str(string)) + (str(letter))
            print (string)
            keyword = input ("Type 'encrypt' code further or 'decrypt' further: ")

            if keyword == 'encrypt' or keyword == 'e':
                EncryptVigenere()

            elif keyword == 'decrypt' or keyword == 'd':
                DecryptVigenere()

        elif eord == 'd':
            texd = input ("Type your word to decrypt: ")
            key2 = int(input("Choose a key between 1-16: "))
            for letter in texd:
                number = (ord(letter)) - (key2)
                letter=(chr(number))
                string = (str(string)) + (str(letter))
            print (string)
            keyword = input ("Type 'encrypt' code further or 'decrypt' further: ")

            if keyword == 'decrypt' or keyword == 'd':
                DecryptVigenere()

            elif keyword == 'encrypt' or keyword == 'e':
                EncryptVigenere()

When I try to print a decrypted code using the Vigenere cipher the code output isn't correct. Thanks in advance:).


text:
Q: Cascading Dropdown list in .NET 6 MVC getting 404 error I am trying to build a cascading dropdown list with a list of countries mapped with their corresponding states. The data is being accessed from SQL Server. I am able to build the country list using the db. However, I am unable to see the data for the states.
CountryStateService.cs:
public async Task<IEnumerable<StateModel>> GetStates(int countryId) {
    var data = await (from cs in db.CountryStates
                      where cs.IdCid == countryId
                      select new StateModel
                      {
                        stateId = cs.stateId,
                        stateName = cs.stateName,
                        IdCid = cs.IdCid
                      }).ToListAsync();

    return data;
}

Home Controller:
[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
    var stateCollection = await _service.GetStates(countryId);
    List<StateModel> stateList = stateCollection.ToList();

    ViewBag.StateList = stateList;
    return View();
}

JQuery: [This is likely the problem as I am unable to see the data.]

<script type="text/javascript">
    $(document).ready(function() {
        $('#countryDropDown').change(function() {
            // show the state dropdown only if a country is selected
            if ($('#countryDropDown option:selected').text != '') {
                $('#stateDropDown').prop('disabled', false);

                var selectedCountry = $(this).val();
                var options = `<option value=0> Select State </option>`

                $('#stateDropDown').empty();

                // get the location of the selected country
                $.getJSON("/Home/LoadStateForCountry/?countryId=" + selectedCountry, function(data) {
                    $.each(data, function(i, stateDetails) {
                        options += "<option value=" + this['stateId'] + ">" + this['stateName'] + "</option>"
                    });

                    $("#stateDropDown").html(options)
                })

            } else {
                $('#stateDropDown').prop('disabled', true);
            }
        });
    });

Razor Page
<select class="form-control form-control-md my-2"
        id="stateDropDown"
        placeholder="Select State"
        asp-items="@ViewBag.StateList">
</select>

A: Since you want to get data from LoadStateForCountry,you should return stateList in the action:
[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
    var stateCollection = await _service.GetStates(countryId);
    List<StateModel> stateList = stateCollection.ToList();

    //ViewBag.StateList = stateList;
    return new JsonResult(stateList);
}


text:
Q: Repeat String Infinitely - Return Count of Specific Character Within N Length of Infinite String - JavaScript Trying to solve this HackerRank challenge:

Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first  letters of Lilah's infinite string.
For example, if the string s = abcac and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of "a" in the substring.

I wrote:

function repeatedString(s, n) {

    s = s.repeat(n);
    s = s.slice(0, n);

    let array = Array.from(s);
    let count = 0;
    for (let i = 0; i < array.length; i++) {
        let char = array[i];
        if (char.match(/[a]/gi)) {
            count++;
        }
    }
    return count;
}
console.log(repeatedString("abcac", 10));

But HackerRank does not like s = s.repeat(n);, apparently:

I'm not sure how else to generate a string of an appropriate length to slice from. s = s.repeat(Infinity) does not work, and s is not already repeated an infinite number of times when it's passed in as a parameter.
I.e. console.logging(s), initially, logs

abcac

In this case.
I also tried:

function repeatedString(s, n) {

  let j = n;
  let newString = "";
  while (n > 0) {
      newString += s;
      n--;
  }

  newString = newString.slice(0, j);
  let count = 0;
  let array = Array.from(newString);

  for (let i = 0; i < array.length; i++) {
      let char = array[i];
      if (char.match(/[a]/gi)) {
          count++;
      }
  }
  return count;
}
console.log(repeatedString("abcac", 10));

But this caused a timeout error.
Any other ideas for how to create a string of valid length to slice from?
EDIT:
Constraints:

1 <= |s| <= 100
1 <= n <= 10^12
For 25% of the test cases, n <= 10^6

A: actually repeating the string n times is a tremendous waste of memory and runtime.
just compute how often the entire string would be repeated times how many as the string has plus the number of as in the part of s.slice(0, n%s.length)
And your runtime goes down to s.length instead of n

function repeatedString(s, n) {
  var r = n % s.length,
    m = (n - r) / s.length,
    count = 0;

  for (var i = 0; i < s.length; ++i) {
    if (s[i] === "a") {
      count += m + (i < r);
    }
  }
  return count;
}

console.log(repeatedString("abcac", 1234567890));

A:

function repeatedString(s, n) {
  var r = n % s.length,
    m = (n - r) / s.length,
    count = 0;

  for (var i = 0; i < s.length; ++i) {
    if (s[i] === "a") {
      count += m + (i < r);
    }
  }
  return count;
}

console.log(repeatedString("abcac", 1234567890));

A: I tested this and knows it works. Essentially, I'm not creating a new string, I just find out how many times I have to multiply the original string in order to be able to truncate it. Then I multiply that number by how many a's there were in the original string.

function repeatedString(s, n) {

    var charLength = s.length;
    var repeat = Math.floor(n/charLength);
    var remainder = n%(charLength);
    var strCut = s.slice(0, remainder);

    let count = 0;
    let arrayX = Array.from(s);
    for (let i = 0; i < arrayX.length; i++) {
        let char = arrayX[i];
        if (char.match(/[a]/gi)) {
            count++;
        }
    }

    count = count * repeat;

    let arrayY = Array.from(strCut);
    for (let i = 0; i < arrayY.length; i++) {
        let char = arrayY[i];
        if (char.match(/[a]/gi)) {
            count++;
        }
    }

    return count;
}

console.log(repeatedString("abcac", 10));

A: I tried a small solution with .repeat but as Thomas said, it's expensive and was taking ages to run tests.

function repeatedString(s, n) {
    const allAs = s.match(/a/g);
    if (!allAs) {
        return 0;
    }
    if (s === 'a') {
        return n;
    }
    const reps = s.repeat(Math.ceil(n/s.length)).slice(0, n).match(/a/g)
    if (!reps) return 0;
    return reps.length;
};

console.log(repeatedString('abc', 10));
console.log(repeatedString('abcde', 10));

But I followed Thomas idea and came up with a simpler solution

function repeatedString(s, n) {
    const allAs = s.match(/a/g);
    if (!allAs) {
        return 0;
    }
    if (s === 'a') {
        return n;
    }
    const rem = n % s.length;
    const reps = (n-rem)/s.length;
    let count = reps * allAs.length;
    if (rem) {
        const rest = s.slice(0, rem).match(/a/g);
        if (rest) count = count + rest.length
    }
    return count;
}

console.log(repeatedString('a', 100000));
console.log(repeatedString('abcde', 10000000000));

A: You could use while loop to repeat original string until length is matched and then match to count the numbers of a.

function repeatedString(s, n) {
  let i = 0, l = s.length;
  while (s.length < n) s += s[i++ % l]
  return s.match(/a/g).length;
}
console.log(repeatedString("abcac", 10));

A: I did this code and it worked well.
function repeatedString(s, n) {
    let modulus = n % s.length;
    let repetition = (n - modulus) / s.length;
    let remainCounts = s.slice(0, modulus).split("").filter((item) => item == "a").length

    return (s.split("").filter((item) => item == "a").length * repetition) + remainCounts
}

enter image description here


text:
Q: Error adding service reference: Type is a recursive collection data contract which is not supported I tried to add a service reference to a WCF service that resides in the same solution from an ASP.NET MVC 4 project but failed. I got a error saying:

Custom tool error: Failed to generate code for the service reference
  'XXX'. Please check other error and warning messages for details. The
  root warning is:
Warning 9 Custom tool warning: Cannot import wsdl:portType Detail: An
  exception was thrown while running a WSDL import extension:
  System.ServiceModel.Description.DataContractSerializerMessageContractImporter
  Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection
  data contract which is not supported. Consider modifying the
  definition of collection 'Newtonsoft.Json.Linq.JToken' to remove
  references to itself. XPath to Error Source:
  //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:portType[@name='IXXX']
  C:\Projects...\Reference.svcmap 1 1 pqrt.web

If I removed the data contracts from the service contract, it worked. I also tried to add the service reference to other projects like a library project or even an ASP.NET MVC 3 project, it all worked. I was wondering if this was an issue with ASP.NET MVC 4? I was using VS 2012 RC.
One workaround I can think of is to add the service reference to a library project and then call the library project from ASP.NET MVC 4, but I hate to do that since it's an extra step. Any suggestions?

A: If you want to keep the reference to Newtonsoft.Json you could also leave Newtonsoft.Json out of the list of assemblies to check for reuse of datacontracts.
To do this: right click your service reference, then click Configure Service Reference...
Under "Reuse types in referenced assemblies" select the second option to specify in which assemblies to search for reused types and select all assemblies but uncheck Newtonsoft.Json

A: Try removing Newtonsoft.Json from your references and re-add your service reference.

A: I had this error at compile time when trying to return a JObject as the endpoint result.
I got around it by making the endpoint return object and having this kind of code:
[WebGet(UriTemplate = "SomeRequest?form_request={form_request}", ResponseFormat = WebMessageFormat.Json)]
public object SomeRequest(string form_request)
{
    dynamic result = new JObject();
    // some other code
    result.status = "success";
    return JsonConvert.SerializeObject(result);
}

The jQuery consuming the service via jsonp e.g. $.getJSON('<?>.svc/SomeRequest', 'form_request=' + webform_as_json, request_callback); then unpacks the serialized object like so:
function request_callback(response) {
    var json = $.parseJSON(response);
    if (json.status == 'success') {

A: Do you really mean to return a node in an arbitrarily deep tree?
If so, then instead of returning a JToken, first convert it to a string to get the JSon text.  On the client end, you can Jtoken.Parse(yourstring) back into a JToken.
If not, then consider passing back the Value<T> and letting the serialization deal with T.


text:
Q: Cannot interfere with the TypeError I am consciously trying to make a mistake to use 'except' statement so that I can interfere with the expected error.
    a = 1
    for i in a:
        try:
            print(a*a)
        except TypeError:
            print("Hata")

I want to run an integer with a 'for' loop and interfere with the 'TypeError' but, somehow, I cannot trigger 'try' statement and "except" statement cannot be triggered, either. As I couldn't understand the reason, I need some help. Thank you in advance for your help.

A: 'int' object is not iterable. If you want to check custom TypeError then use for loop in try and then raise TypeError
a = 1
try:
    for i in a:
        print(a*a)
except TypeError:
    print("Hata")


text:
Q: Simple Linq to XML question Given the XML below..
and given that I have two variable 'Idnt' and 'Xref' which will store the # ID .. How do I get those values ?
I want
var Idnt = 5169452
and
var xref = 5169452

 <ecf:EntityPerson xmlns:ecf="xx">
  <nc:PersonName xmlns:nc="xx">
    <nc:PersonGivenName>JAMES</nc:PersonGivenName>
    <nc:PersonMiddleName>TIBERIUS</nc:PersonMiddleName>
    <nc:PersonSurName>KIRK</nc:PersonSurName>
  </nc:PersonName>
  <nc:PersonOtherIdentification xmlns:nc="xx">
    <nc:IdentificationID>5169452</nc:IdentificationID>
    <nc:IdentificationCategoryText>IDNT</nc:IdentificationCategoryText>
  </nc:PersonOtherIdentification>
  <nc:PersonOtherIdentification xmlns:nc="xx">
    <nc:IdentificationID>5169452</nc:IdentificationID>
    <nc:IdentificationCategoryText>XREF</nc:IdentificationCategoryText>
  </nc:PersonOtherIdentification>
</ecf:EntityPerson>

A: XNamespace ns = "xx";

var doc = XDocument.Load(xmlFilePath);
int idnt =
    int.Parse(
        doc.Descendants(ns + "PersonOtherIdentification")
        .Where(e => e.Element(ns + "IdentificationCategoryText").Value == "IDNT")
        .Single().Element(ns + "IdentificationID").Value);

Console.WriteLine(idnt);


text:
Q: Is the current same everywhere in a series circuit? When we say that the current flowing in a series circuit is the same, do we mean that the current is same in the entire circuit i.e, charge per unit time is the same in the entire circuit at any point of time, or do we mean that at each point in the circuit, the charge per unit time is the same?
While explaining, please bear in mind that I'm a student of the tenth grade, who has just been introduced to charge, emf,etc.. I would really appreciate if there are easy explanations with no complex equations and diagrams.

A:
charge per unit time is the same in the entire circuit at any point of time, or do we mean that at each point in the circuit, the charge per unit time is the same?

If the circuit has only one loop, then at any point in time, the current is the same at all points in that loop.

A:
charge per unit time is the same in the entire circuit at any point of time

at each point in the circuit, the charge per unit time is the same

Both of these statements are true. The current is the same at all points, thus it is the same throughout the entire circuit.
This is a consequence of Kirchhoff's current law: all entering current must equal all leaving current at every point (meaning, if two Coulomb of charge enter every second, then also two Coulomb of charge must leave every second). Otherwise there would be either a charge build-up or a charge deficit somewhere.
When the circuit has reached steady state then this law can be assumed to hold, and then the current is constant throughout a series connection.


text:
Q: How to use two CollectionView in one ViewController? I am working on an existing project which has a collectionView, right now i want to add another collectionView in this same viewcontroller. Already tried different solutions but can not seem to have any luck. Here is the existing code for collectionview:
func numberOfSections(in collectionView: UICollectionView) -> Int {

    if homeList.last?.catList.isEmpty ?? false{
        return homeList.count - 1
    }
    return self.homeList.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if section == homeList.count - 1{
        return 2
    }
    return homeList[section].catList.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if indexPath.section == homeList.count - 1{
        let doctorsCell = collectionView.dequeueReusableCell(withReuseIdentifier: "doctorCell", for: indexPath) as! DoctorsCVC
        doctorsCell.docDelegate = self
        doctorsCell.docList = homeList[indexPath.section].catList as? [Doctor] ?? []
        delayOnMain(0.1){
            doctorsCell.docCollectionView.reloadData()
        }
        return doctorsCell
    }
    else{
        let productsCell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductCVC
        productsCell.setData(homeList[indexPath.section].catList[indexPath.row])
        productsCell.fivePercentView.layer.cornerRadius = 5
        return productsCell
    }
}

And here is my new code for collectionView:
@IBOutlet var collectionView2: UICollectionView!

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return arrData.count
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
     cell.img.image = arrData[indexPath.row].image
     return cell
 }

Can someone help me to merge this code!

A: You can't use two  same collectionView delegate methods (eg -cellForItemAt ) methods in same view controller. So you have to check the collection view inside every collectionView delegate methods.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.collectionView2 {
        return arrData.count
    } else {
        if section == homeList.count - 1 {
            return 2
        }
        return homeList[section].catList.count
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == self.collectionView2 {

      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
      cell.img.image = arrData[indexPath.row].image
      return cell

    }else{
          if indexPath.section == homeList.count - 1{
                let doctorsCell = collectionView.dequeueReusableCell(withReuseIdentifier: "doctorCell", for: indexPath) as! DoctorsCVC
                doctorsCell.docDelegate = self
                doctorsCell.docList = homeList[indexPath.section].catList as? [Doctor] ?? []
                delayOnMain(0.1){
                    doctorsCell.docCollectionView.reloadData()
                }
                return doctorsCell
            }
            else{
                let productsCell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductCVC
                productsCell.setData(homeList[indexPath.section].catList[indexPath.row])
                productsCell.fivePercentView.layer.cornerRadius = 5
                return productsCell
            }
        }
  }

A: What I think is a clearer method is to use a second collectionViewController and a custom container view controller.
That way, the differentiation in the delegate methods is no longer needed.


text:
Q: Inline PHP clone When trying to do this in PHP 5.2.9:
$foo = (clone $template)->bar();

PHP gives me a syntax error:
Parser error "';' expected after expression (Found token: ->)"

Am I doing something wrong? or is there simply no way to clone an object inline, such that I would have to split my statement into two lines?

A: class X {
    public function foo(){
        echo 'inline clone';
    }
}

$x = new X;

$y = clone $x and $y->foo(); // "inline clone"

A: Unfortunately, PHP does not allow that syntax (in any version).  As an alternative to breaking it into two lines, you can do this:
$foo = call_user_func(array(clone $template, 'bar'));

A: This would be available only from PHP 5.4.0
Reading changelog:

Added class member access on instantiation (e.g. (new foo)->bar())
  support.

A: As a workaround you could create a function to clone a variable:
$clone = function ($value) {
    return clone $value;
};

$foo = $clone($template);