text:
Q: PHP - string not being found within mutilple files I currently have some working code that was created years ago, but I now want to remove the stripos function and instead only use an exact match (without case sensitiveness). The code snippet below is what I have before I made modifications, and it works correctly.
<?php
$unicorn = file('unicornsites.txt', FILE_SKIP_EMPTY_LINES);
$aligator = file('aligatorsites.txt', FILE_SKIP_EMPTY_LINES);
$cat = file('catsites.txt', FILE_SKIP_EMPTY_LINES);

$srch = $_POST['search'];

$srch = preg_replace('#^https?://#', '', $srch);
$srch = preg_replace('#^wwww?.#', '', $srch);

if (array_filter($aligator, function($var) use ($srch) {return stripos($var,$srch)!==false;}))
    echo '
That site features an aligator/div>';
elseif (array_filter($unicorn, function($var) use ($srch) {return stripos($var,$srch)!==false;}))
    echo '
That site features a unicorn.
';
elseif (array_filter($cat, function($var) use ($srch) {return stripos($var,$srch)!==false;}))
    echo '
That site  features a cat.
';
else
    echo '
This site features no animal
';
 ?>

This isn't sufficient for my needs anymore, so I wanted to only say what animal is on the site when the address (the srch string) is an exact match as opposed to a very close match. I changed the program to remove the stripos function in an attempt to achieve this, but it would seem my logic is incorrect. The program successfully runs, but it doesn't actually seem to find the string "stackoverflow.com" in any text file,  despite it being in unicornsites.txt.
It's not the fault of removing http/https/www from the address as an echo confirms this. I'm sure it's a misunderstanding on my part on how I should be searching for a string within mutilple files. Can anyone re-position me in the right direction?
<?php
$unicorn = file('unicornsites.txt', FILE_SKIP_EMPTY_LINES);
$aligator = file('aligatorsites.txt', FILE_SKIP_EMPTY_LINES);
$cat = file('catsites.txt', FILE_SKIP_EMPTY_LINES);

$srch = $_POST['search'];

$srch = preg_replace('#^https?://#', '', $srch);
$srch = preg_replace('#^wwww?.#', '', $srch);

if(in_array($srch, $aligator)) {
        echo '
That site features an aligator/div>';
} elseif(in_array($srch, $unicorn)) {
        echo '
That site features a unicorn.
';
} elseif(in_array($srch, $cat)) {
        echo '
That site  features a cat.
';
    else
        echo $srch . '
This site features no animal
';
     ?>


text:
Q: (Magento\Framework\Config\Dom\ValidationException):Element 'head': Character content other than whitespace is not allowed Can anyone help me, I'm having this error, right after adding a folder in magento root
Magento/->app/->/code/-> Bag(Mycustom) .. mgento232

The message that appears is : 1 exception(s): Exception #0
  (Magento\Framework\Config\Dom\ValidationException): Element 'head':
  Character content other than whitespace is not allowed because the
  content type is 'element-only'. Line: 752

.... Can help me pLEASE
Is magento 2.3.2

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I read, run a query from an SQL file using ibm_db in Node.js? I am using Node.js and the ibm_db package to access my DB2 database. I know how to run a text script, but I have a script in an SQL file and I don't know how to approach that.
ibm_db sample:
var ibmdb = require("ibm_db")
, cn = "DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;"
;

ibmdb.open(cn, function (err, conn) {
if (err) {
    return console.log(err);
}

// we now have an open connection to the database, so lets get some data.
// Execute multiple query and get multiple result sets.
// In case of multiple resultset, query will return an array of result sets.
conn.query("select 1 from sysibm.sysdummy1;select 2 from sysibm.sysdummy1;" +
           "select 3 from sysibm.sysdummy1", function (err, rows)
{
    if (err) {
        console.log(err);
    } else {
        console.log(rows); // rows = [ [ { '1': 1 } ], [ { '1': 2 } ], [ { '1': 3 } ] ]
    }
});
});

In this case the query is performed with a string passed into con.query(...)
I have an SQL File (like sample.sql) that contains a few queries like:
select 1 from sysibm.sysdummy1;
select 2 from sysibm.sysdummy1;
select 3 from sysibm.sysdummy1;

I need to sample.sql in Node and run the queries. How do I achieve this?


text:
Q: Minimum torque required to turn a large gear I want to preface this by saying that this isn't homework, it's just a question I've made up myself (so it could just be impossible to solve), and I am a beginner so apologies if I miss something obvious.
I'm asking this question to confirm whether my reasoning is correct, and if it isn't where I went wrong / what I missed.
Let's say I have a very large gear (specifically a pinion) on a rack (which cannot move at all, only the gear may move up and down the rack, and it is free to do so for any distance (for all intents and purposes the rack is infinately long)) with $n$ teeth, a radius $r$ (which extends from the centre of the gear to the tip of the teeth), a static friction constant $\mu_s$ with the rack it is touching, a depth/length $\ell$, a mass $m$ and $\tau_{\text{applied}}$ is the torque I apply to the centre of the gear to turn it. It is some positive number. In what range must that torque be to turn the gear? I.e.: $\tau_{\text{min}} < \tau_{\text{applied}} < \tau_{\text{max}}$. Below $\tau_{\text{min}}$ the wheel would just not be able to tilt over the rack and start moving, and above $\tau_{\text{max}}$ the gear will start slipping and be considered to not work at optimal efficiency.
To calculate $\tau_{\text{max}}$ I get the force exerted on the tip of the wheel by doing $\frac{\tau_{\text{applied}}}{r}=F$. There will be friction $F_{f\text{, max}}$ opposing this and it is equal to $F_{f\text{, max}} = \mu_s N$, and since the downwards force on the gear is $-mg$, the normal must be $N=mg$ as $\sum{F_y}=0$, so $F_{f\text{, max}} = -\mu_s mg$ (negative as it is acting in the opposite direction to $F$. This means that in order for $\sum{F_x}=0$, $F$ must be at maximum $\mu_s mg$ at all times, hence $\tau_{\text{max}}=\mu_s mg \cdot r$.
To calculate $\tau_{\text{min}}$, I reason that to be able to turn and go past the turning point enough such that the centre of mass surpasses it and it begins to topple, the force acting upwards on that point must be greater than $mg$, so the torque at the turning point must be $\tau_{\text{min}}=mg \cdot d$, where $d$ is the distance from the turning point to the centre of the gear tooth. Since each gear tooth is equidistant, the width $w$ of each tooth must be $w=\frac{2 \pi r}{n}$. This means that $d=\frac{w}{2}$, or $d=\frac{\pi r}{n}$. So the minimum torque required to start to turn the gear would be $\tau_{\text{min}}=\frac{mgr}{n} \pi$.
Therefore the torque $\frac{\pi}{n} \cdot mgr < \tau_{\text{applied}} < \mu_s \cdot mgr$
This would also mean that when $\frac{\pi}{n} \ge \mu_s$ there would be no possible $\tau_{\text{applied}}$ to have turning without slipping.
Is this correct? If not, where have I gone wrong / what have I missed?

A: The purpose of a "rack and pinion" is to convert the circular motion of the gear into linear motion of the rack$^1$.
To roll the gear, torque would work against inertia and friction in the same way a smooth wheel (like a rail road locomotive) would.
However, some systems that you propose do exist for climbing steep grades.  If the gears are properly made, resistance to turning or slippage will be minimal.  It will essentially ride along with its teeth applying force to the matching component of the rack.
You would want the teeth long and strong enough not to slip or break.
$^1$ as in rack and pinion steering


text:
Q: Element type is invalid while trying to run app I'm just getting started to learn React Native, and when I try to run my app, I get this error:

Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
object.
Check the render method of ExpoRootComponent.

Here is my index.js
/**
 * @format
 */
// import 'react-native-gesture-handler';
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

Here is my App.js located in src/
import {View, StyleSheet, Text} from 'react-native';

export default function() {
  return (
    <View style={styles.Container}>
      <Text>Welcome</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
});

What am I doing wrong?

A: import React from 'react';

Try to add this import on top of your Component


text:
Q: How would you get the file server's path for images from a call to the shinyApp(ui = ui, server = server) function? In the R Shiny docs, it says you can get an image to display within a panel like so:
img(src = "my_image.png")
This will create a html image tag in your interactive web app:
<img src="r.png">
In which folder should the image file be stored to show up in the app?
How does one find the correct path through their R code?
I tried using getwd() and I tried using getwd() and adding a nested /www/ dir


text:
Q: How to convert bytearray to img tag? I have a service which returns byte array of png image , I want to render it on my jsp page .
I am making ajax call to get the image.
$.ajax({
            type: "GET",
            cache: false,
            async: false,
            url: '<spring:url value="/service/org/flk/2"/>',
            success: function(msg) {

A: You will need to stream base64 encoded data in response and then you can do it like
$("#someDivId").html('<img src="data:image/png;base64,'+response + '"/>');

where response is the base64 encoded image data


text:
Q: learn a new set of data from existing model for enhancing it (tensorflow - keras - callbacks) I make a learning on a dataset, and everything is ok. Sometimes, changes occur, and I've got some new data. I'd like to "continue" the learning from my existing model, with the new set of data, without begining from scratch again.
Here is a simple example to show the problematic and where I'm stucked.
import tensorflow as tf
mnist = tf.keras.datasets.mnist

# get the data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# split in 2 parts to get 2 set of data
x_train1 = x_train[:5000]
x_train2 = x_train[5000:10000]
y_test1 = y_test[:5000]
y_test2 = y_test[5000:]

# set the model
model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)])

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

# Compile the model
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

# set the callback
checkpoint_path = "CHECKPOINTS/cp.ckpt"
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, monitor='accuracy', mode="max", save_best_only=False, save_weights_only=False, save_freq="epoch", verbose=0)

Then I fit my first set of data :
# fit the 1st dataset
model.fit(x_train1, y_test1, epochs=5,callbacks=[cp_callback],verbose=1)

Output:
Epoch 1/5
157/157 [==============================] - 0s 897us/step - loss: >2.3518 - accuracy: >0.1075

Epoch 2/5
157/157 [==============================] - 0s 752us/step - loss: >2.2833 - accuracy: >0.1438

Epoch 3/5
157/157 [==============================] - 0s 731us/step - loss: >2.2656 - accuracy: >0.1564

Epoch 4/5
157/157 [==============================] - 0s 755us/step - loss: >2.2388 - accuracy: >0.1719

Epoch 5/5
157/157 [==============================] - 0s 759us/step - loss: >2.2117 - accuracy: >0.1901

Then my 2nd one :
# fit the 2nd one
model.fit(x_train2, y_test2, epochs=5,callbacks=[cp_callback],verbose=1)

Output:
Epoch 1/5
157/157 [==============================] - 0s 943us/step - loss: >2.3240 - accuracy: >0.0964

Epoch 2/5
157/157 [==============================] - 0s 778us/step - loss: >2.2881 - accuracy: >0.1238

Epoch 3/5
157/157 [==============================] - 0s 805us/step - loss: >2.2688 - accuracy: >0.1514

Epoch 4/5
157/157 [==============================] - 0s 814us/step - loss: >2.2498 - accuracy: >0.1496

Epoch 5/5
157/157 [==============================] - 0s 1ms/step - loss: >2.2289 - accuracy: 0.1704

As you can see, it begins from 0 again the training, without keeping the existing train made before.
How could I do that.
Thanx by advance.


text:
Q: Generic method and linq I have 2 tables in my project:
TableEnvelope{
 ID int primary key,
 EnvelopeNumber int,
 .
 .
 .
}

TableCheck{
ID int primary key,
CMC7 varchar
.
.
.
}

I have to "block" each document to a specific user, because 2 users can't see the same information.
So I have my table:
TableLock{
ID int primary key,
IDEnvelope int,
IDCheck int
UserId int
.
.
.
}

I'm trying to do a Generic method to take N rows in my table and lock it but I can't.
public IQueryable<TEntity> LockDocument<TEntity>(IQueryable<TEntity> colEntity, int countRows)
{
  TEntity objEntity = default(TEntity);
  Database db = new Database();

  var vQuery = (from entity in db.CreateObjectSet<TEntity>()
               Join tableLock in db.TableLock
                 // I have problems here.
                  on entity.ID equals tableLock.IDEntity
               where entity.ID not in tableLock.IDEntity).select().Take(countRows)
 }

How can I do this?
Thank you in advance.

A: You must constrain your TEntity to provide additional information to your method. For example you can define interface:
public interface IEntity
{
    int ID { get; }
}

And implement this interface by all entities you want to pass to your method. Now you can change the definition of your method to:
public IQueryable<TEntity> LockDocument<TEntity>(IQueryable<TEntity> colEntity,
                                                 int countRows)
    where TEntity : IEntity
{ ... }

This will tell your method that it accepts only types implementing IEntity and you can use any property or method defined by IEntity in your method = you will have access to entity.ID.


text:
Q: How do I swap a letter with its immediate neighbor in a string? I am trying to create a function that takes a string as an argument and returns a list of all of the generated words by swapping a letter with its immediate neighbor.
I first take each letter and create a list of strings and each string contains one letter.
Then I iterate through the new list of letters and try to swap them.
Then I join the letters together to form a string.
Then I append the new string to the list that I return.
Here is my code. Please tell me how to fix it. I don't want it to display the passed word in the list. Thank you.
def mixedString(word):

    word = word.lower()
    letters = []
    newArray = []

    for n in word:
        letter = f"{n}"
        letters.append(letter)

    newList = []

    for i in range(len(letters)):
        newWord = ""
        newArray = letters[i:] + letters[:i]
        newWord = "".join(newArray)
        newList.append(newWord)

    return newList

myWord = "Dog"

print(mixedString(myWord))

A: Hint: there are only n - 1 distinct words where one letter of the original word has been swapped. To see why, note that ab only has ba as result.
If a word has the letters are position i and i+1 swapped the letters before i are unchanged and the letters after i + 1 also are unchanged.
def swap(s, i):
    return s[:i] + s[i+1] + s[i] + s[i+2:]

def neighbors(s):
    return [swap(s, i) for i in range(len(s)-1)]

A: You can swap letters like this:
def swap(string, place_1, place_2):
    string = list(string)
    string[place_1], string[place_2] = string[place_2], string[place_1]
    return ''.join(string)

a = '1234'

print(swap(a, 1, 2))
>>> 1324

A: There are many points of improvement, but I will be addressing the one you ask for

I don't want it to display the passed word in the list.

Just skip the first iteration in the relevant loop, e.g. by replacing this:
for i in range(len(letters)):

with this:
for i in range(1, len(letters)):


text:
Q: xml file not found in ear file after running ant build I get the following error when I enter http://localhost:7001/ficv2.0/login on browser address bar:
WARNING: Could not find action or result: /ficv2.0/login
There is no Action mapped for namespace [/] and action name [login] associated with context path [/ficv2.0]. - [unknown location] at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)

struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="struts2web" namespace="/" extends="struts-default">
        <action name="login" class="com.ssga.fi.cv.login.action.LoginAction">
            <result name="success">/jsp/index.jsp</result>
        </action>
    </package>
</struts>

struts.xml has been placed in src directory.
build.xml:
<project name="ficv2.0" default="all" basedir=".">

<target name="set_env" unless="set_env" description="setup the properites.">

    <!-- All the system environment variables will be accessed by prefixing "env.".
    To do that following property has to be set and be pointing to env -->

    <property environment="env" />
    <property name="java.home" value="${env.JAVA_HOME}" />

    <!-- Settings for global directories -->

    <property name="root.dir" value="." />
    <property name="source.dir" value="${root.dir}/src" />
    <property name="des.dir" value="${source.dir}/des" />
    <property name="build.dir" value="${root.dir}/build" />
    <property name="classes.dir" value="${build.dir}/classes" />
    <property name="webapp.dir" value="${root.dir}/WebContent" />
    <property name="lib.dir" value="${webapp.dir}/WEB-INF/lib" />

    <!-- Refers to cvs_build dir -->
    <property name="classes.jar.name" value="ficv2.0" />
    <property name="web.jar.name" value="ficv2.0-web" />
    <property name="ear.name" value="ficv2.0" />
    <property name="war.name" value="ficv2.0" />

    <!-- Class path settings -->
    <property name="struts.jars" value="${lib.dir}/struts2-core-2.3.24.jar ; ${lib.dir}/freemarker-2.3.22.jar ;
        ${lib.dir}/xwork-core-2.3.24.jar ; ${lib.dir}/ognl-3.0.6.jar ; ${lib.dir}/commons-fileupload-1.3.1.jar;
        ${lib.dir}/commons-io-2.2.jar; ${lib.dir}/commons-lang3-3.0.jar;${lib.dir}/javaassist-3.11.0.GA.jar;" />
    <!-- End - Class path settings -->

</target>

<target name="init" depends="set_env" description="Initializes the required directories.">
    <mkdir dir="${classes.dir}" />
    <mkdir dir="${webapp.dir}" />
    <mkdir dir="${webapp.dir}/WEB-INF/lib" />
    <mkdir dir="${build.dir}/war" />
    <path id="project.class.path">
        <fileset dir="${lib.dir}">
            <include name="*.jar" />
        </fileset>
    </path>
</target>

<target name="clean" depends="set_env" description="Clean up the output directories and jar.">
    <echo message="Deleting Compiled Code..." />
    <delete dir="${classes.dir}" />
    <echo message="Deleting Copied Directories..." />
    <delete dir="${build.dir}/${ear.name}.ear" />
    <delete dir="${build.dir}/${war.name}.war" />
    <delete dir="${build.dir}/war" />
</target>

<target name="compile" depends="init" description="Compiles all source files">
    <javac debug="on" srcdir="${source.dir}" destdir="${classes.dir}" verbose="true" classpath="${struts.jars}">
    </javac>
</target>

<target name="create_jar" depends="compile" description="Package the Java classes into a jar.">
    <echo message="Creating Jar file..." />
    <delete file="${webapp.dir}/WEB-INF/lib/${classes.jar.name}.jar" />
    <delete file="${webapp.dir}/WEB-INF/lib/${web.jar.name}.jar" />
    <jar jarfile="${webapp.dir}/WEB-INF/lib/${web.jar.name}.jar" basedir="${classes.dir}" includes="**/action/**" />
</target>

<target name="create_war">
    <delete file="${build.dir}/${war.name}.war" />
    <echo message="${webapp.dir}" />
    <jar jarfile="${build.dir}/${war.name}.war" update="yes" manifest="${webapp.dir}/META-INF/MANIFEST.MF">
        <fileset dir="${webapp.dir}">
            <include name="**" />
        </fileset>
        <zipfileset dir="${webapp.dir}/images" prefix="images">
            <include name="**" />
        </zipfileset>
    </jar>
</target>

<target name="create_ear" depends="create_war">
    <delete file="${build.dir}/${ear.name}.ear" />
    <ear earfile="${build.dir}/${ear.name}.ear" appxml="${root.dir}/META-INF/application.xml">
        <fileset dir="${build.dir}">
            <include name="*.jar" />
        </fileset>
        <fileset file="${build.dir}/${war.name}.war" />
    </ear>
</target>

<target name="all" depends="set_env, create_jar, create_ear" description="Perform all targets." />

</project>

After the running the ant build, I don't see struts.xml inside the ear file.  It will be stored under ficv2.0/build/classes folder.
Please let me know what needs to be updated in build.xml so, struts.xml will be there in the ear generated & above issue is resolved.


text:
Q: How to properly compare dates to strings in PHP? I am using two functions to find certain dates relative to the ones i am passing to the function. EX: my function mgeStart($date) takes $date and finds the previous friday (as this is the start of the work week). This function works as it should. The function mgeEnd($date) compares the current date to Thursday. This is where my problem arises. Every date I pass through to mgeEnd() thinks the date I am passing it is thursday (no errors are reported in my error log). My two functions are held in functions.php, here they are:
I have added multiple error_log() statements to determine that every entry goes through the first if statement of mgeEnd().
function mgeStart($date){

  if(date('D', $date) == 'Fri') { // It is friday
    $start = $date;
  }else{
    $start = date('Y-m-d', strtotime('last friday', strtotime($date))); // last friday
  }
  // error_log("Date: ".$date." Start: ".$start);
return $start;
}

function mgeEnd($date){
  if(date('D', $date) == 'Thu') { // It is thurs
     $end = $date;
  }else{
    error_log("enter2");  //THIS NEVER GETS ENTERED
    $end = date('Y-m-d', strtotime('next thursday', strtotime($date))); // last friday
  }
  return $end;
  error_log("Date: ".$date." End: ".$end);
}

I call the functions in document2:
$endDate = mgeEnd($row_3['WorkDate']);
$startDate = mgeStart($row_3['WorkDate']);

These are inside a for loop and the values are unset at the end of each loop.
The expected result of my program is to have mgeEnd() return the next thursday of the date passed to it.
The error log statements in mgeEnd() are never posted to the log, whereas the one in mgeStart() are. mgeStart() behaves as it should whereas mgeEnd() does not.

A: It always pays to check your error logs. I bet you'd find this in yours:

Notice: A non well formed numeric value encountered...

You can't pass a string to the date() function, it expects a UNIX timestamp. You need to use strtotime() to do the conversion. Try this:
<?php

function mgeStart($date) {
    $date = strtotime($date);
    if(date('D', $date) === 'Fri') { // It is friday
        $start = $date;
    } else {
        $start = date('Y-m-d', strtotime('last friday', $date)); // last friday
    }
    return $start;
}

function mgeEnd($date) {
    $date = strtotime($date);
    if(date('D', $date) === 'Thu') { // It is thurs
        $end = date('Y-m-d', $date);
    } else {
        $end = date('Y-m-d', strtotime('next thursday', $date)); // next thursday
    }
    return $end;
}

echo mgeEnd("2019-05-17");

Live demo: https://3v4l.org/EVnmt


text:
Q: P/Invoke (DLLImport) Different Function Signature According to the documentation, when trying to call unmanaged code in my managed code, it should has the exact same function signature as the unmanaged code.
I tried putting in a different function signature that I know should not have worked.
Original:
int Foo(LibraryDefinedString str, _Outptr_ LibraryDefinedHandle * ptr)

Adaptation (after calling DllImport):
Uint32 Foo(byte[] str, IntPtr ptr)

