text: Q: Unable to resolve dependency 'Microsoft.AspNet.SignalR.SystemWeb'. Source(s) used: 'nuget.org', 'Microsoft and .NET' Not much I can say about this, just installed VS 2015 Community, trying to install SignalR and this error pops out.


text:
Q: Do closed migrated questions always redirect now? I've noticed today that migrated questions now redirect immediately to the target site. Previously, I had enough rep that the original question was still visible on the original site without an automatic redirect. Has this changed?

A: This is by design -- we feel a migrated question should take you directly to the destination, since otherwise it's just another click to get to the actual question and any answers.

A: There's a link on the destination site that sends you back to the closed version of question on the original site. It passes ?noredirect=1 querystring to force not to redirect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern for a base class to do pre-validation and/or post-processing on a deriving class's overridden method? I have the following pattern repeating itself in multiple places:
abstract class Database {
  void connect() {
    this.setStatus( CONNECTING )
    try {
      await this.realConnect()
    }
    catch (error) {
      this.setStatus( ERROR )
      throw error
    }
    this.setStatus( CONNECTED )
  }

  abstract void realConnect()
}

class Sqlite3Database extends Database {
  override void realConnect() {
    await someSqlite3Library.connect(...)
  }
}

It works well, and allows the subclasses to not worry about common functionality like validating input, updating the status, or emiting events. But it leaves me with two methods for everything; method() and realMethod(). It doesn't look as bad here when I have only one connect method, but when in reality I also have disconnect, reconnect, write, read, and more, it gets very weird to write two methods for everything.
Is this a common pattern? Is there a name for it? Is there a better way to accomplish this behaviour?

A: It's a variation of the template method pattern.
AbstractClass {
    void method() {
         methodImpl();
    }

    abstract void methodImpl();
}

ConcreteClass extends AbstractClass {
    void methodImpl() {
        // do stuff
    }
}

This pattern can also be used if the main work is done by the superclass, and the specialized class only needs to implement some hook method (e.g. onConnected).
Note that it sounds like you could also try different patterns. Maybe you should instead use a decorator that calls the wrapped concrete database (you could also have multiple levels of different behavior, which is much more easily composed than via inheritance).
For decorator:
interface Database { void connect(); }

ConnectionDatabase implements Database {
    // pass in SpecializedDatabase
    ConnectionDatabase(Database actualDB) {...}
    void connect() {
        this.setStatus( CONNECTING )
        try {
            await this.actualDB.connect()
        }
        this.setStatus( CONNECTED )
    }
}

SpecializedDatabase implements Database {
    void connect() {
        // do stuff
    }
}

You could also have a look at aspect oriented programming to e.g. wrap some cross-cutting processing.
Edit: One more suggestion is the chain of responsibility. It could have different aspects of managing the connection chained one after the other (more suited towards sequentially executing the different aspects, not really wrapping around the follower). It is not really suited for what you have, but may give you something to consider for certain parts of your system.

A:
Is there a better way to accomplish this behaviour?

They say favor composition over inheritance. A pattern that might give you more flexibility and still do everything you're doing here is the Decorator Pattern. You'd build it like this:
Database db = new Sqlite3Database(
    new dbValidator(
        new dbEventEmiter(
            new Database()
        )
    )
);

Done this way you're free to add, remove, rewrite, or suppress any behavior in any of these layers. You're also on the hook to do a lot of keyboard typing because you still need to write code to delegate. But you have the power to fiddle both as a call comes in and as it goes out.
Over engineered? Most likely. But in addition to being able to add a new layers later you're also free to squish layers together later if you change your mind. So it's only as over engineered as you want it to be. Separate what changes from what stays the same.
The trick here is each of these implements the same interface that it accepts in it's constructor. Nothing that talks to this cares which layer it's talking to. Any layer could be the outer layer. Changing their order changes the order the behaviors happen in.
The point is you can swap behaviors easily. Need event emitting to behave more like messages? Write up a dbMessageEmiter and swap it in.