No exceptions were thrown. Even after I changed the parameters (putting floats or another user-defined type), it still did not throw any exception.
Have not tested whether the function in the Dll actually gets called, but my main question : Is there no warning or error when putting different function signatures from the unmanaged code?

A: No, there is no warning. How could there be? There is no reflection on the native side, so there is no way for the PInvoke marshaller to validate if the managed side is correct. Either the code works, or the code has undefined behavior that may or may not fail.
In any case, your "wrong signature" may or may not be wrong. int and UInt32 have the same size. LibraryDefinedHandle* and IntPtr have the same size. What we don't know is what LibraryDefinedString is actually defined as and whether byte[] is compatible with it or not.
If the signature is mismatched, there are no errors reported on the managed side, but you may get crashes or wrong behavior on the native side.


text:
Q: NullPointerException @one-to-one mapping Hi all I've a small problem to map one-to-one using JPA 2 persistence with EclipseLink vendor and maybe any of you will be able to help.
I want to map one table with another but the field in second table is optional. So I've created @Entity for the first table:
Amp class
private AmpApInfo ampApInfo;
private String apid;

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
public String getApid() {
    return this.apid;
}

public void setApid(String apid) {
    this.apid = apid;
}

    @OneToOne
@JoinColumn(name="apid")
public AmpApInfo getAmpApInfo() {

        return this.ampApInfo;

}

public void setAmpApInfo(AmpApInfo ampApInfo) {
    this.ampApInfo = ampApInfo;
}

and @Entity for the second table
AmpApInfo class
    private String apid;
private Amp amp;
    private String prodOrderNo;

public AmpApInfo() {
}

@OneToOne(optional=true, mappedBy="ampApInfo")
public Amp getAmp() {
    return this.amp;
}

public void setAmp(Amp amp) {
    this.amp = amp;
}

    @Id
public String getApid() {
    return apid;
}
public void setApid(String apid) {
    this.apid = apid;
}

        @Column(name="prod_order_no")
public String getProdOrderNo() {
    return this.prodOrderNo;
}

public void setProdOrderNo(String prodOrderNo) {
    this.prodOrderNo = prodOrderNo;
}

Now when I want to find prodOrderNo like
    public Amp selectProdInfo(String name) {
    // TODO Auto-generated method stub

    Amp amp = Transactions.getEntityManager().find(Amp.class, name.trim());

    System.out.println("order number" + amp.getAmpApInfo().getProdOrderNo());

    return amp;
}

I'm expecting to get null cos its not there but I'm getting java.lang.NullPointerException on the line
  System.out.println("order number" + amp.getAmpApInfo().getProdOrderNo());

Any one can help???

A: Either amp is null or amp.getAmpApInfo() is returning null, and you are trying to call methods on them.


text:
Q: Ubuntu Server Only LAN Access I have installed a software in a Ubuntu Server 14.04.
I need this server to be only accesible within LAN network, for security reasons I want it to be no way accesible from outside. Also, I need to give it a static IP address.
This is what I have done:
sudo vi /etc/network/interfaces
And I have set up the following
auto eth0
iface eth0 inet static
address 192.168.1.109
netmask 255.255.255.0
network 192.168.1.1
broadcast 192.186.1.255

Is any of these unnecesary? Do I need anything else? Can I somehow set something up here to prevent my server from being accesible from the internet?
Thank you very much for your answers.

A: If you don't have any kind of port forwarding enabled in your router, any port of any local IP address won't be accessible from the Internet. So as you have used the static private IP address 192.168.1.109 for the server it won't be accessible from the Internet given no port forwarding is enabled for any port of the server.
Also note that your network address should be 192.168.1.0 and if you want to communicate to the internet from the server you should add the router's address as the gateway address. As your local IP address will be masqueraded by the public IP of the router for any outgoing request you will be safe in that case too.
You can optionally enable some packet filtering rules in iptables of the server for more fine grained firewalling.
The following network configuration should suffice:
auto eth0
iface eth0 inet static
    address 192.168.1.109
    netmask 255.255.255.0
    gateway 192.168.1.1

Assuming 192.168.1.1 is the gateway address.


text:
Q: How do I force a python Decimal to have atleast two decimals? I would need to format a python Decimal object to have atleast two decimals, but no more than 5. Is there a reliable way to do this?
Examples:
1.6 --> 1.60
1.678 --> 1.678
1.98765 --> 1.98765

If there are more than two decimals, it is vital that it does not get truncated to only two decimals.

A: It looks to me like there are two parts to this question - one, determining the correct number of digits and two, quantizing the values to that number of digits.
To do the first, I would get the current exponent using the as_tuple() method. Unless I'm overlooking something simpler.
>>> import decimal
>>> d = decimal.Decimal("1.678")
>>> d.as_tuple().exponent
-3

>>> d2 = decimal.Decimal("1.6")
>>> d2.as_tuple().exponent
-1

So from that you can compute the desired exponent:
MAX_EXPONENT = -2
MIN_EXPONENT = -5
def desired_exponent(d):
    current_exponent = d.as_tuple().exponent
    return min(MAX_EXPONENT, max(MIN_EXPONENT, current_exponent))

The second is answered by the accepted answer on the marked duplicate - use the quantize() method. You'll need to construct a Decimal value with the desired exponent you can provide as the argument to quantize(). There are multiple ways to do that, but two simple ones are exponentiating decimal.Decimal("10") or using the tuple constructor for decimal.Decimal().
>>> quant_arg = decimal.Decimal("10") ** -2
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

Or:
>>> quant_arg = decimal.Decimal((0, (), -2))
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

I used -2 as a literal there, you'd want to use the calculated value of desired_exponent.
There are multiple ways to organize this code, I think the parts that are not obvious are a) accessing the current exponent of a decimal value and b) some of the ways of constructing an arg for quantize(). And this is all assuming you need the actual decimal objects, and aren't just outputting them - if this is a question just about output formatting re-quantizing is probably overkill.

A: Here is the code I use now:
def unitAmount(value):
    """Format a Decimal to match -?[0-9]{1,15}(,[0-9]{2,5})?
    Minimum two decimals, max 5.
    """
    decimals = value.as_tuple().exponent
    if decimals == -1:  # For values like 1.6 --> 1.60
        value = value.quantize(Decimal('1.00'))
    elif decimals < -5:  # For values like 1.1234567.. --> 1.12345
        value = value.quantize(Decimal('1.00000'))
    return value


text:
Q: Count quantity of results for duplicate rows sql I have a table similar to this:
 customer         employee
------        ---------
  A              Adam
  A              Adam
  A              Adam
  B              Bob
  C              Adam
  C              Adam
  B              Bob
  D              Dan