text:
Q: spring boot vaadin 14 build for production failes I am stuck, I can't compile my spring boot vaadin project for production use.
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.3.RELEASE</version>
      <relativePath/>
      <!-- lookup parent from repository -->
   </parent>
   <groupId>de.kreth.clubhelper</groupId>
   <artifactId>clubhelper-attendance</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>clubhelper-attendance</name>
   <description>UI App for Clubhelper Attendance</description>
   <properties>
      <java.version>11</java.version>
      <org.keycloak.version>11.0.1</org.keycloak.version>
      <vaadin.version>14.3.4</vaadin.version>
      <flow.maven.plugin.version>4.0.4</flow.maven.plugin.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>com.vaadin</groupId>
         <artifactId>vaadin-spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.keycloak</groupId>
         <artifactId>keycloak-spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.keycloak</groupId>
         <artifactId>keycloak-spring-security-adapter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
      <dependency>
         <groupId>io.projectreactor</groupId>
         <artifactId>reactor-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjrt</artifactId>
      </dependency>
      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
      </dependency>
   </dependencies>
   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-bom</artifactId>
            <version>${vaadin.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
         <dependency>
            <groupId>org.keycloak.bom</groupId>
            <artifactId>keycloak-adapter-bom</artifactId>
            <version>${org.keycloak.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <plugin>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-maven-plugin</artifactId>
            <executions>
               <execution>
                  <goals>
                     <goal>prepare-frontend</goal>
                     <goal>build-frontend</goal>
                  </goals>
                  <phase>compile</phase>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-clean-plugin</artifactId>
            <configuration>
               <filesets>
                  <fileset>
                     <directory>node_modules</directory>
                     <includes>
                        <include>**</include>
                     </includes>
                     <followSymlinks>false</followSymlinks>
                  </fileset>
                  <fileset>
                     <directory>.</directory>
                     <includes>
                        <include>*.json</include>
                        <include>*.js</include>
                        <include>pnpm-lock.yaml</include>
                        <include>types.d.ts</include>
                     </includes>
                     <followSymlinks>false</followSymlinks>
                  </fileset>
               </filesets>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <profiles>
      <profile>
         <id>productionMode</id>
         <activation>
            <property>
               <name>vaadin.productionMode</name>
            </property>
         </activation>
         <dependencies>
            <dependency>
               <groupId>com.vaadin</groupId>
               <artifactId>flow-server-production-mode</artifactId>
            </dependency>
         </dependencies>
         <build>
            <plugins>
               <plugin>
                  <groupId>com.vaadin</groupId>
                  <artifactId>flow-maven-plugin</artifactId>
                  <version>${flow.maven.plugin.version}</version>
                  <executions>
                     <execution>
                        <goals>
                           <goal>copy-production-files</goal>
                           <goal>package-for-production</goal>
                        </goals>
                        <configuration>
                           <transpileOutputDirectory>${webapp.directory}</transpileOutputDirectory>
                        </configuration>
                     </execution>
                  </executions>
               </plugin>
               <plugin>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-maven-plugin</artifactId>
                  <configuration>
                     <jvmArguments>-Dvaadin.productionMode</jvmArguments>
                  </configuration>
               </plugin>
            </plugins>
         </build>
      </profile>
   </profiles>
</project>

This is the maven command I am using:
mvn -Pvaadin.productionMode clean vaadin:prepare-frontend vaadin:build-frontend package
This is the output:
:~/app$ mvn -Pvaadin.productionMode clean vaadin:prepare-frontend vaadin:build-frontend package
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.inject.internal.cglib.core.$ReflectUtils$1 (file:/usr/share/maven/lib/guice.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for my.app   :app   :jar:0.0.1-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for com.vaadin:vaadin-maven-plugin is missing. @ line 106, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] -------------< my.app   :app    >--------------
[INFO] Building app    0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ app    ---
[INFO] Deleting /home/markus/docker-compose-executions/app   /app   /target
[INFO] Deleting /home/markus/docker-compose-executions/app   /app   /node_modules (includes = [**], excludes = [])
[INFO] Deleting /home/markus/docker-compose-executions/app   /app    (includes = [*.json, *.js, pnpm-lock.yaml, types.d.ts], excludes = [])
[INFO]
[INFO] --- vaadin-maven-plugin:17.0.7:prepare-frontend (default-cli) @ app    ---
[INFO] Added 19 default dependencies to main package.json
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /package.json.
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /target/flow-frontend/package.json.
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /target/flow-frontend/form/package.json.
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /target/index.html'
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /target/index.ts'
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /tsconfig.json'
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /types.d.ts'
[INFO] Copying frontend resources from jar files ...
[INFO] Visited 162 resources. Took 268 ms.
[INFO] Created webpack configuration file: '/home/markus/docker-compose-executions/app   /app   /webpack.config.js'
[INFO]
[INFO] --- vaadin-maven-plugin:17.0.7:build-frontend (default-cli) @ app    ---
[INFO] Scanning classes to find frontend configurations and dependencies...
[INFO] Visited 647 classes. Took 1279 ms.
[INFO] Visited 86 classes. Took 47 ms.
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /target/flow-frontend/package.json.
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /target/flow-frontend/form/package.json.
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /target/index.html'
[INFO] writing file '/home/markus/docker-compose-executions/app   /app   /target/index.ts'
[INFO] Parsing java files from [/home/markus/docker-compose-executions/app   /app   /src/main/java]
[INFO] There are no connect endpoints to generate.
[INFO] Added 33 dependencies to main package.json
[INFO] writing file /home/markus/docker-compose-executions/app   /app   /package.json.
[INFO] Running `pnpm install` to resolve and optionally download frontend dependencies. This may take a moment, please stand by...
[WARNING] Couldn't find  dev dependencies file. Dev dependencies won't be locked
[INFO] Generated pnpmfile hook file: '/home/markus/docker-compose-executions/app   /app   /pnpmfile.js'
[INFO] installing pnpm version 4.4.0 locally
[INFO] using '/usr/bin/node /home/markus/.vaadin/node_modules/pnpm/bin/pnpm.js' for frontend package installation
[INFO] Frontend dependencies resolved successfully.
[INFO] Copying frontend resources from jar files ...
[INFO] Visited 162 resources. Took 66 ms.
[INFO] Updated /home/markus/docker-compose-executions/app   /app   /target/frontend/generated-flow-imports-fallback.js
[INFO] Updated /home/markus/docker-compose-executions/app   /app   /target/frontend/generated-flow-imports.js
[INFO] Updated /home/markus/docker-compose-executions/app   /app   /target/frontend/generated-flow-imports.d.ts
[INFO] Running webpack ...
: Using typescript@3.8.3 from typescript
: Using tsconfig.json from /home/markus/docker-compose-executions/app   /app   /tsconfig.json
: Checking started in a separate process...
: Checking finished with 1 errors
Hash: c1391e3e8704817266b9
Version: webpack 4.42.0
Time: 15519ms
Built at: 2020-10-25 22:59:27
 5 assets
Entrypoint bundle =
Entrypoint export = build/vaadin-export-040d8e0d55fe4b3daad3.cache.js
 [23] ../node_modules/.pnpm/registry.npmjs.org/@polymer/polymer/3.2.0/node_modules/@polymer/polymer/lib/elements/custom-style.js + 1 modules 6.24 KiB {1} {3} [built]
      |    2 modules
 [43] ../node_modules/.pnpm/registry.npmjs.org/@polymer/iron-icon/3.0.1/node_modules/@polymer/iron-icon/iron-icon.js + 1 modules 16 KiB {1} {3} [built]
      |    2 modules
 [47] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-lumo-styles/1.6.0/node_modules/@vaadin/vaadin-lumo-styles/icons.js + 1 modules 14.3 KiB {1} {3} [built]
      |    2 modules
 [48] ../target/frontend/generated-flow-imports.js 1.35 KiB {1} {5} [built]
 [49] ../target/index.ts + 1 modules 92.2 KiB {0} [built]
      | ../target/index.ts 1.43 KiB [built]
      |     + 1 hidden module
 [50] ../target/frontend/generated-flow-imports-fallback.js + 8 modules 15.3 KiB {4} [built]
      | ../target/frontend/generated-flow-imports-fallback.js 3.95 KiB [built]
      | ../target/flow-frontend/comboBoxConnector-es6.js 417 bytes [built]
      | ../target/flow-frontend/contextMenuConnector-es6.js 319 bytes [built]
      | ../target/flow-frontend/dndConnector-es6.js 29 bytes [built]
      | ../target/flow-frontend/flow-component-renderer.js 5.23 KiB [built]
      | ../target/flow-frontend/gridConnector-es6.js 590 bytes [built]
      | ../target/flow-frontend/ironListConnector-es6.js 255 bytes [built]
      | ../target/flow-frontend/ironListStyles.js 320 bytes [built]
      | ../target/flow-frontend/vaadin-grid-flow-selection-column.js 3.88 KiB [built]
 [56] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-text-field/2.6.2/node_modules/@vaadin/vaadin-text-field/theme/lumo/vaadin-text-field.js + 1 modules 11.1 KiB {2} [built]
      |    2 modules
 [71] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-item/2.2.0/node_modules/@vaadin/vaadin-item/theme/lumo/vaadin-item.js + 1 modules 2.23 KiB {2} [built]
      |    2 modules
 [76] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-list-box/1.3.0/node_modules/@vaadin/vaadin-list-box/theme/lumo/vaadin-list-box.js + 1 modules 2.85 KiB {2} [built]
      |    2 modules
 [77] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-text-field/2.6.2/node_modules/@vaadin/vaadin-text-field/theme/lumo/vaadin-password-field.js + 1 modules 1.06 KiB {2} [built]
      |    2 modules
[111] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-date-picker/4.2.0/node_modules/@vaadin/vaadin-date-picker/theme/lumo/vaadin-date-picker.js + 6 modules 13.9 KiB {2} [built]
      |    7 modules
[114] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-time-picker/2.2.0/node_modules/@vaadin/vaadin-time-picker/theme/lumo/vaadin-time-picker.js + 3 modules 1.73 KiB {2} [built]
      |    4 modules
[115] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-login/1.1.0/node_modules/@vaadin/vaadin-login/theme/lumo/vaadin-login-form.js + 2 modules 883 bytes {2} [built]
      |    3 modules
[117] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-context-menu/4.4.0/node_modules/@vaadin/vaadin-context-menu/theme/lumo/vaadin-context-menu.js + 1 modules 4.92 KiB {2} [built]
      |    2 modules
[118] ../node_modules/.pnpm/registry.npmjs.org/@vaadin/vaadin-custom-field/1.1.0/node_modules/@vaadin/vaadin-custom-field/theme/lumo/vaadin-custom-field.js + 1 modules 2.87 KiB {2} [built]
      |    2 modules
    + 152 hidden modules

ERROR in ../target/index.ts
Module not found: Error: Can't resolve '@vaadin/flow-frontend/Flow' in '/home/markus/docker-compose-executions/app   /app   /target'
 @ ../target/index.ts 15:0-50 16:33-37

ERROR in chunk bundle [entry]
build/vaadin-bundle-abadb23bac92212c113c.cache.js
/home/markus/docker-compose-executions/app   /app   /node_modules/.pnpm/registry.npmjs.org/awesome-typescript-loader/5.2.1_typescript@3.8.3/node_modules/awesome-typescript-loader/dist/entry.js!/home/markus/docker-compose-executions/app   /app   /target/index.ts f94cc97538a37d57399caa03b213501e
Unexpected token (17:33)
| // import Flow module to enable navigation to Vaadin server-side views
|
| const { serverSideRoutes } = new !(function webpackMissingModule() { var e = new Error("Cannot find module '@vaadin/flow-frontend/Flow'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())({
|     imports: () => Promise.all(/* import() */[__webpack_require__.e(3), __webpack_require__.e(5)]).then(__webpack_require__.bind(null, 48))
| });

ERROR in [at-loader] ./target/index.ts:18:20
    TS2307: Cannot find module '@vaadin/flow-frontend/Flow'.
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [0] ../node_modules/.pnpm/registry.npmjs.org/html-webpack-plugin/3.2.0_webpack@4.42.0/node_modules/html-webpack-plugin/lib/loader.js!../target/index.html 1.13 KiB {0} [built]
        + 3 hidden modules
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  51.978 s
[INFO] Finished at: 2020-10-25T22:59:27+01:00
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "vaadin.productionMode" could not be activated because it does not exist.
[ERROR] Failed to execute goal com.vaadin:vaadin-maven-plugin:17.0.7:build-frontend (default-cli) on project app   : Webpack process exited with non-zero exit code.
[ERROR] Stderr: ''
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I have no more ideas, what is wrong here.
I tried the instructions here:
https://vaadin.com/docs/flow/production/tutorial-production-mode-basic.html
but the 'executions' tag made maven fail.
The snipplet is from here:
https://github.com/vaadin/flow-spring-examples/blob/master/pom.xml
The original (even not working) pom.xml was generated from https://start.spring.io/
I think my pom.xml is missing something, but I don't know what.
Has someone a working pom.xml with spring boot and vaadin?
After rereading and experiments with removing and adding plugins, I think the error is this line:
'''
Error: Can't resolve '@vaadin/flow-frontend/Flow'
'''
Why is this not compiled and how to compile it?


text:
Q: Posterior Probability Density for a set of random variables I've been reading Watanabe's book on Bayesian Statistics, and had trouble with the posterior probability density formula for a set of random variable pairs.
For a set of random variables $X^n=(X_1,X_2,...,X_n)$ subject to $q(x_1)q(x_2)...q(x_n)$ i.e. independent random variables (each of which are $\Bbb R^N$), the posterior of the model parameter $w \in W \subseteq \Bbb R^d$ is a straightforward application of the Bayes rule (where the prior represents $\varphi(w)$):
$$
p\left(w \mid X^n\right)=\frac{1}{Z\left(X^n\right)} \varphi(w) \prod_{i=1}^n p\left(X_i \mid w\right)
$$
$$
Z\left(X^n\right)=\int \varphi(w) \prod_{i=1}^n p\left(X_i \mid w\right) d w
$$
However, Watanabe at (1.9) then claims, for $(X^n,Y^n) = ((X_1,Y_1),(X_2,Y_2),...,(X_n,Y_n))$ subject to $q(x_1,y_1)q(x_2,y_2)...q(x_n,y_n)$ i.e. independent random variable pairs (each sample on $\Bbb R^m \times \Bbb R^n$), the following is true:
$$
p\left(w \mid X^n, Y^n\right)=\frac{1}{Z\left(X^n, Y^n\right)} \varphi(w) \prod_{i=1}^n p\left(Y_i \mid X_i, w\right)
$$
$$
Z\left(X^n, Y^n\right)=\int \varphi(w) \prod_{i=1}^n p\left(Y_i \mid X_i, w\right) d w
$$
But this doesn't make sense; it seems to ignores $P(X_i \mid w)$ for the factorization of $P(X_i, Y_i)$ within $\prod$, nor do they seem to cancel out (since one's within the integral at the denominator). Am I missing something?

A: I don't think that you are missing anything.
In fact, you are totally right in pointing this out!
There seem to be some assumptions hidden in the notation, in particular, in the formulation "for an arbitrary pair $(p(y|x,w),\varphi(w))$".
I suppose that it might be implied that $X^{n}$ and $w$ are independent (and also that $X_{i}$ and $Y_{i}$ are conditionally independent given $w$), but, in my humble opinion, it is a somewhat counterintuitive introduction to posterior distributions.


text:
Q: CTreeCtrl Checkbox Child item state I have a CTreeCtrl with Checkbox. How can I make it work like standard app:
+ When I select a root item, all its child iems will be selected,
+ When I select a child item, its root item will be marked with a rectangle in the checkbox, and if all other childs of that root were already selected, it will be a check mark instead of the rectangle at the root item.

A: It's not 'standard', you have to do all that manually.

A: After several searches I found this on CodeProject. Hope anyone who meet the same issue  can find it could be in help
http://www.codeproject.com/Articles/140828/A-Multi-selectable-Tree-Control-Supports-Transpare


text:
Q: Java DATE Parsing I´m having a stupid problem with java.util.Date.
I have this line of code, but I don´t understand why this date is unparseable with this format.
public class TestTime {
    public static void main(String[] args) {
        final String DATE_FORMAT = "EEE MMM dd HH:mm:ss zzz yyyy";

        String date = "Sat Dec 31 10:00:00 CET 2011";
        SimpleDateFormat dFormat = new SimpleDateFormat(DATE_FORMAT);

        Date lDate = null;
        try {
            lDate = dFormat.parse(date);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

A: I don't see anything wrong with this.  It executes for me without error, and returns:
Sat Dec 31 09:00:00 GMT 2011

A: If your system uses a locale other than English you need to use this constructor:
SimpleDateFormat(DATE_FORMAT,Locale.ENGLISH);

If this is not the problem, you should format a date using the same formatter and compare the output to your input string.

A: Seems to be a Locale-related problem.
If I set a French locale, the pattern does not work. If I set the Locale to be US in the SimpleDateFormat constructor, it does works.
SimpleDateFormat dFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);


text:
Q: What's the technique of using phrases of different meanings separated by a conjunction called? I've been wondering this for a while. Here's some examples:
taking lives and orders, made cookies but no conversation. I googled phrases of different types in one clause, but this didn't yield any useful results. This doesn't seem like parallelism, since the phrases have different meanings in context of the sentence. Anyone have any ideas?

A: Zeugma is one of stylistic syntactic figures. It is defined as 'the use of a single word in relation to two other parts of a sentence althoughgrammatically or logically the word applies to only one of them' /Macmillan Dictionary/. For example, the joke 'The cinema-makers should shoot fewer films and more actors' is another example of zeugma.


text:
Q: How can I make Bootstrap components align right? I have a responsive table and a button, now I want to make them align right so I do this:

    <button type="button" class="btn btn-primary btn-sm pull-right">upload</button>

I add pull-right to the button and the page looks like this:

How can I make the button and table align right properly?

A: As you can see from the example pull-right class should be working. You might have some problem with padding-right on the parent div of the table, or maybe some col-sm-11 class?

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

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <button type="button" class="btn btn-primary btn-sm pull-right">upload</button>

               1	2	3

               1	2	3

               1	2	3

               1	2	3

               1	2	3

A: use col-sm-offset.

    <button type="button" class="btn btn-primary btn-sm pull-right">upload</button>

A: By default,td items aligned to left so override it.
#main table tr td:last-child{
        text-align: right !important;
    }


text:
Q: SQL - Capitalize first letter of each word I know that this thread exists all over the place, however, this is a slightly different case.
In the suite my company uses, I have limited access to the SQL and cannot run the complicated codes with functions, etc. I had a SQL query that compiled data over multiple columns into one column and used a group by clause to weed out multiplicities. However, this caused all the results to be returned in all caps, since variations existed. I must now change it back to how it should be, i.e. first letter of each word capitalized. I need a very concise way of doing this. The suite uses VBScript and XML, but this particular issue is more complicated because I cannot edit the results on the client-side, the suite simply asks for the column name to be displayed (populate a drop-down menu). Any suggestions? Thanks!
Query:
Select Insurance
From
(Select Ins1 as Insurance
From InsAuth2
WHERE Ins1 IS NOT NULL
Union All
Select Ins2 as Insurance
From InsAuth2
WHERE Ins2 IS NOT NULL
Union All
Select Ins3 as Insurance
From InsAuth2
WHERE Ins3 IS NOT NULL
Union All
Select Ins4 as Insurance
From InsAuth2
WHERE Ins4 IS NOT NULL
Union All
Select Ins5 as Insurance
From InsAuth2
WHERE Ins5 IS NOT NULL) as table
Group By Insurance

A: This will uppercase the first letter of the string. If there are multiple words, this is better done in the application layer. You would likely need to write a SQL function to do this.
select upper(substring(MyColumn, 1, 1)) + substring(MyColumn, 2)
from MyTable

or
select upper(substring(MyColumn, 1, 1)) || substring(MyColumn, 2)
from MyTable

A: You did not say that this was for SQL Server but here is a solution in case it is.
Here is a working sample. Replace the table variable @T with the query you have.
declare @T table(Insurance varchar(max))

insert into @T values
('BENGT MIKAEL ERIKSSON'),
('XMLCHARTEST<>&''"')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+' '
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from
  (
  select cast('<N>'+replace(
                    replace(
                    replace(Insurance,
                    '&', '&'),
                    '<', '<'),
                    ' ','</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

Result:
Insurance
----------------------
Bengt Mikael Eriksson
Xmlchartest<>&'"


text:
Q: How to make that a page not detect that I am using the automatize control in puppeteer I'm working on a bot that buys by himself, but the page knows I'm using a bot maybe because the message  "Chrome is being controlled by automated test software", so I want to know if there is a way in pupeteer to launch a "regular version" of a browser simulating that is a human person so in that way not being tracked as a bot by the page.
I tried with
const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
        executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
  });

but is the same using Chrome and chronium


text:
Q: Python не видит библиотеку в venv Установил PyCharm. Создал проект с виртуальным окружением (venv). Через pip установил colorama. Но почему-то питон не видит эту библиотеку в venv'е. Как это можно поправить?
main.py:
from colorama import Fore, Back, Style

print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')


text:
Q: Query That Pulls Duplicate Parts On The Same Order In my system, there should not be the same part# listed on an order more than once. I'm trying to write a query that will pull up any parts that appear on an order more than once. For example:
Order# Part QTY
1      A    1
1      A    1
1      B    5
2      A    4
2      B    4
2      C    3
3      A    5
3      B    5
3      B    7
4      A    3
4      B    6
5      A    3

So the problems here would be Order # 1 because part A appears more than once, and the same thing with Order# 3 because part B appears more than once. The rest of the orders would be fine. Where would I start if I want to achieve something like this.

A: The following query literally follows what you are asking.  It aggregates by the combination of order and part, and returns those values when they occur more than once for a given pair.
SELECT Order, Part
FROM yourTable
GROUP BY Order, Part
HAVING COUNT(*) > 1


text:
Q: Newtonsoft is not serializing navigation property I have an EF object RetailDocuments. It is related to the DocumentTemplateMaster object via foreign key. Many RetailDocuments can have the same DocumentTemplateMaster.
I'm retrieving a List<RetailDocument> and have turned off proxy creation and lazy loading. The referenced DocumentTemplateMaster object is there in the List but not when it is serialized.
I've tried a number of solutions I've seen here on SO and other places but for whatever reason, it's not working for me.
Here's my code, commented code shows stuff I've tried but didn't seem to make a difference:
using (RetailDocumentEntities db = new RetailDocumentEntities()) {
    db.Configuration.ProxyCreationEnabled = false;
    db.Configuration.LazyLoadingEnabled = false;
    List<RetailDocument> retailDocuments =
    retailDocuments = db.RetailDocument.Include("DocumentTemplateMaster").where(x=>x.col2 = "someVal").ToList();

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };
string retVal = JsonConvert.SerializeObject(retailDocuments, Formatting.Indented, serializerSettings);

    //JsonSerializerSettings settings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Serialize};// PreserveReferencesHandling = PreserveReferencesHandling.Objects};// ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ReferenceLoopHandling = ReferenceLoopHandling.Serialize };
    //string retVal = Newtonsoft.Json.JsonConvert.SerializeObject(retailDocuments, settings);
    return retVal;
}

Before I serialize it, DocumentTemplateMaster shows up as a navigation property in the List as it should but when serialized, it is missing. I'm sure it's a silly little thing I'm missing but what is it?
Edit: the context is defined and the include is there. The referenced DocumentTemplateMaster is there in the retrieved list. This is not the problem. The problem is in the serialization as it is not in the serialized string

A: You need to include your navigation property if you have lazy loading turned off
retailDocuments = db.RetailDocument.Include(x => x.DocumentTemplateMaster).where(x=>x.col2 = "someVal").ToList();

However note that Include has some notable performance impact. Often it is better to retrieve the values in 2 separate calls and add the relation in memory.

A: After a lot more research, it would appear that navigation properties also need to have the [DataMember] attribute.
Once I added that, the problem went away.
Sometimes it's the simple things.


text:
Q: Monitoring a particular sidekiq queue in a rails application As per the documentation for sidekiq monitoring at https://github.com/mperham/sidekiq/wiki/Monitoring if we need to monitor the queue backlog we add the following to config/routes.rb
require 'sidekiq/api'
match "queue-status" => proc { [200, {"Content-Type" => "text/plain"}, [Sidekiq::Queue.new.size < 100 ? "OK" : "UHOH" ]] }, via: :get

To monitor the latency
match "queue-latency" => proc { [200, {"Content-Type" => "text/plain"}, [Sidekiq::Queue.new.latency < 30 ? "OK" : "UHOH" ]] }, via: :get
Q1. I have multiple queues in my application called order_submission, mailers, critical and default.
If i want to monitor the backlog or latency for a particular queue say 'order_submission' how can i do that ?
Q2. The documentation also says that We have a Pingdom check every minute which fires off an email if the response == 'UHOH' for the following
match "queue-status" => proc { [200, {"Content-Type" => "text/plain"}, [Sidekiq::Queue.new.size < 100 ? "OK" : "UHOH" ]] }, via: :get

I know the Pingdom service is used to hit urls for testing performance and availability but its not clear to me what it means that there is already a pingdom check that runs every minute and sends the email . Would like to have clarification on this.
Thanks

A: A1 You may pass queue name:
Sidekiq::Queue.new('my_queue').size

A2 I didn't work with Pingdom, so I can just advise to:

*

*Check their docs, whether they can parse response or not.

*Change responce status when queque status is not OK, choose one from the list.

A: If you want to monitor individual queue in sidekiq, you can do so with the help of sidekiq_queue_metrics gem. It provides below features:

*

*View stats of all the queues

*View summary of an individual queue

*View failures of an individual queue along with backtrace.

Also the number of failures per queue is configurable.
Here is how you use this gem.
require 'sidekiq_queue_metrics'

Sidekiq.configure_server do |config|
  Sidekiq::QueueMetrics.init(config)
end

Also I have written a blog on this rubygem. Head over there for more details.


text:
Q: Getting a countable set from an uncountable set I am a bit confused with the proof of the following proposition (taken from Royden's Real Analysis - 3rd edition page 26).
$\textbf{Proposition}:$ There is an uncountable set $X$ which is well ordered by a relation $<$ in such a way that:
1) There is a last element $\Omega \in X$
2) If $x\in X$ and $x \neq\Omega$, then the set $\{y\in X:y<x\}$ is countable.
Proof: Let $Y$ be any uncountable set, say the one given by Problem 23. By the well ordering principle, there is a well ordering $<$ for $Y.$ If $Y$ does not have a last element, take an element $\alpha \notin Y,$ replace $Y$ by $Y\cup\{\alpha\},$ and extend the order $<$ by setting $y<\alpha$ for all $y\in Y$. This new $Y$ has a last element and is well ordered by $<.$ The set of $y$ in $Y$ for which the set $\{x \in Y : x<y\}$ is uncountable is a nonempty set, since it contains the last element of $Y.$ Let $\Omega$ be the smallest element in this set, and let $X=\{x \in Y : x< \Omega \textrm{ or } x= \Omega\}.$ Then $X$ is the required set.
My confusion is in the last two sentences. How does $X=\{x \in Y : x< \Omega \textrm{ or } x= \Omega\}$ make the set $\{y\in X:y<x\}$ countable?


text:
Q: PHP JQuery - Load multiple DIV's with 1 request My site currently has to load 6 different PHP pages to fill info for 7 DIV's.
Some refresh every 5 seconds, some every second.
I would rather load the one single PHP page every second, and split the details to all of the DIV's. That way only 1 request is sent per second, rather than 3 or 4 requests.
so --> api/getdata.php will echo: "$5.93, $10.36, 27:31 1, 22, Joe". Then JQuery will need to split each comma to a different DIV. Something like this:
setInterval(function() {$('#balance, #pot, #timer, #round, #id, #username').load('api/getdata.php');}, 1000);

I had a look on Google, but couldn't find anything to what I am looking for.
My current method (very bad) is:
<script type="text/javascript">
        $(document).ready(function() {
            $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
            $('#GetBalance, #GetBalanceWithdraw').load('get/GetBalance.php');
            $('#Clock').load('get/Clock.php');
            $('#GetPot').load('get/GetPot.php');

            setTimeout(function() {$('#errmsg').fadeOut('slow');}, 5000);
            setInterval(function() {
            $('#GetPot').load('get/GetPot.php');
            $('#TotalBids').load('get/TotalBids.php');
            }, 2500);
            setInterval(function() {$('#GetBalance, #GetBalanceWithdraw').load('get/Balance.php');}, 5000);
            setInterval(function() {$('#GetBalance').load('get/Balance.php');}, 5000);
            setInterval(function() {$('#Clock').load('get/Clock.php');}, 1000);
        });
    </script>

A: So you will need to split your response and only then assign to elements. At this moment you add same value to all elements.
You need something like this:
setInterval(function() {
    $.get( 'api/getdata.php', function( data ) {
        var result = data.split( ', ' );
        $( '#balance' ).text( result[ 0 ] );
        $( '#pot' ).text( result[ 1 ] );
        $( '#timer' ).text( result[ 2 ] );
        $( '#round' ).text( result[ 3 ] );
        $( '#id' ).text( result[ 4 ] );
        $( '#username' ).text( result[ 5 ] );
    } );
}, 1000);

But in this case you can flood you server with requests if back-end will slow with response, so better to call new AJAX after 1 second after previous loaded using recursive function:
function updateData() {
    $.get( 'api/getdata.php', function( data ) {
        var result = data.split( ', ' );
        $( '#balance' ).text( result[ 0 ] );
        $( '#pot' ).text( result[ 1 ] );
        $( '#timer' ).text( result[ 2 ] );
        $( '#round' ).text( result[ 3 ] );
        $( '#id' ).text( result[ 4 ] );
        $( '#username' ).text( result[ 5 ] );
        setTimeout( updateData, 1000);
    } );
}
updateData();

A: If you have all your strings in one string and comma separated, you could do this:
$( "#result" ).load( "ajax/test.html", function(data) {
  spread_the_news(data);
});

and then
function spread_the_news(data)
{
  var res = data.split(",");
  update_div_0_with_data(res[0]);
  update_div_1_with_data(res[1]);
  ...
}


text:
Q: Getting Undefined property from Object created with d3.js I am trying to read in data from a csv file and console.log the data returned. I am getting undefined. Why is it that if I console.log the store object I can see a property of routes in the console? But trying to consoloe log the routes property shows undefined.
let store = {};

function loadData() {
    // Add the code to load the CSV file named "routes.csv" | 1 Line
    let promise = d3.csv("routes.csv");

    return promise.then(routes => {
        // Save the routes into our store variable;
        store.routes = routes;
        return store;
    })

}

loadData();
console.log(store.routes);

The first few lines of the csv file looks like the following:
ID,AirlineID,AirlineName,AirlineCountry,SourceAirportID,SourceAirportCode,SourceAirport,SourceCity,SourceCountry,SourceLatitude,SourceLongitude,DestAirportID,DestCode,DestAirport,DestCity,DestCountry,DestLatitude,DestLongitude
1,24,American Airlines,United States,4355,ABE,Lehigh Valley International Airport,Allentown,United States,40.65209961,-75.44080353,3876,CLT,Charlotte Douglas International Airport,Charlotte,United States,35.2140007,-80.94309998
2,24,American Airlines,United States,4355,ABE,Lehigh Valley International Airport,Allentown,United States,40.65209961,-75.44080353,3752,PHL,Philadelphia International Airport,Philadelphia,United States,39.87189865,-75.2410965
3,24,American Airlines,United States,3718,ABI,Abilene Regional Airport,Abilene,United States,32.41130066,-99.68190002,3670,DFW,Dallas Fort Worth International Airport,Dallas-Fort Worth,United States,32.896801,-97.03800201
4,24,American Airlines,United States,4019,ABQ,Albuquerque International Sunport Airport,Albuquerque,United States,35.04019928,-106.6090012,3670,DFW,Dallas Fort Worth International Airport,Dallas-Fort Worth,United States,32.896801,-97.03800201
5,24,American Airlines,United States,4019,ABQ,Albuquerque International Sunport Airport,Albuquerque,United States,35.04019928,-106.6090012,3484,LAX,Los Angeles International Airport,Los Angeles,United States,33.94250107,-118.4079971
6,24,American Airlines,United States,4019,ABQ,Albuquerque International Sunport Airport,Albuquerque,United States,35.04019928,-106.6090012,3830,ORD,Chicago O'Hare International Airport,Chicago,United States,41.97859955,-87.90480042
7,24,American Airlines,United States,4019,ABQ,Albuquerque International Sunport Airport,Albuquerque,United States,35.04019928,-106.6090012,3462,PHX,Phoenix Sky Harbor International Airport,Phoenix,United States,33.43429947,-112.012001
8,24,American Airlines,United States,532,ABZ,Aberdeen Dyce Airport,Aberdeen,United Kingdom,57.20190048,-2.197779894,507,LHR,London Heathrow Airport,London,United Kingdom,51.4706,-0.461941

A: Returning values inside the then block return a promise. So, you need to add a then block with your function call which is not needed here. I think that will just make it more complex.
You can simply log the data inside the function and write your code inside the then block only.
let store = {};

function loadData() {
    // Add the code to load the CSV file named "routes.csv" | 1 Line
    let promise = d3.csv("routes.csv");

promise.then(routes => {
    // Save the routes into our store variable;
    store.routes = routes;
    console.log(store.routes);
  })
}

loadData();

UPDATE
let store = {};

function loadData() {
    // Add the code to load the CSV file named "routes.csv" | 1 Line
    let promise = d3.csv("routes.csv");
    return promise;
}

loadData().then(routes => {
  // Save the routes into our store variable;
  store.routes = routes;
  console.log(store.routes);
})


text:
Q: Can this animation be done with javascript? So, I need to make a simulation of processor scheduling and I thought JavaScript could do the trick until I found out that it doesn't support sleep (or similar method). It has setTimeout but it is really too much to figure out and synchronize all the elements).
In my animation I want to have ready queue, then process go to CPU where it waits until finished, then it goes to waiting queue where it uses memory, and then it is put back to ready queue. The thing is I want process in CPU and process in waiting queue to do their thing in same time (to be "busy").
If i put all processes in same jQuery queue animation then it is not possible.
If I try to do it without jQuery queues then there is problem that one animation wont wait for previous to finish. And there is a problem where everything is calculated while loops are running so basically it set all the variable first and then runs the animation.
And this is just too much of a work (if possible) to do with setTimeout functions.
So basically i want to know can a similar animation like this be done in JavaScript (and some library if easier): this animation
Or if not could you tell me some language and api where it could be easily done (preferably some fast to learn language).
Many tnx.

A: Yes, I've been working on couple of flash-like website that are using only javascript. This animation is very simple and you can use javascript for that with no problem.
I recommend TweenMax plugin.


text:
Q: Directional derivative, why is this incorrect? A function $\vec{F}$ is dependent on the lenght (norm) of $\vec{r}$
${\vec{F}(\vec{r})=F_{x}(\vec{r})\hat{x}+F_{y}(\vec{r})\hat{y}+F_{z}(\vec{r})\hat{z}}
 $,
in which
$F_{x}=F\left(\vec{r}\right)\frac{r_{x}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}$,  $F_{y}=F\left(\vec{r}\right)\frac{r_{y}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}$,   ${F_{z}=F\left(\vec{r}\right)\frac{r_{z}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}}$
Now I want to calculate the following derivative:
$\frac{\partial}{\partial r_x}\left(\vec{r}\cdot\vec{F}(\vec{r})\right)=\frac{\partial}{\partial r_x}\left(r_xF_x+r_yF_y+r_zF_z\right)=F_{x}+r_{x}\frac{\partial F_{x}}{\partial r_{x}}+r_{y}\frac{\partial F_{y}}{\partial r_{x}}+r_{z}\frac{\partial F_{z}}{\partial r_{x}}
$
where $\frac{\partial F_{x}}{\partial r_{x}}=\frac{\partial F(\vec{r})}{\partial r_{x}}\frac{r_{x}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}+F(\vec{r})\frac{\partial}{\partial r_{x}}\left(\frac{r_{x}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}\right)
 $
in which $\frac{\partial}{\partial r_{x}}\left(\frac{r_{x}}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}\right)
 =\frac{1}{\sqrt{r_{x}^{2}+r_{y}^{2}+r_{z}^{2}}}-\frac{r_x}{(r_{x}^{2}+r_{y}^{2}+r_{z}^{2})^{3/2}}$
When I use this in a model, the answers are incorrect, so it got me to think there is something wrong in my reasoning.


text:
Q: Regex with conditions I have two lists of words, and i'm building a regex to parse a list of strings.
sub = []
for pos,line in enumerate(lines):
  for word in wordsFromList1:
    regex = r".?" + re.escape(word) + r"(.*?)\."
    try:
      found = re.finditer(regex, line, re.IGNORECASE)
      for matchNum, match in enumerate(found):
        for groupNum in range(0, len(match.groups())):
          groupNum = groupNum + 1
          sub.append(word + ' ->' + match.group(groupNum))
    except AttributeError:
      found = 'error'

Right now i'm cycling through the first list, finding a term and capturing everything after that until a period shows up. But, sometimes i would prefer to cut that capture short IF a word from wordsFromList2 comes before the period. How would i change the expression (while nesting another loop for that list) in order to make that happen?
Thanks!


text:
Q: Why was my vim question moved to SU?
Vim questions: do they belong to Stack Overflow or Super User? - Discussing which site vim questions should be asked.
Are questions about vi, vim, and other clones on-topic here? - Discussing whether vim is on topic at http://unix.stackexchange.com

My question Upgrading Vim on Mac OS X regarding vim boiled down to, what I believe, is a developer issue.  The $PATH value in your ~/.bash_profile and using an IDE.  Not only that but the community has seemed to agree that SO is the place for vim questions.
I don't particularly care if the question gets moved back to SO.  I'd just like to know, why was it moved in the first place?  What aspect of my question made it more suitable for SU?

A: Your question is neither about programming, nor about using vim, both of which would qualify it for SO. It's about how to get your OS to pick up a specific executable when you call it without a qualified path. It's not specific to vim, nor something specific to developers at all.
So it's a better fit for SU.


text:
Q: Setting up a samba share between windows xp and ubuntu 11 in a vm player I am trying to mount a shared folder from windows xp to my ubuntu vm.  It is running in vm player.
I installed samba with sudo apt-get smbclient smbfs
Next, I run smbclient -L computer_name_here and get the error NT_STATUS_LOGON_FAILURE.  What am I doing wrong?  How can I solve this?

A: The only thing that I can think of is to check the network type, in settings. I think it works properly with a nat'ed interface, however if you want to be sure, you can try a host only network. Also, look into the -U option for smbclient, and specify a suername:
smbclient -L computer_name -U user_name


text:
Q: Interpreting conflicting Regression Results I have a bit of a question regarding interpreting regression coefficients. Let's say for example I have data which covers a three week period of time, and that I have a simple linear equations as follows:
y ~ x
Let's say I run the regression over this three week period of time such that for the coefficient of x I find that it is equal to 0.0032 for the whole period.
Now, let's say I want to divide up the period and run the regression per week instead, so that for Week 1 for x I obtain the coefficient 0.00977, for Week 2 I obtain 0.02877, and for Week 3 I obtain 0.00318.
I'm a little confused by this, Week 1 has less data compared to Week 2 and Week 3, but Week 2 and 3 have pretty much the same amount of data, so I'm not sure why the regression results for Week 3 are very similar to the overall regression results over the whole period. Can anyone provide any ideas of why this might be the case? Naturally since I haven't provided any data it would impossible fore anyone to give me the exact reason, but I'm mostly looking for some ideas for why I'm obtaining these results, and whether perhaps there's a way to measure or account for this phenomena. Thanks in advance.


text:
Q: "class A succeeds class B" means in Scala reference? In the Scala 2.8 reference, section 5.3.3 page 69 (77 in the pdf) the following paragraph appear:

Assume a trait D defines some aspect
  of an instance x of type C (i.e. D is
  a base class of C). Then the actual
  supertype of D in x is the compound
  type consisting of all the base
  classes in L(C) that succeed D.

What does the notation L(C) means (in the original text it's a calligraphic capital \ell like symbol)?
What does the phrase "classes... that succeed D" means? I'm not familiar with the notation.

A: The bottom line is, L(C) consists of all the base classes (the whole inheritance hierarchy of C, including traits) ordered as a chain, with Any at the top, and C at the bottom. Succeeds D means, is higher in the chain then D.
The longer explanation is that we want to know, for each class, its "parent" -- for implementation purposes and general clarity (it's terribly messy in C++, where unbounded multiple inheritance is allowed). In Java it is simple -- you only have a single direct superclass. However, because of the mixin-class composition in Scala, which is a form of multiple inheritance (from one superclass + possibly several traits), the base classes of any class form a directed acyclic graph. L(C) is the linearization of the C's base classes -- starting from the superclass, and adding the traits (and their base classes) such that they form a chain and each class has her own base classes above itself. You can read more about it in Section 6 of the overview of Scala. It's a nice, comprehensive outline of the feature.

A: L(C) is class linearization. Then "succeeds" regards to the position in the result sequence. Linearization is defined in chapter 5.1.2 of the spec.


text:
Q: Arrays.sort not filling array, overwriting values that are already in the array I need to generate an array int[] randomNumbers of random numbers with no duplicates. To do this, I make an array with all values that can go into randomNumbers, then use a random number generator to pick one out of the list, check if it's already in randomNumbers, and if it isn't, put it in randomNumbers.
(I want numbers between 1 and max, not 0 and max-1)
To be able to use Arrays.sort(int[]), the list needs to be sorted. So I use a third array, with the same values as randomNumbers called sortedNumbers, and sort it on every iteration:
public int[] uniqueRandom(int max, int numRequired) {
    if (max < numRequired) {
        numRequired = max;
    }
    int[] randomNumbers = new int[numRequired];
    int[] sortedNumbers = new int[numRequired];
    int[] sequentialNumbers = new int[max];
    for (int i = 1; i < max; i++) {
        sequentialNumbers[i] = i;
            System.out.println(sequentialNumbers[i]);
    }

    int p = 0;
    while (p < numRequired) {
        int j = r.nextInt(max) + 1;
        System.out.println("J:" + j);
        if (Arrays.binarySearch(sortedNumbers, j) >= 0) {
            System.out.println("Number Found:" + Arrays.binarySearch(randomNumbers,  j));
        } else {
            randomNumbers[p] = j;
            sortedNumbers[p] = j;
            Arrays.sort(sortedNumbers);
            for (int i = 0; i < randomNumbers.length; i++) {
                System.out.println("rNum[" + i + "]:" + randomNumbers[i]);
            }
            System.out.println("\n");
            for (int i = 0; i < randomNumbers.length; i++) {
                System.out.println("sNum[" + i + "]:" + sortedNumbers[i]);
            }
            p++;
        }

    }

    return randomNumbers;
}

My issue is that I'm getting an output where sortedNumbers is overwriting values. For uniqueRandom(5, 5) the output is:
J:2
rNum[0]:2
rNum[1]:0
rNum[2]:0
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:0
sNum[4]:2

J:2 // 2 already in the list, try again

J:2

J:4
rNum[0]:2
rNum[1]:4
rNum[2]:0
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:0
sNum[3]:2
sNum[4]:4

J:5
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:0
rNum[4]:0

sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:4
sNum[4]:5

J:2

J:3
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:0

sNum[0]:0  // Should be:
sNum[1]:0  // 2
sNum[2]:2  // 3
sNum[3]:3  // 4
sNum[4]:5  // 5

J:4
rNum[0]:2
rNum[1]:4
rNum[2]:5
rNum[3]:3
rNum[4]:4

sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:3
sNum[4]:4

So you can see the issue. I'm using java 1.7, and have no idea why it's doing this!

A: You are putting the new number into both arrays using the same index. Your rNum array is filling from top down, but the sorted array is not: Each time you sort it, the new value moves down in the array and the zeros are always at the top. I think you could fix it by always putting the new number in the first position of the sorted array:
sortedNumbers[0] = j;

A: To solve your problem I would use a Set, that assure us to have unique results.
Below snipest will generate array with required number of unique integers.
Set<Integer> uniqueNumbers = new HashSet<Integer>();
Random r = new Random();
while(uniqueNumbers.size() < numRequired) {
    uniqueNumbers.add(r.nextInt(maxRandom) + 1);
}
return uniqueNumbers.toArray(new Integer[0]);

A: When you input J=5
the sortedNUm[] is
sNum[0]:0
sNum[1]:0
sNum[2]:2
sNum[3]:4
sNum[4]:5

next when you input J=3 (your p=3)
after
sortedNumbers[p] = j;

your sNUM[3] which is 4 is replaced by 3
hence after sorting it becomes
sNum[0]:0  // Should be:
sNum[1]:0  // 2
sNum[2]:2  // 3
sNum[3]:3  // 4
sNum[4]:5  // 5

notice 4 is not present
I suggest you initialize the array to -1 or 0 and add the variables at the start of array
like
sortedNumbers[0]=j;

and after Arrays.sort(); the first position will always be empty to add more numbers

A: While it doesn't answer the question, here is an alternative which is O(n) and work well provided max is not large.
public static void main(String[] args) {
    System.out.println(Arrays.toString(uniqueRandom(20, 10)));
}

public static int[] uniqueRandom(int max, int numRequired) {
    int[] possible = new int[max];
    int[] ret = new int[numRequired];
    for (int i = 0; i < max; i++)
        possible[i] = i + 1;
    Random r = new Random();
    int numLeft = max;
    for (int i = 0; i < numRequired; i++) {
        int idx = r.nextInt(numLeft);
        ret[i] = possible[idx];
        if (idx < --numLeft)
            possible[idx] = possible[numLeft];
    }
    return ret;
}

prints
[4, 10, 12, 19, 8, 3, 15, 1, 14, 7]

What I am trying to say is that perhaps you could make it simpler.

A: There are a few issues with your code:

*

*since you only increment p when the new number j doesn't already exist in the arrays, that, combined with the fact that you sort the sortedArray first leads to the value actually being placed sometimes over an existing value (which shifted position due to the sort)

*I don't understand what's the use of the sequentialNumbers array...
Here's an example which should work:
private static Random r = new Random();

public static void main(String[] args) {
    System.out.println(Arrays.toString(uniqueRandom(10, 10)));
}

public static int[] uniqueRandom(int max, int numRequired) {
    if (max < numRequired) {
        numRequired = max;
    }
    int[] randomNumbers = new int[numRequired];
    int[] sortedNumbers = new int[numRequired];
    Arrays.sort(sortedNumbers);

    int p = 0;

    while (p < numRequired) {
        int j = r.nextInt(max) + 1;
        if(Arrays.binarySearch(sortedNumbers, j)<0) {
            randomNumbers[p] = j;
            System.arraycopy(randomNumbers, 0, sortedNumbers, 0, randomNumbers.length);
            Arrays.sort(sortedNumbers);
            p++;
        }
    }

    return randomNumbers;
}


text:
Q: Boostrap datepicker + after inputbox it not working I am using bootstrap date-picker. I need to show multiple datepicker.
Html code:

<input type="text" class="dateRangePicker" value=""/>

<button name="clone" value="clone"></button>

Js code:
$(document).ready(function() {
$(".dateRangePicker").datepicker({
            format : 'yyyy-mm-dd',
            startDate : new Date(),
            autoclose : true,

        });
$("button").click(function(){
var clone = $('.dateRangePicker').clone();
$('.content').append(clone);
});

});

After I click the button the dateRangePicker clone will be append to content div.
Error: Append inputbox datepicker not working.
Expected : After append the textbox for all datepicker need to work

A: Initialize datepicker as below to attach it to dynamically created elements:
DEMO
$('body').on('focus',".dateRangePicker", function(){
      $(this).datepicker({
            format : 'yyyy-mm-dd',
            startDate : new Date(),
            autoclose : true
      });
});

Note - If $('body') doesn't work for you [there are possibilities] then please use $(document)

A: In your code you are initializing the datepicker using the code
$(".dateRangePicker").datepicker({
        format : 'yyyy-mm-dd',
        startDate : new Date(),
        autoclose : true,

    });

You need to also call this code from your button click after the HTML has been cloned to initialize the new datepicker.


text:
Q: Save file on windows phone 8.1 How to save a file that is not to replace the previous file on windows phone 8.1? Because using the code below, there is always a message dialog to replace and cancel, can not change the file name.
This is the code:
public void Save()
        {
            //isContentChanged = false;
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            //{
            //    SuggestedStartLocation = PickerLocationId.PicturesLibrary
            //};
            savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" });
            savePicker.FileTypeChoices.Add("Word 97 - 2003 Document", new List<string>() { ".doc" });
            savePicker.FileTypeChoices.Add("Rich Text Document", new List<string>() { ".rtf" });
            savePicker.DefaultFileExtension = ".docx";
            savePicker.SuggestedFileName = "WordDocument";
            savePicker.PickSaveFileAndContinue();

        }

        /// <summary>
        /// Continues the file save picker.
        /// </summary>
        /// <param name="fileSavePickerContinuationEventArgs">The <see cref="FileSavePickerContinuationEventArgs"/> instance containing the event data.</param>
        public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
        {
            bool showErrorMsg = false;
            if (args.File != null)
            {
                try
                {
                    System.Threading.CancellationTokenSource src = new System.Threading.CancellationTokenSource();
                    Debug.WriteLine(args.File.Name + " was saved.");
                    richTextBox.Save(args.File);
                }
                catch
                {
                    showErrorMsg = true;
                }
                if (showErrorMsg)
                {
                    MessageDialog dialog = new MessageDialog("Save Failed");
                    await dialog.ShowAsync();
                }
            }
        }

Please help me


text:
Q: TiKZ node name prefixes in scopes I am using TiKZ to draw two copies of the same graph above each other, and now I want to add edges between a vertex in one copy and a vertex in the other copy. It suddenly occurred to me that it would be nice if I could put each copy in a separate scope, give each scope a name, and refer to nodes inside the scope in an "object oriented" way by referring to the node as <scope name>.<node name>. To illustrate, it would be cool if I could do something like this:
\documentclass{article}

\usepackage{tikz}

\begin{document}

\tikzstyle{vertex}=[circle,draw,fill=black!20]

\begin{tikzpicture}

% ---- Copy 1
\begin{scope}[yshift=-32pt,name=G1]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (0, 0) {v};
\end{scope}

% ---- Copy 2
\begin{scope}[yshift=32pt,name=G2]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (0, 0) {v};
\end{scope}

\draw (G1.u) -- (G2.v);

\end{tikzpicture}

\end{document}

Here, I refer to node u of scope G1 as G1.u, and to node v of scope G2 as G2.v.
Is something like this possible in TiKZ?

A: Instead of scopes, with TiKZ 3.0 is possible to use pics. If a name is assigned to a pic, this name acts as name prefix and is appended before any internal node name.
An example will be more clear than my english:
\documentclass{standalone}

\usepackage{tikz}

\begin{document}

%\tikzstyle{vertex}=[circle,draw,fill=black!20]

\tikzset{vertex/.style={circle, draw, fill=black!20},
    myscope/.pic={
        \node[vertex] (-u) at (0,0) {u};
        \node[vertex] (-v) at (0,1) {v};
    }
}

\begin{tikzpicture}

\pic[yshift=-32pt] (G1) {myscope};
\pic[yshift= 32pt] (G2) {myscope};

\draw (G1-u) to[out=30,in=-30] (G2-v);
\draw (G2-u) to[out=210,in=150] (G1-v);

\end{tikzpicture}

\end{document}

A: Edit: It looks like my answer below is completely unnecessary since TikZ has a standard name prefix key that acts much the same way as what I wrote (although it doesn't separate with the prefix from the name with spaces).
The manual has this to say about the name prefix key:

The value of this key is prefixed to every node inside the current
  scope. This includes both the naming of the node (via the name key or
  via the implicit (⟨name⟩) syntax) as well as any referencing of the
  node. Outside the scope, the nodes can (and need to) be referenced
  using "full name" consisting of the prefix and the node name.
The net effect of this is that you can set the name prefix at the
  beginning of a scope to some value and then use short and simple names
  for the nodes inside the scope. Later, outside the scope, you can
  reference the nodes via their full name:
\tikz {
  \begin{scope}[name prefix = top-]
    \node (A) at (0,1) {A};
    \node (B) at (1,1) {B};
    \draw (A) -- (B);
  \end{scope}
  \begin{scope}[name prefix = bottom-]
    \node (A) at (0,0) {A};
    \node (B) at (1,0) {B};
    \draw (A) -- (B);
  \end{scope}
  \draw [red] (top-A) -- (bottom-B);
}

Using built-in functionality is almost certainly the best choice.

Original answer:
Loop Space gave a nice answer that works as long as you don't need to refer to the nodes by their unprefixed names.
For example, if you add a \draw (u) -- (v); inside each of those scopes, you get the somewhat mysterious error, Package pgf Error: No shape named u is known.
A better option is to change the definition of prefix node name to not change how names are recorded but to add an alias with the prefix.
\tikzset{
  prefix node name/.style={%
    /tikz/name/.append style={%
      /tikz/alias={#1 ##1}%
    }%
  }
}

In essence, adding prefix node name=foo to a scope will cause all name=bar inside the scope to act as if it were name=bar,alias={foo bar}.
Here's a modification of Loop Space's example using the above definition of prefix node name and a slight modification to the picture (so the nodes aren't on top of each other) and with some \draws added to show the effect.
\documentclass{article}
\usepackage{tikz}

\tikzstyle{vertex}=[circle,draw,fill=black!20]

\tikzset{
  prefix node name/.style={%
    /tikz/name/.append style={%
      /tikz/alias={#1 ##1}%
    }%
  }
}

\begin{document}
\begin{tikzpicture}

% ---- Copy 1
\begin{scope}[yshift=32pt,prefix node name=G1]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (2, 0) {v};
  \draw (u) -- (v);
\end{scope}

% ---- Copy 2
\begin{scope}[yshift=-32pt,prefix node name=G2]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (2, 0) {v};
  \draw (u) -- (v);
\end{scope}

\draw[->] (G1 u) -- (G2 v);
\end{tikzpicture}

\end{document}

A: Here's a simple hack that redefines the naming code inside the scope to append a prefix.  You can't use a . as a separator though as that would confuse the parser.  I've used a space, but you could use something else (some punctuation, such as . is special, there's a list somewhere here).
\documentclass{article}
%\url{http://tex.stackexchange.com/q/128049/86}

\usepackage{tikz}

\begin{document}

\tikzstyle{vertex}=[circle,draw,fill=black!20]

\makeatletter
\tikzset{%
  prefix node name/.code={%
    \tikzset{%
      name/.code={\edef\tikz@fig@name{#1 ##1}}
    }%
  }%
}
\makeatother

\begin{tikzpicture}

% ---- Copy 1
\begin{scope}[yshift=-32pt,prefix node name=G1]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (0, 0) {v};
\end{scope}

% ---- Copy 2
\begin{scope}[yshift=32pt,prefix node name=G2]
  \node[vertex] (u) at (0, 0) {u};
  \node[vertex] (v) at (0, 0) {v};
\end{scope}

\draw (G1 u) -- (G2 v);

\end{tikzpicture}

\end{document}

Note that this works both with implicit and explicit naming of nodes (ie via name=<name> and \node (name) ...).


text:
Q: How to pass string without quotes in cassandra parameter of .execute method My query:
SELECT *
FROM employee.emp_details
WHERE id = 7

This is my code
from cassandra.cluster import Cluster

HOST = ['10.107.2.123']
PORT = '9042'
cluster = Cluster(HOST, PORT)
session = cluster.connect()

val = 'FROM'
rows = session.execute('''SELECT * %s employee.emp_details WHERE id = %s''', (val, 7))

This is the error that I am getting:

Traceback (most recent call last):
  File "/home/sachhya/Documents/Example/ex.py", line 9, in
  rows = session.execute('''SELECT * %s employee.emp_details WHERE id = %s''', (val, 7))
  File "/usr/local/lib/python3.6/dist-packages/cassandra/cluster.py", line 2134, in execute
  return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
  File "/usr/local/lib/python3.6/dist-packages/cassandra/cluster.py", line 4026, in result
  raise self._final_exception
  cassandra.protocol.SyntaxException:

I believe that my query string is something made like that after parameter bind. SELECT * 'FROM' employee.emp_details WHERE id = 7
Please help I need to use 'val' variable to bind in my query string.

A: Technically, you don't have to bind the FROM in your query. Use string formatting in this case:
rows = session.execute('''SELECT * {} employee.emp_details WHERE id = %s'''.format(val), (7,))

A: from cassandra.cluster import Cluster

HOST = ['10.107.2.123']
PORT = '9042'
cluster = Cluster(HOST, PORT)
session = cluster.connect()

val = 'FROM'
query = 'SELECT * {} employee.emp_details WHERE id = {}'.format(val, 7)

# or query = ('SELECT * %s employee.emp_details WHERE id = %s' % (a, 7))

rows = session.execute(query)

output from terminal:
>>> query = ('SELECT * %s employee.emp_details WHERE id = %s' % (a, 7))
>>> query
'SELECT * FROM employee.emp_details WHERE id = 7'

>>> query = 'SELECT * {} employee.emp_details WHERE id = {}'.format(a, 7)
>>> query
'SELECT * FROM employee.emp_details WHERE id = 7'

A: Let me show you the power of prepared statements.
from cassandra.cluster import Cluster
HOST = ['10.107.2.123']
 PORT = '9042'
 cluster = Cluster(HOST, PORT)
 session = cluster.connect()
val=7
query="SELECT * employee.emp_details WHERE id = ?"
prepared_query=session.prepare(prepared_query)
results=session.execute(prepared_query,(val))
print results
Use Prepared Statements to when you have to iterate through variables in query.
Visit: Prepared Statements Docs


text:
Q: Progressive association in Clojure I came across a thing I needed today where I wanted to progressively associate entries in a map, each based on the results of the previous one(s). Here's what I did:
(defn -Y [v k f] (assoc v k (f v)))

(defn build-map [a-map]
 (-> a-map
  (-Y :x #(reduce + (:values %) )  )
  (-Y :y #(/ (:x %) 100) )
  (-Y :z #(* (:y %) 10000000) )
 )
)
(build-map {:values (range 8)})

I'd welcome your thoughts on a) is it a good thing ? b) is there an existing way to do it that I haven't seen ? (I don't know the API well)

A: So you got a map that goes through some transformations and you end up with a final map. Your implementation looks fine to me except that -Y isn't doing much of thing and it may not be required as a separate function.
You can do all this using just reduce function, something like:
(def operations [ [:x #(reduce + (:values %))]
                  [:y #(/ (:x %) 100)]
                  [:z #(* (:y %) 10000000)]
                ])

(defn build-map [a-map]
   (reduce (fn [s [k f]] (assoc s k (f s) ) ) a-map operations)
   )

(build-map {:values (range 8)})

A: I think the answer by Ankur is a good improvement on your original design.
I just wanted to mention that it's not always necessary to overcomplicate things. If you compute all the additional map entries in the same function anyways, this simple approach is much more readable, in my opinion:
(defn build-map [a-map]
  (let [x (reduce + (:values a-map))
        y (/ x 100)
        z (* y 10000000)]
    (merge a-map {:x x :y y :z z})))


text:
Q: NAT using iptables on Ubuntu 16.04 doesn't work I used to use Ubuntu 14.04 trusty for our NAT server (build on Google Cloud Platform), but recently I tried to use the Ubuntu 16.04 xenial.
I configured perfectly same as I've done in 14.04, but it DOESN'T WORK as NAT server. The only difference is the versions of the OS and libraries.
The configuration is quite simple, which is described in Google's documentation:

*

*Allow IP forwarding sudo sysctl -w net.ipv4.ip_forward=1 and

*Configure the iptables sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
https://cloud.google.com/compute/docs/networking#natgateway
That's it. In Ubuntu 14.04, it worked. In Ubuntu 16.04, it didn't.
Can someone help me to configure it correctly?
I have no idea what I'm missing nor what point I should check.
Thanks in advance!

Here're the additional info
In Ubuntu 14.04
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.5 LTS"
$
$ sudo dpkg -l iptables
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name             Version       Architecture  Description
+++-================-=============-=============-=====================================
ii  iptables         1.4.21-1ubunt amd64         administration tools for packet filte
$
$ sudo iptables -v -x -n -L
Chain INPUT (policy ACCEPT 5898 packets, 944634 bytes)
    pkts      bytes target     prot opt in     out     source               destination
    5898   944634 sshguard   all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 40 packets, 3444 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 5658 packets, 526971 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain sshguard (1 references)
    pkts      bytes target     prot opt in     out     source               destination
$
$ sudo iptables -t nat -v -x -n -L
Chain PREROUTING (policy ACCEPT 18 packets, 3471 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 14 packets, 3231 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 797 packets, 48528 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
    pkts      bytes target     prot opt in     out     source               destination
     801    48768 MASQUERADE  all  --  *      eth0    0.0.0.0/0            0.0.0.0/0
$
$ ifconfig
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
          inet addr:10.146.0.3  Bcast:10.146.0.3  Mask:255.255.255.255
          inet6 addr: fe80::4001:aff:fe92:3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1460  Metric:1
          RX packets:6379 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6099 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1080290 (1.0 MB)  TX bytes:644140 (644.1 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
$
$ sudo sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

In Ubuntu 16.04
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS"
$
$ sudo dpkg -l iptables
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name             Version       Architecture  Description
+++-================-=============-=============-=====================================
ii  iptables         1.6.0-2ubuntu amd64         administration tools for packet filte
$
$ sudo iptables -L -v -x -n
Chain INPUT (policy ACCEPT 474 packets, 44440 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
    pkts      bytes target     prot opt in     out     source               destination
      16      960 ACCEPT     all  --  *      ens4    0.0.0.0/0            0.0.0.0/0
       0        0 ACCEPT     all  --  ens4   *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT 355 packets, 38412 bytes)
    pkts      bytes target     prot opt in     out     source               destination
$
$ sudo iptables -t nat -v -x -n -L
Chain PREROUTING (policy ACCEPT 9 packets, 3013 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 6 packets, 2833 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 756 packets, 46153 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 759 packets, 46333 bytes)
    pkts      bytes target     prot opt in     out     source               destination
       0        0 MASQUERADE  all  --  *      ens4    0.0.0.0/0            0.0.0.0/0
$
$ sudo ifconfig
ens4      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
          inet addr:10.146.0.4  Bcast:10.146.0.4  Mask:255.255.255.255
          inet6 addr: fe80::4001:aff:fe92:4/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1460  Metric:1
          RX packets:6274 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6064 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1043141 (1.0 MB)  TX bytes:641746 (641.7 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
$
$ sudo sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

A: I believe this has to do with a systemd-networkd change. I was trying to accomplish something similar recently on Ubuntu 16.04, and stumbled across a webpage explaining that forwarding has to be enabled on the interface itself. I am unable to find this webpage at the moment, and I don't know when this was changed.
So this will enable forwarding, but in addition to this, it has to be enabled on the interface
sudo sysctl -w net.ipv4.ip_forward=1

To see if forwarding is enabled or not, run this:
sysctl -a | grep forwarding

To enable forwarding on eth0, run this:
sudo sysctl net.ipv4.conf.eth0.forwarding=1

I believe I read that enabling forwarding on an interface will set net.ipv4.ip_forward to 1, so the first step might not be necessary. If this is the case, disabling forwarding again on the interface will not revert net.ipv4.ip_forward back to 0. At least that's how I  remember it.

A: Make sure you have set set the firewall to allow forwarding of traffic. It's possible that switching to Ubuntu 16 that the firewall is preconfigured to an implicit deny policy for packet forwarding
sudo iptables -A FORWARD -o eth0 -j ACCEPT
sudo iptables -A FORWARD -m state \
--state ESTABLISHED,RELATED -i eth0 -j ACCEPT

Also make sure that you have added your NAT rule to run  after reboot. Add the same rule to /etc/rc.local
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


text:
Q: Getting Errors where there should be none I do not know why I am being asked to place commas where periods should be. const cards is saying I can't set it there when this is the way to set a variable.
I have tried to change from const to let and restructure .forEach syntax
class TabLink {
    constructor(tabElement) {
        // assign this.tabElement to the tabElement DOM reference
        this.tabElement = tabElement;

        // Get the `data-tab` value from this.tabElement and store it here
        this.tabData = this.tabElement.dataset.tab;

        // We need to find out if a user clicked 'all' cards or a specific category.  Follow the instructions below to accomplish this task:

        // Check to see if this.tabData is equal to 'all'
        if (this.tabElement.dataset.tab === "all") {
            // If `all` is true, select all cards regardless of their data attribute values
            this.cards = document.querySelectorAll(".card");
        } else {
            // else if `all` is false, only select the cards with matching this.tabData values
            this.cards = document.querySelectorAll(`.card[tabData="${this.tabData}"]`);
        }

        // Map over the newly converted NodeList we just created in our if statement above. Convert each this.cards element into a new instance of the TabCard class. Pass in a card object to the TabCard class.
        this.cards = Array.from(this.cards).map((card) => new TabCard(card));

        // Add a click event that invokes this.selectTab
        this.tabElement.addEventListener('click', () => { this.selectTab() });
    }

    selectTab() {

            // Select all elements with the .tab class on them
            // const tabs = document.querySelectorAll();
            const tabs = document.querySelectorAll('.tab');

            // Iterate through the NodeList removing the .active-tab class from each element
            Array.from(tabs).forEach((tabs))
            link.classList.remove(".active-tab");
        }
        //

    // Select all of the elements with the .card class on them
    const cards = document.querySelectorAll('.card');

    // Iterate through the NodeList setting the display style each one to 'none'
    cards.forEach(card => {
        card.style.display = "none";
    })

    // Add a class of ".active-tab" to this.tabElement
    this.tabElement = ".active-tab";

    // Notice we are looping through the this.cards array and invoking selectCard() from the TabCard class. Just un-comment the code and study what is happening here.
    this.cards.forEach(card => card.selectCard());
    console.log(this.cards);
}

'const' can only be used in a .ts file.
';' expected.
',' expected.
',' expected.
Unexpected token. A constructor, method, accessor, or property was expected.
Declaration or statement expected.


text:
Q: python 2.7 isnan() function not working I am having a slight issue with math's .isnan() function in python. Pretty much, I have this code:
import math
diceChoice = raw_input('Which dice will you throw?\n 4 sides\n 6 sides\n 12 sides?\n>')

if math.isnan(float(diceChoice)):
    print(str(diceChoice) + ' is an invalid choice')

and if diceChoice isn't a number (eg 'a') it gives me the error:
ValueError: could not convert string to float: a

If I don't convert it to a float, it gives me another error saying that it needs to be a float. I must be doing something wrong as the isnan function would be useless if it only accepts numbers. Can someone please help me
Thanks in advance

A: The float() function used on any other string other than a decimal number, 'nan', '-inf' or 'inf' (or slight variants of those strings) will throw a ValueError instead, because anything else is not a valid floating point value. math.isnan() only works on the special float value float('nan'), but it is not ever called if float() raises an exception first.
Use exception handling to catch that error instead:
try:
    diceChoice = int(diceChoice))
except ValueError:
    print(diceChoice, 'is an invalid choice')

I used int() instead because your input requires that the user enters a whole number.
Just to be explicit: float('nan') is a specific floating point value to signify the output of certain mathematical operations that are not an exception. It is never used to signify invalid input.

A: isnan() is really only used to check if a number doesn't have a finite value. Consider instead doing something like:
if not diceChoice.isdigit():

The error is raised because you attempt to convert a string to an integer with float('a'). Easier to just do the above.

A: NaN are used to define things that are not numbers in a floating point context like 0/0 or the square root of a negative number for example. You can use isdigit or something else.


text:
Q: How to stop execution of a function via add_action hook? I have the following functions:
function test($post_id){

do_action('test_action',$post_id);

echo $post_id;

}

add_action('test_action',function($post_id){

if ( $post_id == 2 ) //Stop test function execution

}

Using the function hooked to add_action, how to stop the execution of test() function without adding any code to test(). In the above example, if $post_id == 2 , the echo $post_id; code should not run in test().

A: The usual way to add an action hook is more like this:
// ... some other code
do_action( 'my_action', $post_id );

// ...elsewhere
add_action( 'my_action', 'wpse405965_function' );
/**
 * Function hooked to my_action
 *
 * @param int $post_id The post ID.
 */
function wpse405965_function( $post_id ) {
    if ( 2 !== $post_id ) {
        echo $post_id;
    }
}

The way you've wrapped the do_action() inside a function confuses me. It seems extraneous.
Reference

*

*add_action()

A: You have both registered and called action hooks, did you know you could do the same with filters? This answer uses a filter to call a return; statement as the community suggested, to do an early return and stop executing the rest of test function body (echo in your case).
function test($post_id)
{
    do_action('test_action', $post_id);

    if ( apply_filters('wpse_405965_stop_execution', false) )
        return;

    echo $post_id;
}

add_action('test_action', function($post_id)
{
    if ( $post_id == 2 ) // Stop test function execution
        add_filter('wpse_405965_stop_execution', '__return_true');
});


text:
Q: Loading PHP webform in Magnific Popup Modal I have been creating a some web form's for the purpose of setting up meeting request for IT equipment.
I have the a pre-made form (equip_meeting.php) that is Styled with CSS that I want to load in Magnific Popup Modal.
Once the data is entered and validations are confirmed the form will submit the data to a equip_meeting_mail.php page to be formatted for email deliver to a designated email box.
The modal will close and the user will be sent to the confirmation page outputted with the success message of the Mail send.
I am using the following test page code and the php form will not load.
Below is the Popup Page Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<link rel="stylesheet" type="text/css" href="itform.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="magnific-popup/magnific-popup.css">

Open modal

<?php include "equip_meeting.php" ?>

Dismiss

The page being opened is a styled form page.

A: Apparently single quotes around the equip_meeting.php resolved this issue.


text:
Q: Rails redirect to html file stored in S3 There's a button in our Rails application which will redirect to the HTML file stored in S3. The file is not public accessible so we need to download the HTML in memory (stored as
a variable in rails controller) and load it as a separate HTML.
I can already read the file from S3 in a string (in HTML format), but how I can tell rails to render that as a HTML page? Thanks in advance.


text:
Q: Spring OAuth + JWT -- /oauth/token I'm trying to configure my spring application to use JWT using https://github.com/spring-projects/spring-security-oauth.  I've exposed a bean for ConsumerTokenServices backed by a JwtTokenStore, but hitting /oauth/token doesn't give me a JWT.
$ curl localhost:8643/contextpath/oauth/token?grant_type=client_credentials -u user:password`
{"access_token":"a78a6225-78d5-4cb8-9393-6c0b567a6f24","token_type":"bearer","expires_in":5684,"scope":"read write"}%

I know that the TokenStore is being used, because hitting check_token produces an error, where it didn't before.
$ curl https://localhost:8643/context/oauth/check_token?token=a78a6225-78d5-4cb8-9393-6c0b567a6f24
{"error":"invalid_token","error_description":"Cannot convert access token to JSON"}%
How do I make my TokenEndpoint spit back a JWT?

A: Maybe you should use JwtAccessTokenConverter provided by spring and then properly  configured.
Here is an example:
public class YourTokenEnhancer extends JwtAccessTokenConverter {

//you can autowire sth for you logic

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                 OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);

    OAuth2AccessToken enhancedToken = super.enhance(customAccessToken, authentication);
    return enhancedToken;
}

And the configuration is:
 @Configuration
 @EnableAuthorizationServer
 public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
 //other config...
 @Bean
 public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new YourTokenEnhancer();
    converter.setSigningKey("secret");
    return converter;
 }

 @Override
 public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

    endpoints.authenticationManager(authenticationManager)
            .tokenStore(redisTokenStore())
            .tokenServices(authorizationServerTokenServices())
            .accessTokenConverter(accessTokenConverter())//configure it here
            ;
 }
}


text:
Q: C# Windows Form Application how to initialize an array once and not every time a button event happens I have to create a simplistic C# windows application that initializes a boolean array of size 10 to false at the beginning of the program. Then as input is added it slowly changes each array indent to true. I can't figure out where to put this. I can't put it in the enterButton event as that would initialize the entire array to "false" each time the button is clicked, but I need it to hold its last spot.
 bool[] assignedSeat = new bool[10];
 for (int i = 0; i < assignedSeat.Length; i++)
            {
                assignedSeat[i] = false;
            }

A: use this
bool[] assignedSeat = new bool[10];
int currentIndex = 0;
public Form1()
{
    InitializeComponent();
    for (int i = 0; i < assignedSeat.Length - 1; i++)
    {
        assignedSeat[i] = false;
    }
}

private void Button_Click(object sender, EventArgs e)
{
    if(currentIndex < assignedSeat.Length)
    {
       assignedSeat[currentIndex] = true;
       currentIndex++;
    }
}


text:
Q: Проверка совпадения пароля введенного на странице с паролем в БД Всем привет. Я захешировал пароль с помощью password_hash и отправил его в БД и как мне теперь при авторизации при вводе моего пароля получить тот же хеш, что хранится в БД?
Совпадения нахожу вот так:
$check_user = mysqli_query($connect, "SELECT * FROM user WHERE login = '$login' AND password = '$password'");

A: *

*Достаём пользователя из БД только по логину

*Сравниваем пароль, который ввёл пользователь и тот, что достали из бд через password_verify

*Если не совпадают - до свиданья, если совпадают - ок


text:
Q: Create a DIV next to the cursor position on click What I'm trying to do is, when a user clicks somewhere on a page, a div containing a random image would show up on in the position of a click and it stays there. This must be able to be repeated, showing a different image every time. Any suggestions?

A: With random images from 1 to 10:
jQuery(document).ready(function(){
  $(document).click(function(e){
    var num = Math.floor((Math.random()*10)+1);
    var img = $('
Image '+num+':
');
    $("#img_container").html(img).offset({ top: e.pageY, left: e.pageX});
  });
})

DEMO

A: Here's a working fiddle.
JS:
$(function(){
    var fadeDelay = 1000;
    var fadeDuration = 1000;
    $(document).click(function(e){
        var div = $('
')
            .css({
                "left": e.pageX + 'px',
                "top": e.pageY + 'px'
            })
            .append($(''))
            .appendTo(document.body);

        setTimeout(function() {
            div.addClass('fade-out');
            setTimeout(function() { div.remove(); }, fadeDuration);
        }, fadeDelay);
    });
});

CSS:
body {
    position: relative;
}

.image-wrapper {
    position: absolute;
    transform: translate(-50%, -50%);
    opacity: 1;
}

.image-wrapper.fade-out {
    opacity: 0;
    transition: opacity 1s ease-in-out;
}


text:
Q: Multiple image upload approach laravel What's the best approach to store multiple images in database?
Upon browsing and searching for solution and approaches I found 2 options
first one is take the file name and concatenate and separate them using either comma or |
but I'm having doubts since I think that's messy and would produce errors later in the system
second is I make another table for images and add foreign key (post_id) to know which post it belongs.
Any suggestion will be appreciated.

A: Both methods work well. I would place the second.
It can also provide convenience when using some image upload plugins (filepond, dropzone etc.).
If I were to choose the first method, I would save the serialized arrays (with serialize()) for better bet.

A: Second one because it is normalized and you can have a better DX with that, No weird implementation to edit or any manipulation of post.


text:
Q: Testing HOC with Recompose I'm having some troubles testing that a prop is fired on my HOC.
import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';

import { fetchCurrentUser } from '../../actions/users';
import { getUser } from '../../reducers/users';
import User from '../../models/User';

export default Component => compose(
  connect(state => ({
    user: getUser(state),
  }),
  { fetchCurrentUser }),
  lifecycle({
    componentDidMount() {
      if (this.props.user instanceof User) return;
      this.props.fetchCurrentUser();
    },
  }),
)(Component);

What I'd like to know is whether or not fetchCurrentUser is trigger when user is NOT a User instance.
So far I have that in my test:
it.only('fetches user if user is not a User instance', () => {
  const setup = () => {
  const props = {
    user: 'string',
    fetchCurrentUser: jest.fn(),
   };
   const enzymeWrapper = mounting(props);

   return {
     props,
      enzymeWrapper,
    };
  };

  // That returns 0 so false
  expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
});

It seems like I can't replace the props doing it this way. If I log this.props in the lifecycle method, I never see user: 'string'
Thanks in advance

A: You would need to shallow mount the component in order to test its functionality.
it.only('fetches user if user is not a User instance', () => {
  const setup = () => {
  const props = {
    user: 'string',
    fetchCurrentUser: jest.fn(),
   };
   // shallow render the component
   const enzymeWrapper = shallow(<Component {...props} />)

   return {
      props,
      enzymeWrapper,
    };
  };

  expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
});

A: OK so, with shubham-khatri's help, here's what I did to make it work.
Separated the component into 2 different ones, and tested the one with the call only. That way I could mock the passed props from the test.
Component:

import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';

import { fetchCurrentUser } from '../../actions/users';
import { getUser } from '../../reducers/users';
import User from '../../models/User';

const Connected = connect(state => ({
  user: getUser(state),
}),
{ fetchCurrentUser });

export const Enhanced = lifecycle({
  componentDidMount() {
    if (this.props.user instanceof User) return;

    this.props.fetchCurrentUser();
  },
});

export default Component => compose(
  Connected,
  Enhanced,
)(Component);

Test:
describe('Fetching user', () => {
    const setup = (moreProps) => {
      const props = {
        fetchCurrentUser: jest.fn(),
        ...moreProps,
      };

      const EnhancedStub = compose(
        Enhanced,
      )(Component);

      const enzymeWrapper = shallow(
        <EnhancedStub {...props} />,
      );

      return {
        props,
        enzymeWrapper,
      };
    };

    it('fetches user if user is not a User instance', () => {
      expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
    });

    it('does NOT fetch user if user is a User instance', () => {
      expect(setup({ user: new User({ first_name: 'Walter' }) }).props.fetchCurrentUser.mock.calls.length).toEqual(0);
    });
  });

Hope that helps someone.