I'm trying to figure out how to show how many times Adam has had repeat customers and how many times Bob has.
So in the example above it would return:
Adam => 2 (he's had 2 repeat customers, customer A and C)
Bob => 1 (he's had 1 repeat customer, customer b)
Dan => 0 (he's only had one customer, no repeats)
What I have so far is:
SELECT customer, COUNT(*) as cnt
FROM table
GROUP BY employee
HAVING cnt > 1

But I just can't seem to get the rest of the way.

A: You can try the below query :
SELECT
    t.employee, COUNT(*) AS cnt
FROM
    (SELECT
        employee, customer, COUNT(*) AS actcnt
    FROM
        customers
    GROUP BY customer , employee HAVING actcnt > 1) AS t
GROUP BY t.employee
ORDER BY t.employee;

DEMO

A: You first need to find the repeat customer:
SELECT employee,customer FROM yourtable GROUP BY employee, customer having COUNT(*) > 1;

After that you can find how many repeat customers each employee has had:
SELECT employee, COUNT(*) from (
 SELECT employee,customer
  FROM yourtable
  GROUP BY employee, customer
  HAVING COUNT(*) > 1
 ) t
GROUP BY employee;

A: select employee, count(*)-1 as cnt
from t1
group by employee,customer
having cnt > 0;

A:
IF you COUNT repeat  employee :

SELECT id,customer,employee,COUNT(*) FROM USER  GROUP BY employee HAVING COUNT(*)>0

IF you COUNT repeat customer :

SELECT id,customer,employee,COUNT(*) FROM USER  GROUP BY customer HAVING COUNT(*)>0

//Note: I take total count, you change )COUNT()>0 to COUNT()>1
   && Table=user as

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer` varchar(200) DEFAULT NULL,
  `employee` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

/*Data for the table user */
insert  into `user`(`id`,`customer`,`employee`)
values (1,'A','Adam'),(2,'A','Adam'),(3,'A','Adam'),(4,'B','Bob'),(5,'C','Adam'),(6,'C','Adam'),(7,'B','Bob'),(8,'D','Dan');

A: SELECT customer, employee
  FROM table
GROUP BY customer, employee
  HAVING count(*) > 1


text:
Q: Error while aggregating factor variable- argument is not numeric or logical Below is the str of my data set.
'data.frame':   9995 obs. of  10 variables:
 $ Count           : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Gates    : Factor w/ 5 levels "B6","B9","I1",..: 3 3 4 4 3 4 4 4 4 4 ...
 $ Entry_Date           : Date, format: "0006-10-20" "0006-10-20" "0006-10-20" ...
 $ Entry_Time           : Factor w/ 950 levels "00:01:00","00:04:00",..: 347 366 450 550 563 700 701 350 460 506 ...
 $ Exit_Date          : Date, format: "0006-10-20" "0006-10-20" "0006-10-20" ...
 $ Exit_Time          : Factor w/ 1012 levels "00:00:00","00:01:00",..: 618 556 637 694 770 936 948 590 640 655 ...
 $ Type_of_entry    : Factor w/ 3 levels "Manual","Pass",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ weekday     : Factor w/ 7 levels "Friday","Monday",..: 2 2 2 2 2 2 2 6 6 6 ...
 $ Ticket.Loss: Factor w/ 2 levels "N","Y": 1 1 1 1 1 2 2 1 1 1 ...
 $ Duration  : Factor w/ 501 levels "00:01:00","00:02:00",..: 223 142 139 96 159 188 199 192 132 101 ...

I am using below function:
W <- aggregate(Duration ~ Gates, data=parking, FUN=mean)

But getting below error:

Warning messages: 1: In mean.default(X[[i]], ...) :   argument is not
  numeric or logical: returning NA

A: Duration is a factor of strings that look like time durations, "00:01:00", etc.
The chron package works with character strings such as this.
library(chron)
aggregate(chron(times=Duration) ~ Gates, data=parking, FUN=mean)

This will give the average time for each level in Gates.
See also convert character to time in R

A: If the OP's dataset is infact time column, we can use as.POSIXct to convert it to 'DateTime' class
parking$Duration <- as.POSIXct(parking$Duration, format = "%H:%M:%S")
transform(aggregate(Duration ~ Gates, data = parking, FUN = mean),
                               Duration = sub("\\S+\\s+", "", Duration))
#  Gates Duration
#1    B6 11:08:34
#2    B9 11:07:31
#3    I1 11:07:10

NOTE: No external packages used.
data
set.seed(24)
parking <- data.frame(Gates = sample(c("B6", "B9", "I1"), 20, replace=TRUE),
  Duration = format(seq(Sys.time(), length.out=20, by = "1 min") , "%H:%M:%S"))


text:
Q: DISTINCT with two array_agg (or one array_agg with tuple inside)? I've got the following query:
SELECT DISTINCT ON (ps.p)
  m.groundtruth, ps.p, ARRAY_AGG(m.anchor_id), ARRAY_AGG(m.id)
FROM
  measurement m
JOIN
  (SELECT unnest(point_array) AS p) AS ps
  ON ST_DWithin(ps.p, m.groundtruth, distance)
GROUP BY ps.p, m.groundtruth
ORDER BY ps.p, RANDOM()

The output looks like that:
groundtruth | p           | anchor_array | id_array
------------------------------------------------------
G1          | P1          | {1,3,3,3,4}  | {1,2,3,4,5}
G2          | P1          | {1,5,7}      | {6,7,8}
G1          | P2          | {1,3,3,3,4}  | {1,2,3,4,5}

Alternative query:
SELECT DISTINCT ON (ps.p)
  m.groundtruth, ps.p, ARRAY_AGG(row(m.anchor_id, m.id))
...

Output:
groundtruth | p           | combined_array
-----------------------------------------------------------
G1          | P1          | {(1,1),(3,2),(3,3),(3,4),(4,5)}
G2          | P1          | {(1,6),(5,7),(7,8)}
G1          | P2          | {(1,1),(3,2),(3,3),(3,4),(4,5)}

What I want to achieve:

*

*Getting rid of duplicate entries inside anchor_array

*And for each deleted item: Delete the item from the id_array with the same index

Or for the alternative query and output:

*

*Make each tuple distinct concerning the first entry of the tuple
What the result should look like:
groundtruth | p           | anchor_array | id_array
------------------------------------------------------
G1          | P1          | {1,3,4}      | {1,2,5}
G2          | P1          | {1,5,7}      | {6,7,8}
G1          | P2          | {1,3,4}      | {1,2,5}

Or for the alternative query and output:
groundtruth | p           | combined_array
-----------------------------------------------------------
G1          | P1          | {(1,1),(3,2),(4,5)}
G2          | P1          | {(1,6),(5,7),(7,8)}
G1          | P2          | {(1,1),(3,2),(4,5)}

P.S. I have ignored the randomization part in the example output for better overview.

Real result set:
p                                           ; groundtruth                                ; ids
---------------------------------------------------------------------------------------------
"0101000000EE7C3F355EF24F4019390B7BDA011940";"010100000094F6065F98E44F40A930B610E4A01B40";"{"(29,250)","(30,251)","(31,241)","(32,263)","(33,243)","(34,264)","(35,277)"}"
"0101000000EE7C3F355EF24F40809F71E140681940";"010100000094F6065F98E44F40A930B610E4A01B40";"{"(29,250)","(30,251)","(31,257)","(32,276)","(33,272)","(34,264)","(35,249)"}"
"0101000000EE7C3F355EF24F40E605D847A7CE1940";"0101000000EE7C3F355EF24F4019390B7BDA011940";"{"(30,194)","(31,181)","(32,168)","(33,124)","(34,141)","(35,4)"}"
"0101000000EE7C3F355EF24F404C6C3EAE0D351A40";"010100000014D044D8F0DC4F4073BA2C2636DF1C40";"{"(30,281)","(31,278)","(32,297)","(33,284)","(34,294)","(35,303)"}"
"0101000000EE7C3F355EF24F40B3D2A414749B1A40";"0101000000DE9387855AEB4F4062670A9DD7581A40";"{"(30,235)","(31,214)","(32,220)","(33,221)","(34,217)","(35,232)"}"
"0101000000EE7C3F355EF24F4019390B7BDA011B40";"0101000000AF94658863D54F40A7E8482EFF211E40";"{"(27,316)","(31,329)","(32,334)","(33,340)","(34,327)","(35,324)"}"
"0101000000EE7C3F355EF24F40809F71E140681B40";"0101000000DE9387855AEB4F4062670A9DD7581A40";"{"(30,224)","(31,210)","(32,220)","(33,230)","(34,226)","(35,213)"}"
"0101000000EE7C3F355EF24F40E605D847A7CE1B40";"010100000014D044D8F0DC4F4073BA2C2636DF1C40";"{"(30,281)","(31,304)","(32,288)","(33,293)","(34,306)","(35,295)"}"
"0101000000EE7C3F355EF24F404C6C3EAE0D351C40";"010100000094F6065F98E44F40A930B610E4A01B40";"{"(29,250)","(30,256)","(31,257)","(32,271)","(33,254)","(34,260)","(35,277)"}"
"0101000000EE7C3F355EF24F4019390B7BDA011D40";"010100000007F0164850C44F405F46B1DCD24A2040";"{"(31,383)","(32,409)","(33,390)","(34,411)","(35,407)"}"

A: Similar to what I answered at your preceding question, just with ARRAY of rows like you suggested and shorter positional notation:
SELECT DISTINCT ON (1)
       p, groundtruth, array_agg(ROW(anchor_id, id)) AS ids
FROM (
   SELECT DISTINCT ON (1, 2, 3)
          ps.p, m.groundtruth, m.anchor_id, m.id
   FROM  (SELECT unnest(point_array) AS p) AS ps
   JOIN   measurement m ON ST_DWithin(ps.p, m.groundtruth, distance)
   ORDER  BY 1, 2, 3, random()
   ) x
GROUP  BY 1, 2
ORDER  BY 1, random();

But I like the other version with a 2-dimensional array better.


text:
Q: Execute the code inside onDraw() only after the click in view I have a class that extends a view.
This class is called in xml to build my view. Now the view call the onDraw automatically the onDraw function on loaded. But how i can do what is do on onDraw() function only after i click in that view?? In conclusion i need to execute the code inside onDraw() only after the click in view.
DrawView.java:
public class DrawView extends View {
    Paint mPaint = new Paint();
    Context context;

    public DrawView(Context context, AttributeSet attrs){
        super(context, attrs);
        this.context = context;
        // setWillNotDraw(true);

    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        mPaint.setColor(Color.MAGENTA);
        canvas.drawRect((float) (getWidth()*0.3), (float) (getHeight()*0.3), getWidth(), getHeight(), mPaint);

main.xml:
<LinearLayout
      android:orientation="vertical"
      android:layout_height="fill_parent"
      android:layout_width="0dip"
      android:layout_weight="1">
      <com.example.sliding.DrawView
            android:id="@+id/tv_listRow_item1"
            android:tag="tv_listRow_item1_1"
            android:layout_height="0dip"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:width="100dip"
            android:height="30dip"
            android:background="@drawable/textview_listrow_border"/>
</LinearLayout>

main.java:
 ((DrawView)v.findViewById(R.id.tv_listRow_item1)).setOnClickListener(listener);
  private View.OnClickListener listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
    }
}

Any suggestions? Thanks for your time and attention.

A: Try overriding the
    public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// your actions here
}
}

then call invalidate() function, which will set a flag to call the onDraw() of your view.


text:
Q: Django - cannot deploy with mod_wsgi in virtualenv with python 3.4 i've been trying for two days and still can't deploy my django proj to apache + mod_wsgi-express in virtualenv with python3.4. I'm getting Internal Server Error on the web browser. please help~~~
note: i am running mod_wsgi with operating system Apache 2.4.10
in terminal, i ran mod_wsgi-express with the following command:
(env3.4)root@X110:/var/www/html/example.com/mysite# mod_wsgi-express start-server --host 192.168.1.110 --port 8000 --working-directory mysite --application-type module mysite.wsgi --user developer --group developer
Server URL         : http://192.168.1.110:8000/
Server Root        : /tmp/mod_wsgi-192.168.1.110:8000:0
Server Conf        : /tmp/mod_wsgi-192.168.1.110:8000:0/httpd.conf
Error Log File     : /tmp/mod_wsgi-192.168.1.110:8000:0/error_log (warn)
Request Capacity   : 5 (1 process * 5 threads)
Request Timeout    : 60 (seconds)
Startup Timeout    : 15 (seconds)
Queue Backlog      : 100 (connections)
Queue Timeout      : 45 (seconds)
Server Capacity    : 20 (event/worker), 20 (prefork)
Server Backlog     : 500 (connections)
Locale Setting     : C.UTF-8

error log:
[Thu Nov 10 01:05:11.682936 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] mod_wsgi (pid=4692): Target WSGI script '/tmp/mod_wsgi-192.168.1.110:8000:0/handler.wsgi' cannot be loaded as Python module.
[Thu Nov 10 01:05:11.683051 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] mod_wsgi (pid=4692): Exception occurred processing WSGI script '/tmp/mod_wsgi-192.168.1.110:8000:0/handler.wsgi'.
[Thu Nov 10 01:05:11.683109 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] Traceback (most recent call last):
[Thu Nov 10 01:05:11.683194 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805]   File "/tmp/mod_wsgi-192.168.1.110:8000:0/handler.wsgi", line 94, in <module>
[Thu Nov 10 01:05:11.683213 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805]     recorder_directory=recorder_directory)
[Thu Nov 10 01:05:11.683266 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805]   File "/var/www/html/example.com/env3.4/lib/python3.4/site-packages/mod_wsgi/server/__init__.py", line 1335, in __init__
[Thu Nov 10 01:05:11.683290 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805]     __import__(entry_point)
[Thu Nov 10 01:05:11.683323 2016] [wsgi:error] [pid 4692:tid 139781773657856] [remote 192.168.1.10:54805] ImportError: No module named 'mysite'

============================================================
below are my settings.
operating system
os: debian 8.6.0
ip address: 192.168.1.110
apt-get install build-essential
apt-get install libssl-dev
apt-get install apache2-threaded-dev
apt-get install python-dev
apt-get install libmysqlclient-dev
apt-get install python-virtualenv

created a virtualenv with python 3.4
virtualenv env3.4 --python=python3.4

in the virtualenv, i've installed the following with pip:
pip install django #django 1.10.3
pip install -U setuptools
pip install mysqlclient
pip install djangorestframework
pip install django-filter
pip install httpie
pip install coreapi (to include api schema)
pip install coreapi-cli (client)
pip install mod_wsgi

project structure:
/var/www/html/example.com/mysite
                           +mysite
                               settings.py
                               urls.py
                               wsgi.py
                           +app1
                           +app2

settings.py
ALLOWED_HOSTS = ['192.168.1.110']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    .....
    'rest_framework',
    'mod_wsgi.server',
]
....
WSGI_APPLICATION = 'mysite.wsgi.application'

wsgi.py
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()


text:
Q: Elastic search, Filter is not working using java.sql.Time object Even though Time format in query and data are same still ES is not giving any result, Can you please check and correct me any thing wrong in dealing with java.sql.Time objects from Java
Query sample is given below :
 GET /regularride/regularride/_search
    {
      "size": 5000,
      "query": {
        "bool": {
          "filter": [
            {
              "range": {
                "monday": {
                  "lt": "10:36:00 AM"
                }
              }
            },
            {
              "range": {
                "monday": {
                  "gt": "08:36:00 AM"
                }
              }
            }
          ]
        }
      }
    }

and available data in database is shown below :
{"took":1,"timed_out":false,"_shards":{"total":3,"successful":3,"skipped":0,"failed":0},"hits":{"total":45,"max_score":1,"hits":[{"_index":"regularride","_type":"regularride","_id":"26201","_score":1,"_source":{"vehicleNumber":"5656","vehicleModel":"Hatch Back","farePerKm":4,"availableSeats":4,"noOfPassengers":0,"vehicleType":"Car","cumOverlapDist":0,"riderHasHelmet":false,"fromDate":"Nov 28, 2018, 12:00:51 AM","processedDate":"Dec 11, 2018, 12:01:51 AM","duration":51,"monday":"10:06:00 AM","tuesday":"10:06:00 AM","wednesday":"10:06:00 AM","thursday":"10:06:00 AM","friday":"10:06:00 AM","dateType":"ALL"}},{"_index":"regularride","_type":"regularride","_id":"26606","_score":1,"_source":{"vehicleNumber":"cufufu","vehicleModel":"Hatch Back","farePerKm":4,"availableSeats":4,"noOfPassengers":0,"vehicleType":"Car","cumOverlapDist":0,"riderHasHelmet":false,"fromDate":"Nov 29, 2018, 12:00:00 AM","processedDate":"Dec 11, 2018, 12:01:00 AM","duration":24,"monday":"07:07:00 AM","tuesday":"07:07:00 AM","wednesday":"07:07:00 AM","thursday":"07:07:00 AM","friday":"07:07:00 AM"}}]}}


text:
Q: SQLException : Missing defines in servlet I am working on a web application using jsp and servlet using oracle.jdbc.OracleDriver.This code,working fine on my PC,but when trying to deploy build of application on other server,i am getting Exception like this.
java.sql.SQLException: Missing defines
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:158)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:305)
at oracle.jdbc.driver.OracleStatement.prepareAccessors(OracleStatement.java:793)
at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:235)
at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:95)
at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1947)
at org.apache.tomcat.dbcp.dbcp.DelegatingCallableStatement.getObject(DelegatingCallableStatement.java:143)
at cwep.Login.processRequest(Login.java:127)
at cwep.Login.doPost(Login.java:198)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Unknown Source)

After debugging my application,i found that when I am calling database(Oracle 10g) procedure on server side and getting cursor using callableStatement.registerOutParameter(1,OracleTypes.CURSOR), I am getting  above Exception at
    callableStatement.execute(); statement.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
static String CNPOOL = "cnpool";//Getting CNPOOL correctly for database connection
 CallableStatement cs = null;
 static DataSource dataSource;//Declared as global
        response.setContentType("text/html;charset=UTF-8");

            PrintWriter out = response.getWriter();
            CallableStatement cs = null;
            String str = conectionPool;
            System.out.println(str);
            try {
            InitialContext initContext = new InitialContext();
            Context context = (Context) initContext.lookup("java:/comp/env");
            dataSource = (DataSource) context.lookup(str);
            System.out.println(" CxN Pool " + str);
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            ecode = Integer.parseInt(username);
            System.out.println(" eCode " + ecode);
            try {
                con = ConnectionBean.getConnection(dataSource);
                System.out.println(" CxN " + con.toString());
            } catch (Exception e) {
                System.out.println(" Opening the Cxn 1st Time" + e);
            }
            if(con!=null)
            {
            System.out.println(" Before Calling proc_user_login " + ecode);
            cs = con.prepareCall("{call proc_user_login(?,?,?,?,?)}");
            cs.setInt(1, empcode);
            cs.setString(2, password);
            cs.registerOutParameter(3, Types.NUMERIC);
            cs.registerOutParameter(4, Types.NUMERIC);
            cs.registerOutParameter(5, Types.VARCHAR);
            try {
                cs.execute();
            } catch (Exception e) {
                System.out.println("--------------------After executing first proc----------------------- ");
            }
            int message = cs.getInt(3);

            if (message == 0) {

                cs = con.prepareCall("{call proc_get_XXXlist(?,?)}");
                cs.setInt(1, empcode);
                cs.registerOutParameter(2, OracleTypes.CURSOR);
                try {
                     System.out.println("Before executing XXXList proc ");
                    cs.execute();      //GETTING EXCEPTION AT THIS STATEMENT
                    System.out.println("After executing XXXList");
                } catch (Exception e) {
                    System.out.println("exception in After executing secod proc ");
                }
                ResultSet rset = (ResultSet) cs.getObject(2);
                Vector v1 = new Vector();
                Vector v2 = new Vector();
                Vector v3 = new Vector();
                while (rset.next()) {
                    v1.addElement(rset.getString(1));
                    v2.addElement(rset.getString(2));
                    v3.addElement(rset.getString(3));
                }
                //rset.last();
                String[] str1 = new String[v1.size()];
                String[] str2 = new String[v2.size()];
                String[] str3 = new String[v3.size()];
                v1.copyInto(str1);
                v2.copyInto(str2);
                v3.copyInto(str3);

                request.setAttribute("ecode", Integer.toString(ecode));
                request.setAttribute("clientid", str1);
                request.setAttribute("constring", str2);
                request.setAttribute("URL", str3);
                RequestDispatcher rd = request.getRequestDispatcher("XXX.jsp");

                rd.forward(request, response);
                //response.sendRedirect("XXX.jsp");
            } else {
                response.sendRedirect("index.jsp?val=" + message);
            }

            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("EEE---" + e);
            Utility.log("FinalExceptionToServlet.namelookup:", e.toString(), "SERVER", "E");
        }
    }

In this code,First database login_usr procedure execute properly,but when trying to execute 2nd procedure,which returns a cursor as outparameter,i'm getting above exception.If same code working fine on my PC,then why it throws exception when trying to execute callablestatement after Serverside deployment.Here I'm using Ojdbc14.jar and classes12.jar.Is there is any .jar missmatch..???
Thanks in advance.

A: As you have mentioned that the code was running earlier, Here the culprit could be OracleTypes. As its abstract class you need correct and concrete implementation of it which is your Driver.

*

*Verify  the version of the JDBC driver and the type of JDBC driver (Thin or OCI) you

*Download new jar from oracle site or from here.

Also, try using oracle.jdbc.OracleTypes before looking for drivers.
e.g. cn.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);


text:
Q: Bash script to execute Java console application I have a Java console application which accepts the user input and performs action based on the input. Below is the sample:
**Payout Table          Multiplier**
=======================================
Royal Flush     |       250
Straight Flush  |       50
Four of a Kind  |       25
Full House      |       9
Flush           |       6
Straight        |       5
Three of a Kind |       3
Two Pairs       |       2
Royal Pair      |       1

-----------------------------------
Balance: $500
Enter bet:

I have to enter the amount to bet with:
Enter bet: 300

HAND: [K Spades, J Spades, 10 Clubs, 9 Diamonds, J Hearts]
Enter positions of cards to keep (e.g. 1 4 5):

Enter positions of cards to keep (e.g. 1 4 5):
3

Held Cards: [10 Clubs]
NEW HAND: [10 Clubs, 5 Clubs, 10 Hearts, A Diamonds, 10 Diamonds]

**Three of a Kind**

Your balance: $1400
One more game (y or n)?

y

I just need help with an idea of a bash script to automate this manual process.

A: Depending on the complexity of the different cases that you would like to enter, you might be able to use expect:
https://linux.die.net/man/1/expect
Example for a similar problem:
Use Expect in a Bash script to provide a password to an SSH command
Example:
#!/usr/bin/expect
eval spawn java Main

# May need to adjust prompts to match better
interact -o -nobuffer -re "Enter bet: " return
send "300\r"
interact -o -nobuffer -re "Enter positions of cards to keep (e.g. 1 4 5):\r" return
send "3\r"
interact -o -nobuffer -re "One more game (y or n)?" return
send "y\r"
interact


text:
Q: Changing all variables to specific naming convention (lowercase) Is there any automated way to change all variables (alongside there references) in file to specific convention (lower case) without changing the whole line to lowercase?
I'm using VScode IDE but it doesn't seem to help, it only helps in changing them one by one!
In my case
local Device_MacAddress_f =     ... >> local device_macAddress_f
local Device_Signalstate_f=     ... >> local device_signalstate_f
local Device_Controller_f =     ...
local Device_Timesinceboot=     ...
local Device_Ipaddress_f =      ...
local Device_Subnetmask_f =     ...
local Device_Gateway_f =        ...
local Device_Netbiosname_f=     ...
local Device_Dhcpstate_f =      ...
local Device_Fwversion_f =      ...
local Device_Kernalversion=     ...
local Device_Controllertype_f = ...

A: Enable regex search .*
Search: local Device_([A-Z])
Replace: local device_\l$1


text:
Q: How to calculate the Laplace transform of $\sum_{k=0}^{+\infty}(-1)^{k}\delta (t-k)$? On my midterm, I had the following question:

Calculate the Laplace transform of $$\sum_{k=0}^{+\infty}(-1)^{k}\delta (t-k)$$

I was wondering how I should calculate it. I know that the transform would be $\dfrac{e^s}{1+e^s}$, and we were given the hint that we may need to use
$$\sum_{k=0}^{+\infty} a^{k} = \dfrac{1}{1-a}$$
for $|a|<1$. My original thought was to write out the sum, which would become
$$\sum_{k=0}^{+\infty}(-1)^{k}\delta (t-k) = [\delta(t)-\delta(t-1)] + [\delta(t-2)+\delta(t-3)]+\cdots$$
Then I know the Laplace transform of the pairs would be
$$[1-e^{-s}]+[e^{-2s}+e^{-3s}]+\cdots$$
and then group the positive terms ($\sum_{k=0}^{+\infty}e^{-2ks}$) and the negative terms ($-\sum_{k=0}^{+\infty}e^{-(2k+1)s}$) and use the hint to get the final result, but I am unable to get the correct answer. I was wondering if my approach is correct or perhaps there is another way to calculate the Laplace transform?
Thank you in advance.

A: $$
\mathcal{L} \left\{ \sum_{k=0}^{+\infty}(-1)^{k}\delta (t-k) \right\}
= \int_0^\infty \left( \sum_{k=0}^{+\infty}(-1)^{k}\delta (t-k) \right) e^{-st} \, dt
= \sum_{k=0}^{+\infty}(-1)^{k} \int_0^\infty \delta (t-k) e^{-st} \, dt \\
= \sum_{k=0}^{+\infty}(-1)^{k} e^{-ks}
= \sum_{k=0}^{+\infty}(-e^{-s})^{k}
= \frac{1}{1-\left(-e^{-s}\right)}
= \frac{1}{1+e^{-s}}
= \frac{e^s}{e^s+1}
$$


text:
Q: Laravel i can't show only user-created objects checking by user_email, like a shopping cart different for every user I'm trying to create a particular online address book where each user can register and create his contacts.
When the contacts are created, the "user_email" and "session_id" of the user who created it are saved in "students" tab.
This is the structure of the users table
This is the structure of the students table
This is the function "addStudent" present in "StudetsController" (Don't pay attention to "ICF Dropdown")
<?php

namespace App\Http\Controllers;

use App\Student;
use App\Product;
use Session;
use User;
use Auth;
use DB;
use Illuminate\Http\Request;
use function GuzzleHttp\Promise\all;

class StudentsController extends Controller
{

public function addStudent(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            $student = new Student();
            $student->student_sex = $data['student_sex'];
            $student->student_name = $data['student_name'];
            $student->student_surname = $data['student_surname'];
            $student->student_birth = $data['student_birth'];
            $student->codice_icf = $data['codice_icf'];
            if(!empty($data['description'])){
                $student->description = $data['description'];
            }else{
                $student->description = '';
            }
            $student->user_email = $data['user_email']=Auth::user()->email;
            if(empty($session_id)) {
                $student->session_id = $data['session_id']= str_random(40);
            }else{
                $student->session_id = Student::get('session_id');
            }
            $student->save();
            return redirect('/')->with('flash_message_success','Lo studente è stato creato con successo!');
        }

        //ICF drop down start
        $products = Product::get();
        $products_dropdown = "<option selected disabled>Codice ICF</option>";
        foreach($products as $pro){
            $products_dropdown .= "<option value='".$pro->product_name."'>".$pro->product_name."</option>";
        }
        //Categories drop down ends

        return view('students.add_student')->with(compact('products_dropdown'));
    }

As you can see the students are created and they save the email of who created them
Now on the index page, i would like the logged in user to see only his students.
First of all i create a foreach loop for students in index.blade.php
@foreach($students as $student)

                    @if($student->student_sex == "M")

                    @else

                    @endif

 {{$student->student_name}} {{$student->student_surname}}

{{$student->codice_icf}}

            @endforeach

Where "$students" is defined in "IndexController" like this
<?php

namespace App\Http\Controllers;

use App\Category;
use App\Product;
use App\Student;
use Session;
use Illuminate\Http\Request;

class IndexController extends Controller
{

    public function index(){
        $students = Student::get();
        return view('index')->with(compact('students'));
    }
}

And the $student function in "StudentsController" like this:
<?php

namespace App\Http\Controllers;

use App\Student;
use App\Product;
use Session;
use User;
use Auth;
use DB;
use Illuminate\Http\Request;
use function GuzzleHttp\Promise\all;

class StudentsController extends Controller
{

 public function addStudent(Request $request){...}

 public function student(){
        if(Auth::check()){
            $user_email = Auth::user()->email;
            $students = DB::table('students')->where(['user_email'=>$user_email])->get();
        }
        return redirect('/')->with(compact('students'));
    }

As you can see the students appear on the index page, but if i log in with a different user they stay the same
This is my users controller, if you need the login function
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use App\Student;
use Session;
use DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class UsersController extends Controller
{
    public function userRegister(){
        return view('users.register');
    }

    public function userLogin(){
        return view('users.login');
    }

    public function login(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            if(Auth::attempt(['email'=>$data['email'],'password'=>$data['password']])){
                $userStatus = User::where('email',$data['email'])->first();
                if($userStatus->status == 0){
                    return redirect()->back()->with('flash_message_error', 'Il tuo  account non è attivo! Conferma la tua email per attivarlo.');
                }
                Session::put('frontSession',$data['email']);
                return redirect('/');
            }else{
                return redirect()->back()->with('flash_message_error', 'Email o Password errate!');
            }
        }
    }

    public function register(Request $request){
        if ($request->isMethod('post')) {
            $data = $request->all();
            //Check if User Already exist
            $usersCount = User::where('email', $data['email'])->count();
            if ($usersCount > 0) {
                return redirect()->back()->with('flash_message_error', 'Email già registrata!');
            } else {
                $user = new User;
                $user->name = $data['name'];
                $user->email = $data['email'];
                $user->password = bcrypt($data['password']);
                $user->save();

                // Send Confirmation Email
                $email = $data['email'];
                $messageData = ['email' => $data['email'],'name'=>$data['name'],'code'=>base64_encode($data['email'])];
                Mail::send('emails.confirmation',$messageData, function ($message) use($email){
                    $message->to($email)->subject('Conferma Account');
                });

                return redirect('/login')->with('flash_message_success', 'Perfavore conferma la tua email per attivare il tuo account!');

            }
        }
    }

    public function logout(){
        Auth::logout();
        Session::forget('frontSession');
        return redirect('/');
    }

    public function confirmAccount($email){
        $email = base64_decode($email);
        $userCount = User::where('email', $email)->count();
        if ($userCount > 0) {
            $userDetails = User::where('email', $email)->first();
            if ($userDetails->status == 1) {
                return redirect('/login')->with('flash_message_success', 'Il tuo account è già attivo! Effettua il login.');
            } else {
                User::where('email', $email)->update(['status' => 1]);
                //Welcome Email
                $messageData = ['email' => $email,'name'=>$userDetails->name];
                Mail::send('emails.welcome',$messageData, function ($message) use($email){
                    $message->to($email)->subject('Benvenuto!');
                });
                return redirect('/login')->with('flash_message_success', 'Il tuo account è stato attivato! Effettua il login adesso.');
            }
        }else{
            abort(404);
        }
    }

    public function checkEmail(Request $request)
    {
        $data = $request->all();
        $usersCount = User::where('email', $data['email'])->count();
        if ($usersCount > 0) {
            echo "false";
        } else {
            echo "true"; die;
        }
    }
}

How can I see for each different user only the students created by him using his email as a control field?
Thanks in advance!

A: It looks like you are doing a redirect to your IndexController
return redirect('/')->with(compact('students'));

You cannot redirect and pass some variable

A: Thanks to Oleg Andreyev advice, i solved the problem by removing the function "student" in "StudentsController", so i delete this line:
 public function student(){
    if(Auth::check()){
        $user_email = Auth::user()->email;
        $students = DB::table('students')->where(['user_email'=>$user_email])->get();
    }
    return redirect('/')->with(compact('students'));
}

And i changed the "index" function to "IndexController" from this:
public function index(){
    $students = Student::get();
    return view('index')->with(compact('students'));
}

To this one:
public function index(){
    $students = Student::get();
    if(Auth::check()){
        $user_email = Auth::user()->email;
        $students = DB::table('students')->where(['user_email'=>$user_email])->get();
    }
    return view('index')->with(compact('students'));
}

And now i can see the students related to the email of the user who created them!


text:
Q: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claimtrc' in 'having clause' I'm running into a weird problem when using laravel eloquent and I can't find a way to solve it.
I'm running laravel 5.6
The error I'm getting is
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'claimtrc' in 'having clause' (SQL: select count(*) as aggregate from `claims` where `claims`.`id` not in (select `claim_id` from `claim_tracking` where `claim_tracking`.`claim_id` = claims.id or `claim_tracking`.`type` = Finished or `claim_tracking`.`type` = Brake) group by `claims`.`id` having `claimtrc` >= 1)

The code I'm running is:
$claimsPostponed = Claim::select(DB::raw('*, (SELECT count(*) FROM claim_tracking WHERE claim_tracking.claim_id=claims.id) as claimtrc'))
            ->wherenotin('claims.id', function ($query) {
                $query->select('claim_id')
                    ->from('claim_tracking')
                    ->where('claim_tracking.claim_id', '=', 'claims.id')
                    ->orwhere('claim_tracking.type', 'Finished')
                    ->orwhere('claim_tracking.type', 'Brake');
            })
            ->groupBy('claims.id')
            ->having('claimtrc', '>=', 1)->count();

It works fine like this and I can get the count:
$claimsPostponed = Claim::select(DB::raw('*, (SELECT count(*) FROM claim_tracking WHERE claim_tracking.claim_id=claims.id) as claimtrc'))
            ->wherenotin('claims.id', function ($query) {
                $query->select('claim_id')
                    ->from('claim_tracking')
                    ->where('claim_tracking.claim_id', '=', 'claims.id')
                    ->orwhere('claim_tracking.type', 'Finished')
                    ->orwhere('claim_tracking.type', 'Brake');
            })
            ->groupBy('claims.id')
            ->having('claimtrc', '>=', 1)->get();
        $claimsPostponed = count($claimsPostponed);

But I don't think this way is efficient because it's loading all the results into an array then counting the array.

A: Why dont you try WhereRaw instead of Having from a Select
Something like this:
    $claimsPostponed = Claim::wherenotin('claims.id', function ($query) {
                    $query->select('claim_id')
                        ->from('claim_tracking')
                        ->where('claim_tracking.claim_id', '=', 'claims.id')
                        ->orwhere('claim_tracking.type', 'Finished')
                        ->orwhere('claim_tracking.type', 'Brake');
                })
                ->WhereRaw("(SELECT count(*) FROM claim_tracking WHERE claim_tracking.claim_id=claims.id) >= 1")
                ->groupBy('claims.id')
                ->count();

You can try something like this and let me know if that works for you.
Also keep in mind you dont need the Select, since Count will only do "SELECT COUNT(*)" anyway
Other aproach could be using Joins or WhereHas could be even better.
Asuming claim_tracking is a relation, should be something like this:
    $claimsPostponed = Claim::select('*')
                ->whereHas('claim_tracking',function($q){
                    $q->whereIn('type', ['Finished', 'Brake']);
                })
                ->WhereRaw("(SELECT count(*) FROM claim_tracking WHERE claim_tracking.claim_id=claims.id) >= 1")
                ->groupBy('claims.id')
                ->count();

A: I think it may be work
$claimsPostponed = Claim::select(DB::raw('*, (SELECT count(*) as claimtrc FROM
claim_tracking WHERE claim_tracking.claim_id=claims.id)'))
            ->wherenotin('claims.id', function ($query) {
                $query->select('claim_id')
                    ->from('claim_tracking')
                    ->where('claim_tracking.claim_id', '=', 'claims.id')
                    ->orwhere('claim_tracking.type', 'Finished')
                    ->orwhere('claim_tracking.type', 'Brake');
            })
            ->groupBy('claims.id')
            ->having('claimtrc', '>=', 1)->count();


text:
Q: Use Java Stream to filter list based on values from second list I'm trying to Filter a list of objects based on values from second list.
List A:
[
   {
      "id":"12345",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   },
   {
      "id":"34567",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   },
   {
      "id":"56789",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   }
]

List B:
["12345", "56789"]

Now i want to remove the item of List A with IDs available in List B.
Im trying to use JavaStream but can't understand the syntax and i'm trying ForEach loop but its not working properly.
I've done something similar in Swift as following.
            if let allModOptions = allModifersList?.first?.options {
                let excludedIDs = pObj?.excluded_ids
                if excludedIDs!.count > 0 {
                   let allowedOptions = allModOptions
                   ->>>>    **.filter{ !excludedIDs!.contains($0.id!)}** <<<<-
                        .filter{c in c.deleted_at == nil}.sorted {
                        $0.index ?? 0 < $1.index ?? 0
                       }

                    allModsList?.first?.options = allowedOptions

                }
               modisList.append(contentsOf: allModsList!)
            }

Any help is appreciated

A: *

*If I understand correctly, you are given the following information:

*

*a class with 3 fields: id, name, description. Lets call this class Item.

*a list of ids of Items which should be removed from List A. Lets call this list, idsOfItemsToRemove.

*a list of all Items to evaluate

*an expected list; a list of Items which do not contain any value present in idsOfItemsToRemove.

*If the above assumptions are true, then the code snippet below should be indicative of what you are seeking to do.

@Test
public void test() {
    // given
    Integer idOfItemToBeRemoved1 = 12345;
    Integer idOfItemToBeRemoved2 = 56789;
    Item itemExpectedToBeDeleted1 = new Item(idOfItemToBeRemoved1, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeDeleted2 = new Item(idOfItemToBeRemoved2, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeRetained1 = new Item(34567, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeRetained2 = new Item(98756, "nameOfItem", "descriptionOfItem");

    List<Integer> idsOfItemsToRemove = Arrays.asList(
            idOfItemToBeRemoved1,
            idOfItemToBeRemoved2);

    List<Item> listOfItems = Arrays.asList(
            itemExpectedToBeDeleted1,
            itemExpectedToBeDeleted2,
            itemExpectedToBeRetained1,
            itemExpectedToBeRetained2);

    List<Item> expectedList = Arrays.asList(
            itemExpectedToBeRetained1,
            itemExpectedToBeRetained2);

    // when
    List<Item> actualList = listOfItems
            .stream()
            .filter(item -> !idsOfItemsToRemove.contains(item.getId()))
            .collect(Collectors.toList());

    // then
    Assert.assertEquals(expectedList, actualList);
}

This code has also been pushed to Github.

https://raw.githubusercontent.com/Git-Leon/stackoverflow-answers/master/javastreamfilter/

A: you should use filter on main collection and !contains on List collection
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Scratch {
    static class Element {
        int id;
        String name;
        String description;

        public Element(int id, String name, String description) {
            this.id = id;
            this.name = name;
            this.description = description;
        }

        @Override
        public String toString() {
            return "Element{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", description='" + description + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        List<Element> elements = new ArrayList<>(Arrays.asList(
           new Element(12345, "nameofitem", "asdfafd"),
           new Element(34567, "nameofitem", "asdfafd"),
           new Element(56789, "nameofitem", "asdfafd")
        ));
        List<Integer> filterNot = new ArrayList<>(Arrays.asList(12345, 56789));
        List<Element> result = elements.stream().filter(item -> !filterNot.contains(item.id)).collect(Collectors.toList());

        result.forEach(System.out::println);
    }

}


text:
Q: Definition of matrix transformation I really understand the definition of linear transformation, but I'm not sure about the definition of matrix transformation. Could it be that a matrix transformation is defined as a linear transformation that is defined by:
$$
T(x)= Ax
$$
where $A$ is a matrix over some field?

A: In fact, any linear transformation $\mathscr{A}: V \to V$, where $V$ is an arbitrary vector space over a field $F$ has its "matrix transformation" representation. In detail, suppose $\dim(V) = n$, then we can choose a fixed basis $\{v_1, \ldots, v_n\}$ of $V$. Since the transformation is linear and $\{v_1, \ldots, v_n\}$ is a basis of $V$, it can be shown that for each $i \in \{1, \ldots, n\}$, there exist $a_{i1}, \ldots, a_{in} \in F$, such that
$$\mathscr{A}v_i = a_{i1}v_1 + \cdots + a_{in}v_n.$$
Define matrix $A$ as:
$$A = \begin{pmatrix}
a_{11} & \cdots & a_{1n} \\
\vdots & \ddots & \vdots \\
a_{n1} & \cdots & a_{nn}
\end{pmatrix}$$
Then for any $v \in V$, suppose its coordinate with respect to $\{v_1, \ldots, v_n\}$ is $x = (x_{1}, \ldots, x_{n})^T$, then it is easily seen that
$$\mathscr{A}v = x_1\mathscr{A}v_1 + \cdots + x_n\mathscr{A}v_n = (v_1, \ldots, v_n)Ax. \tag{1}$$
From $(1)$ it can be seen that the space of all linear transformations on $V$ and the space of all $n \times n$ matrices are isometric. In this sense "linear transformation" and "matrix transformation" can be treated equally.
Regarding linear transformation and matrix further, it maybe also worth noting that the matrix representations for one linear transformation $\mathscr{A}$ under different bases are similar.


text:
Q: Mathematica: Characters overlap in rotated text There seems to be a problem with rotating text that contains both normal and "script" characters. To illustrate this I've written a short function:
RotatePrint[s_String] :=
  GraphicsRow[Table[
    Graphics[Rotate[Text[Style[s, 50]], j]] // ImageCrop,
    {j, 0, 2 Pi, Pi/4}]]

RotatePrint["Sc"], i.e. with two normal characters, works as expected:

RotatePrint["\[ScriptCapitalS]\[ScriptC]"], i.e. with two "script" characters, works just as well:

RotatePrint["\[ScriptCapitalS]c"], i.e. with a mix of normal and script characters, however, behaves strangely:

What I find especially peculiar is that the overlap does not happen for the rotation angle Pi/2.
Thanks for your help!
Edit1: I know one can work around this by using ImageRotate instead of Rotate but this doesn't solve the problem per se.
Edit2: Since this seems to depend on the operating system and Mathematica version: I use Mathematica v8.0.0.0 on Windows 7 64-bit.

A: In Mathematica 7 on Windows 7 I get this to a lesser degree:

I propose this workaround:
rowPrint[s_String] :=
 GraphicsRow @
  Table[Graphics @ Text @ Rotate[Style[Row @ Characters @ s, 50], j],
   {j, 0, 2 Pi, Pi/4}]

rowPrint["\[ScriptCapitalS]c"]


text:
Q: Weird result difference in calculation with same numbers I have the following code (m_threshold (in interval [0..1]) and binSize (=1000) are constants):
std::vector<std::vector<ResidualEntry>> *bins = new std::vector<std::vector<ResidualEntry>>;
... //filling vector
int n = bins->size(); //is 27779
double a = -(2 * (n * binSize - m_threshold * pointCount)) / ((n * n + n) * binSize);
double a2 = -(2 * (bins->size() * binSize - m_threshold * pointCount)) / ((bins->size() * bins->size() + bins->size()) * binSize);

a and a2 return completely different numbers. a is about 0.02 and a2 is -3.6e-5 which is the correct one
Why does this happen?

A: Thanks to @SirDarius: vector::size() returns a value of type size_type which should normally be an unsigned value, while int is a signed value, making the two lines completely different. After using size_t for initializing n, it all works now.


text:
Q: ACCESS file connection from EXCEL to SharePoint (SQL database) I have an access connection file (.accdb) that allows me to use EXCEL (Office 365) to query a SharePoint Library.  It all works great EXCEPT for new files added to that SharePoint Library.  I can query for and return all data for these new files/entries but cannot get the filename for these new entries for some reason.  Any help would be most appreciated.
Const SQLIMSSHAREPOINTCONNECTION = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\MORGAN\MACROS\IMS_SHAREPOINT_db.accdb"
Sub routine:
Dim i As Long
Dim cn As Object
Dim rs As Object
Dim StrSql As String
Dim thePieces1() As String
Dim thePieces2() As String
Dim theFullFilename As String
Dim theShortFilename As String

StrSql = "SELECT [Name], [ID], [PartNumber(s)], [DateCompleted], [DocumentType], " & _
        "[WorkOrder(s)], [PurchaseOrder(s)], [SalesOrder(s)], [CustomerName(s)], [WorkCenter]" & _
        " FROM [Inspection Reports]"

Set cn = CreateObject("ADODB.Connection")
cn.Open SQLIMSSHAREPOINTCONNECTION
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open StrSql
If Not (rs.BOF And rs.EOF) Then

    i = 1

    On Error Resume Next
    Do While Not rs.EOF

        i = i + 1
        theFullFilename = ""
        theShortFilename = ""
        ReDim thePieces1(10)

        thePieces1 = Split(rs.Fields(0), "#")
        theFullFilename = thePieces1(1)
        thePieces1() = Split(theFullFilename, "/")
        theShortFilename = thePieces1(UBound(thePieces1))

        Range("A" & i).Value = rs.Fields(1)      ' ID
        Range("B" & i).Value = theShortFilename  ' Filename
        Range("C" & i).Value = rs.Fields(2)      ' PartNumber(s)
        Range("D" & i).Value = rs.Fields(3)      ' DateCompleted
        Range("E" & i).Value = rs.Fields(4)      ' DocumentType
        Range("F" & i).Value = rs.Fields(5)      ' WorkOrder(s)
        Range("G" & i).Value = rs.Fields(6)      ' PurchaseOrder(s)
        Range("H" & i).Value = rs.Fields(7)      ' CustomerName
        Range("I" & i).Value = rs.Fields(8)      ' WorkCenter

        rs.MoveNext

    Loop

A: It's not clear to me how your sharepoint access Excel connection works, but your  recordset (rs) probably needs a refresh or requery after you updated the sharepoint data.


text:
Q: MSI GS63 7RD wont start after a beep, but the keyboard light comes in So yes, this is relatively weak compared to my Mac from observing the result of taking it around in my backpack. I know I was forewarned against the durability of the hardware. I couldn't help it because the information was fully recognized only after I experienced a dent in the plastic cover near power button after a single carry-around in a backpack. Plus, this is a much-needed personal laptop with high-speed computing power at affordable price. Now I am overdue for return as well as a warranty for fix.
When I turn it on, I hear a 'beep' and the keyboard light turns in, but the screen remains pitch black.
This model has internal battery, so the common suggestions to detach/attach battery (https://forum-en.msi.com/index.php?topic=288794.0) and then restart with the cord plugged in would have to wait awhile for me to try. In the meantime.. does anyone have explanation or suggestion for this issue?

A: The beep that you hear after starting the Laptop is the result of the Power On Self Test. I could not find the meanings of the beep codes in the manual of the Laptop that I downloaded from the MSI website. But one of the diagrams in the manual showed that it has an AMI BIOS. In AMI BIOS, 1 beep indicates a memory refresh timer error (Source - AMI BIOS POST beep codes). The solution they have stated is to reseat the RAM modules or replace them. If you are comfortable and know how to work with the hardware in a Laptop, you can try to remove the memory modules, clean around the contacts if dust has accumulated and reseat it again to see if that fixes the problem. That is the simplest thing to do according to the beep code.
Although what I stated above is probably the problem according to the beep code, you can connect an external monitor to the laptop to see if it works. This way you can verify if the Laptop screen is defective or not.

A: So I went to the MSI service center, and this model does not provide beep sounds to provide information.
It was merely a noise in the speaker that they weren't able to explain, nor had the professional attitude to search for a reason other than simply state that 'dual booting' could be the reason why.
It nonetheless corrected itself for unknown reason. Powering off in longer time has helped.


text:
Q: Update datapanel when the model is switched I have an application linked with my autodesk account and I also have a panel dashboard that load the data from the current model, the issue is that this panel isnt update when I choose another model into the hub.
Im trying to find the Autodesk.viewing.EVENT that can record this step but I couldnt. All of them have been tryed and whitout success...
Autodesk.Viewing.GEOMETRY_LOADED_EVENT,
Autodesk.Viewing.OBJECT_TREE_CREATED_EVENT,
Autodesk.Viewing.MODEL_ADDED_EVENT...

A: I have got this working. Don't worry about events, it's working fine.
Here are my changes and additions:
PanelBarChart.js(same goes in piechart as well)
loadWithCustomProperty(property) {
    this.propertyToUse = property;
    this.chart.destroy();
    this.drawChart();
}

After creating list in dashboard.js, add the change event:
$('#'+_this._selectcontainer).change(function() {
        console.log($('#'+_this._selectcontainer+' option:selected').text())
        _this._panel.loadWithCustomProperty($('#'+_this._selectcontainer+' option:selected').text())
    });

Here _this._selectcontainer is UUID, because you're adding multiple chards, so id needs to be unique.


text:
Q: How to create an interactive pdf file with javascript? I want to create dynamic pdf files and embed initials and signature to them inside browser. I found pdfkit.org but I need a more comprehensive solution that allows creating functionalities similar to what you see in docusign. Are there solution out there that you can point me to?

A: From farther research, I learned that PDF & Javascript are good friends. The easiest way to achieve manipulating content within a pdf is to convert it to html, add the changes to it and then convert it back to pdf. There are a few different services available that help you with this kind of conversion. Here are a few of those services:

*

*https://cloudconvert.com

*http://www.pdfonline.com/

*https://market.mashape.com/netservice/convert-pdf-to-html


text:
Q: Question about passing hidden state and cell state gradients from the next LSTM cell to the previous in backpropagation As part of an ongoing project, I am writing a machine learning package in .Net, and I am currently working on implementing the LSTM layer. I have been following this very helpful article as I implement the backpropagation.
So far, I have been able to successfully compute the input gradient for a single LSTM cell but I am a bit stumped when dealing with multiple cells.
My unit tests indicate that the gradients are computed correctly for the last cell but are incorrect for each preceding cell. I suspect that this is because I am not correctly passing back either the hidden state or cell state gradients (or both).
It was my understanding that the output of each backward cell is truncated to match the hidden size and then added to the hidden state gradient of the next cell to form the current hidden state gradient. Similarly, the cell state gradient is computed and added to the cell state gradient of the next cell. By next cell, I am referring to the cell ahead of the current one that was just back propagated through.
However, this seems to not be the case - or at least I am not implementing it correctly. Any and all help would be greatly appreciated!
This is what my forward and backward cells look like:
Forward cell:
 public void LSTMForwardCell(Vector<double> currentCellInput, int index)
 {
            Vector<double> previousCellOutput = index > 0 ? HiddenStates[index - 1] : Vector<double>.Build.Dense(_hiddenUnits);
            Vector<double> previousCellState = index > 0 ? CellStates[index - 1] : Vector<double>.Build.Dense(_hiddenUnits);

            List<double> rawData = currentCellInput.ToList();
            rawData.AddRange(previousCellOutput);

            // z_t
            Vector<double> concatData = Vector<double>.Build.DenseOfEnumerable(rawData);

            CellInputs[index] = concatData;

            // forget gate
            ActivationCache[index][(int)LSTMParameter.F] = ActivationGates[index][(int)LSTMParameter.F].ForwardPropagation(
                LSTMGates[(int)LSTMParameter.F].ForwardPropagation(concatData));

            // input gate 1
            ActivationCache[index][(int)LSTMParameter.I] = ActivationGates[index][(int)LSTMParameter.I] .ForwardPropagation(
                LSTMGates[(int)LSTMParameter.I].ForwardPropagation(concatData));

            // input gate 2, c wave
            ActivationCache[index][(int)LSTMParameter.C] = ActivationGates[index][(int)LSTMParameter.C].ForwardPropagation(
                LSTMGates[(int)LSTMParameter.C].ForwardPropagation(concatData));

            // output gate
            ActivationCache[index][(int)LSTMParameter.O] = ActivationGates[index][(int)LSTMParameter.O].ForwardPropagation(
                LSTMGates[(int)LSTMParameter.O].ForwardPropagation(concatData));

            CellStates[index] =
                ActivationCache[index][(int)LSTMParameter.F].PointwiseMultiply(previousCellState) +
                    ActivationCache[index][(int)LSTMParameter.I].PointwiseMultiply(ActivationCache[index][(int)LSTMParameter.C]);

           HiddenStates[index] =
               ActivationCache[index][(int)LSTMParameter.O]
                   .PointwiseMultiply(
                        ActivationGates[index][(int)LSTMParameter.V].ForwardPropagation(CellStates[index]));
}

Backward cell:
public Vector<double> LSTMBackwardCell(Vector<double> previousError, int index)
{
            Vector<double> previousCellState = index > 0 ? CellStates[index - 1] : Vector<double>.Build.Dense(_hiddenUnits);

            Vector<double> hiddenStateGradient = previousError + _nextHiddenStateGradient;

            Vector<double> cellStateGradient =
                    ActivationCache[index][(int)LSTMParameter.O]
                        .PointwiseMultiply(ActivationGates[index][(int)LSTMParameter.V].BackPropagation(hiddenStateGradient)) +
                            _nextCellStateGradient;

            Vector<double> cGradient = cellStateGradient.PointwiseMultiply(ActivationCache[index][(int)LSTMParameter.I]);
            Vector<double> iGradient = cellStateGradient.PointwiseMultiply(ActivationCache[index][(int)LSTMParameter.C]);
            Vector<double> fGradient = cellStateGradient.PointwiseMultiply(previousCellState);
            Vector<double> oGradient = hiddenStateGradient.PointwiseMultiply(
                ActivationGates[index][(int)LSTMParameter.V].ForwardPropagation(CellStates[index]));

            for (int i = 0; i < 4; i++)
                LSTMGates[i].Input = CellInputs[index];

            Vector<double> F_ActivationGradient = LSTMGates[(int)LSTMParameter.F].BackPropagation(
                ActivationGates[index][(int)LSTMParameter.F].BackPropagation(fGradient));

            Vector<double> I_ActivationGradient = LSTMGates[(int)LSTMParameter.I].BackPropagation(
                ActivationGates[index][(int)LSTMParameter.I].BackPropagation(iGradient));

            Vector<double> O_ActivationGradient = LSTMGates[(int)LSTMParameter.O].BackPropagation(
                ActivationGates[index][(int)LSTMParameter.O].BackPropagation(oGradient));

            Vector<double> C_ActivationGradient = LSTMGates[(int)LSTMParameter.C].BackPropagation(
                ActivationGates[index][(int)LSTMParameter.C].BackPropagation(cGradient));

            _nextCellStateGradient = cellStateGradient;
            _nextHiddenStateGradient = hiddenStateGradient;

            return F_ActivationGradient +
                   I_ActivationGradient +
                   O_ActivationGradient +
                   C_ActivationGradient;
}

These cells are called from the forward and back propagation methods respectively:
Forward prop:
public override Vector<double> ForwardPropagation(Vector<double> input)
{
            Input = input;

            for (int i = 0; i < _sequenceLength; i++)
            {
                Vector<double> currentInput = input.SubVector(i * _vocabSize, _vocabSize);
                LSTMForwardCell(currentInput, i);
            }

            Vector<double> outputCell = LSTMGates[(int)LSTMParameter.V].ForwardPropagation(HiddenStates[_sequenceLength - 1]);

            return outputCell;
}

Back prop:
public override Vector<double> BackPropagation(Vector<double> outputError)
{
            if(!AccumulateGradients) DrainGradients();
            _nextCellStateGradient = Vector<double>.Build.Dense(_hiddenUnits);
            _nextHiddenStateGradient = Vector<double>.Build.Dense(_hiddenUnits);
            Vector<double> outputGradient = Vector<double>.Build.Dense(_sequenceLength * _vocabSize);

            outputError = LSTMGates[(int)LSTMParameter.V].BackPropagation(outputError);

            Vector<double> previousCellGradient = outputError;
            for (int i = _sequenceLength - 1; i >= 0; i--)
            {
                Vector<double> rawLSTMGradient = LSTMBackwardCell(previousCellGradient, i);
                outputGradient.SetSubVector(i * _vocabSize, _vocabSize, rawLSTMGradient);
                previousCellGradient = rawLSTMGradient.SubVector(0, _hiddenUnits);
            }

            return outputGradient;
}

Note that I have Dense/Activation layers already implemented and I am reusing them here within the LSTM since each of the 4 LSTM activations are just a dense layer passed to an activation layer.
My unit tests use finite differences to verify the correctness of the gradient computations and they indicate that the above code seems to be correct for a single cell (the last cell in the sequence).
In case more context is needed, the full project can be found here and the class where the above code lives is found here.
Thank you very much in advance for any insights that can be offered!


text:
Q: Posting a comment by signing into LinkedIn I have a question about the possibility of writing a comment or review on a website by having to sign into LinkedIn first. Just like how you can Sign into Twitter and post comments, can you do the same with LinkedIn.
I want to make sure that not just anyone is posting comments on a site - that is, I want to verify that its a legitimate person commenting.

A: LinkedIn does support this functionality - it's used by AOL on sites like their Defense page:
http://defense.aol.com/
The tutorials page for LinkedIn includes an example of using LinkedIn for Login and Registration on a site:
https://developer.linkedin.com/documents/tutorials
Or you can simply use Login with LinkedIn directly (if you don't want to integrate with an existing registration system):
https://developer.linkedin.com/documents/sign-linkedin
Hope this helps!


text:
Q: How do I update an Entity Reference using a SelectList in edit form? This is a follow-up to the discussion in this post. I am not sure how to ask the follow-up question in a 2-month-old thread; so I apologize if there is a better way.
Anyway, to reiterate I have an ASP.NET MVC Edit form, and one of the fields is a select list. I get the values fine, but I am having trouble to update the primary entity after Post. Obviously, I have the key to the lookup entity, but it seems crazy to have to load all lookups. So, the suggested solution is entity reference
For clarity, let's say I have a customer as main entity, and title (Mr / Mrs / Dr, etc.) as the lookup.
So, the link above suggests the following:
customer.TitleReference.EntityKey = new EntityKey("MyEntities.Titles", "Id",
    Int32.Parse(formData["personTitle"]);

So far, so good. I assign the entity key (and I see in the debugger that is indeed what I expect). But I can't figure out how to get the new value saved along with other customer fields. I am doing the following:
var originalCustomer = (from c in MyEntities.Customers
    where c.Id = customer.Id select c).first();
MyEntities.ApplyPropertyChanges(originalCustomer.EntityKey.EntitySetName,
    customer);

This updates all customer fields, except for lookups. Intuitively, it is (somewhat) understandable, since if I specify originalCustomer.EntityKey.EntitySetName, ApplyPropertyChanges ignores originalCustomer.TitleReference.EntityKey.EntitySetName.
But if I do specify originalCustomer.TitleReference.EntityKey.EntitySetName, runtime complains that the entity is null (which is also understandable, since I didn't assign anything to the entity; only to entity reference.
As is probably obvious, I am going circles around what seems to be quite straightforward situation. However, I can't find any tutorials that cover it (which is strange in itself).
Furthermore, I have a more complex problem... the customer may have multiple addresses and the address has state... hopefully, once I figure out the titles - I can extrapolate.
By the way, the example (customer - title - address) is fictitious; but it models the problem quite well.

A: This should work:
var originalCustomer = (from c in MyEntities.Customers
    where c.Id = customer.Id select c).First();

originalCustomer.TitleReference.EntityKey = new EntityKey("MyEntities.Titles", "Id",
    Int32.Parse(formData["personTitle"]);

context.SaveChanges()


text:
Q: Error: You need to specify a command before moving on. Use '--help' to view the available commands al obtener la versión de angular Estaba instalando la cli de angular y sale correctamente instalado pero al momento de verificar la versión me salta este error. ¿Qué puede ser?:
Error: You need to specify a command before moving on. Use '--help' to view
the available commands.

A: Como se describe en el historial de cambios de la versión 14 de angular-cli, el comando ng —-version fue removido en la nueva versión de angular a favor de ng version y  ng v.
Por favor, usa a partir de ahora:
ng version

o bien:
ng v