text:
Q: undefined is not an object (evaluating '_react.React.Component') I am developing an app in react-native while running the app I get this error.

My index.js file
import App from './App';
import {name as appName} from './app.json';

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

My App.js file
import { StyleSheet, View, StatusBar } from 'react-native';
import Routes from './src/store/Routes';
import 'react-native-gesture-handler';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#18163E" barStyle="light-content" />
        <Routes />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
  },

}); ```

While running i am getting above error and it is pointed to index.js file

A: This is missing.
import React, { Component } from 'react';

A: Did you forget to import AppRegistry from react-native?

A: Your error message clearly states the React component missing.
In your App.js file add the below line:
import React, { Component } from 'react';

All of your react components should have this line.
After adding the above line your App.js file will appear as below:
import React, { Component } from 'react';
import { StyleSheet, View, StatusBar } from 'react-native';
import Routes from './src/store/Routes';
import 'react-native-gesture-handler';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#18163E" barStyle="light-content" />
        <Routes />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
  },

});


text:
Q: How to pass multiples states at the same time to a child component from parent component in Reactjs? I am new to Reactjs and thanks in advance.
I have the states below:
const [firstName, setFirstName]=useState();
const [lastName, setLastName]=useState();

I want to pass both firstName and lastName to the child component from the parent component at the same time. How could I do that?

A: You could do it this way, assuming that your components are called Parent and  Child:
export default function Parent(){
   const [firstName, setFirstName]=useState();
   const [lastName, setLastName]=useState();

   return (
     <Child firstName={firstName} lastName={lastName} />
   )

}

And you get them inside Child like so:
export default function Child(props){

  console.log(props.firstName, props.lastName)
  return

}

A: If you mean that you want to pass firstName and lastName to child element, relevant to component where you declared the states then you just need to pass them as props
<Child firstName={firstName} lastName={lastName} />

and inside child you would access them like props
function Child(props){

console.log(props) //this will show props of child component, there are stored your statements

return(...something here...)
}

A: See the react docs for components and props

Components accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.

When React sees an element representing a user-defined component, it passes JSX attributes (and children) to this component as a single object. We call this object "props".

import { useState } from "react";

function ParentComponent() {
  const [firstName, setFirstName] = useState("John");
  const [lastName, setLastName] = useState("Smith");
  return (

      <ChildComponent firstName={firstName} lastName={lastName} />

  );
}

function ChildComponent(props) {
  return (

firstName: {props.firstName}

lastName: {props.lastName}

  );
}

Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: A plane electromagnetic wave - phase change - amplitude
A plane electromagnetic wave has the shape:
$\vec{E}(\vec{r},t)=E_0\cdot cos(\vec{k}\vec{r}-\omega t)\cdot \vec{e}_y$
$\vec{B}(\vec{r},t)=(B_1\cdot cos(\vec{k}\vec{r}-\omega t)+B_2\cdot sin(\vec{k}\vec{r}-\omega t))\cdot \vec{e}_z=B_0\cdot cos(\vec{k}\vec{r}-\omega t+\phi)\cdot \vec{e}_z$
In what direction is $\vec{k}$ facing?
Determine the amplitude $B_0$ and the phase change $\phi$ between $\vec{E}$ and $\vec{B}$.

We got this one in our lecture of experimental physics and it kind of bugs me because I can't find the right approach to this one.
How can I get from what is given to the direction of $\vec{k}$. I mean, I know that electromagnetic wave is moving along the x-axis from that, meaning $\vec{r}$ is too? Can I conclude the direction from the fact that there is a dot product between $\vec{k}$ and $\vec{r}$?
About the second part: In general $E$ and $B$ are in phase, right? Since that's not the case here, can I assume that it results from a reflection on a surface? But how would I get to $B_0$ and the phase change without explicit values for $\omega$ and such?

A:
How can I get from what is given to the direction of $\vec{k}$

The E-field has only a y component. And the B-field has only a z-component. Since this is a plane wave, then you know that the direction of propagation must be in either positive or negative x.
From the information given, I believe it's actually ambiguous which direction the wave is travelling.

In general E and B are in phase, right?

Yes. In a plane wave they are in phase. In a near-field radiation situation, they might not be. See further discussion in this electronics stackexchange question

Since that's not the case here, can I assume that it results from a reflection on a surface?

No, even if the plane wave resulted from a reflection off a surface, the E and B fields would be in phase.

But how would I get to $B_0$ and the phase change without explicit values for ω and such?

You can determine $B_1$ and $B_2$ from knowing that the E and B fields are in phase. Then you can determine $B_0$ and $\phi$ from those ($\phi$ = 0).

A: Enough time has passed that this homework-type question can be answered. It can be done in two ways. The first, by knowing the general properties of transverse electromagnetic waves; the second, by direct application of Maxwell's equations.
Method 1:
I will assume that the wave is travelling in a neutral, non-conducting medium, so that the wave-vector is a real number.
If we make this assumption then the E- and B-field should be in phase, so $\phi=0$.
The amplitude of the magnetic field is $E_0$ divided by the wave velocity. So $B_0 = E_0 k/\omega$.
The E-field, B-field and wave vector are mutually perpendicular and $\vec{E}\times \vec{B}$ should point in the direction of the wave vector. Since $\vec{e_y}\times \vec{e_z}=\vec{e_x}$, then $\vec{k} = k\vec{e_x}$ and $\vec{k}\cdot \vec{r} = kx$.
If $\phi=0$, then, since sine and cosine of the same argument are orthogonal functions, the wave only has a cosinusoidal component, so $B_1 = B_0$ and $B_2 = 0$.
Method 2:
Gauss's law in a neutral medium is that
$$\nabla \cdot \vec{E}=0\ .$$
If we let $\vec{k}=k_x \vec{e_x}+ k_y\vec{e_y}+ k_z\vec{e_z}$ and take the divergence of the electric field (which only has a y-component), then
$$ -k_y E_0\sin(\vec{k}\cdot \vec{r}-\omega t)=0$$
and so $k_y=0$.
We can then use Faraday's law to get an expression for the B-field.
$$\vec{B} = -\int \nabla \times \vec{E}\ dt\ .$$
$$\vec{B}= -\int -\vec{e_x} \frac{\partial E}{\partial z} + \vec{e_z}\frac{\partial E}{\partial x} \ dt$$
$$\vec{B} = \int E_0 \sin(\vec{k}\cdot\vec{r}-\omega t)(-k_z \vec{e_x}+ k_x\vec{e_z})\ dt, $$
$$\vec{B} = \frac{E_0}{\omega}\cos(\vec{k}\cdot\vec{r}-\omega t)(-k_z \vec{e_x}+ k_x\vec{e_z})\ .$$
Comparing this with
$$ B_0 \cos(\vec{k}\cdot\vec{r}-\omega t +\phi)\vec{e_z}$$
we can immediately see that $k_z=0$, $\phi=0$ and that $B_0 = E_0 k_x/\omega$.
Note, that if $k$ were a complex number (for example, a wave in a conductor), then $B_0$ would also be complex. To have $B_0$ as a real number, the phase angle $\phi$ would have to be a non-zero value.

A: Recall that $cos\alpha\cdot sin\beta +cos\beta\cdot sin\alpha = cos(\alpha+\beta)$.
If you suppose that $B_1=B_0\cdot sin\phi$ and $B_2=B_0\cdot cos\phi$, it turns out that:
$B_1cos(kr-\omega t)+B_2cos\phi=B_0\cdot sin\phi \cdot cos(kr-\omega t)+B_0\cdot sin(kr-\omega t)\cdot cos\phi=$
$=B_0\cdot cos(kr-\omega t+\phi)$.


text:
Q: Implementing Google Calendar to Angular 14 I'm making a website for a cultural association in my local area and I'm trying to implement a calendar linked with a Google Calendar that the owner can easily modify on his end so that it's updated on the website.
I'm new with Angular and webdev, and I just tried some Angular components I found here and there.
Mainly tried Fullcalendar but didn't understand how to implement it in angular 14 with google events.
I see the code mostly uses js while I code in typescript through component modules.


text:
Q: Error: failed to find target with hash string 'android-14' in:Open Android SDK Manager I know this question has been asked several times before this, but i am looking for some other kind of answer.
I just want to run a project, and it gives me this error.
Error:A problem occurred configuring project ':app'.
> failed to find target with hash string 'android-14' in: C:\Users\etc.
Open Android SDK Manager

I took a look at my Android sdk manager, and yes. I do not have  android 14.
Then I tried to find the part of project which refrences the Andoid 14. But i found nothing.
Here is my manifest
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
<application android:label="@string/app_name"
             android:icon="@drawable/ic_launcher">

So which part or line really ask for Android 14?

A: here is the solution
open build.gradle there you will find
compileSdkVersion 8

change it to android 6 version as shown below
compileSdkVersion 23

A: You need to replace the number of target into project.properties "target=android-14" to your available android api level in your android studio. You can see that on SDK Manager.
Example, if you have api level 22 available you need to put  "target=android-22"

A: I had this issue when I imported openCV library into Android Studio.
It turns out I just need to manually edit the build.gradle for the openCV library to match your own project.

A: you can find those properties in 'build.gradle'
// Compilation configuration.
minSdkVersion = 13
compileSdkVersion = 14
targetSdkVersion = 14
buildToolsVersion = "14.0.0"

You can change to install SDK version or add SDK version for your IDE

A: Facing the same issue, I have found atribute "compileSkdVersion" which holds the reference to v.14 in proguard.cfg (Graddle Scripts, assuming you are using Android Studio 1.4).
Changed to "23" (latest today version),  error went gone.
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.android.lifecycle"
        minSdkVersion 7
        targetSdkVersion 15
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

A: I'm facing the same issue.
What I did to work was:

*

*Open de build.gradle in notepad++.

*Change the attr "compileSdkVersion" from "Google Inc.:Google APIs:14" to "14"

*Open de Android Studio and rebuild de project.

A:
Then I tried to find the part of project which refrences the Andoid 14. But i found nothing.

It would be in your project.properties file in an Eclipse project, or your module's build.gradle file (compileSdkVersion) in an Android Studio project.


text:
Q: kubernetes PersistentVolumeClaim not bound, but volume is bound I'm new to Kubernetes and I'm following the GKE Elasticsearch 5 Getting Started doc. I cannot get the cluster to start when using the PersistentVolumeClaim and the configMap (mounting local, my laptop, path to containers). It works when the configMap is removed.
kubectl version:
Client Version: version.Info{Major:"1", Minor:"7", GitVersion:"v1.7.0", GitCommit:"d3ada0119e776222f11ec7945e6d860061339aad", GitTreeState:"clean", BuildDate:"2017-06-29T23:15:59Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:33:17Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}

kubectl describe pod some-elasticsearch outputs the error:
[SchedulerPredicates failed due to persistentvolumeclaim "elasticsearchdata" not found, which is unexpected., SchedulerPredicates failed due to persistentvolumeclaim "elasticsearchdata" not found.
[SchedulerPredicates failed due to PersistentVolumeClaim is not bound: "elasticsearchdata", which is unexpected., SchedulerPredicates failed due to PersistentVolumeClaim is not bound
The volume is shown as bound. Any suggestions? Here's my pod.yaml:
metadata:
  name: some-elasticsearch
  labels:
    name: some-elasticsearch
spec:
  containers:
    - image: launcher.gcr.io/google/elasticsearch5
      name: elasticsearch
      volumeMounts:
        - name: elasticsearchdata
          mountPath: /usr/share/elasticsearch/data
        - name: elasticsearchconfig
          mountPath: /usr/share/elasticsearch/config
  volumes:
    - name: elasticsearchdata
      persistentVolumeClaim:
        claimName: elasticsearchdata
    - name: elasticsearchconfig
      configMap:
        name: elasticsearchconfig
---
# Request a persistent volume from the cluster using a Persistent Volume Claim.
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: elasticsearchdata
  annotations:
    volume.alpha.kubernetes.io/storage-class: default
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 5Gi

If I comment out the elasticsearchconfig, the cluster starts successfully:
- name: elasticsearchconfig
  mountPath: /usr/share/elasticsearch/config

- name: elasticsearchconfig
  configMap:
    name: elasticsearchconfig

Output from kubectl describe pvc elasticsearchdata:
Name:       elasticsearchdata
Namespace:  default
StorageClass:   standard
Status:     Bound
Volume:     pvc-52f0d3d2-6d57-11e7-94f6-42010af002a5
Labels:     <none>
Annotations:    pv.kubernetes.io/bind-completed=yes
        pv.kubernetes.io/bound-by-controller=yes
        volume.alpha.kubernetes.io/storage-class=default
        volume.beta.kubernetes.io/storage-provisioner=kubernetes.io/gce-pd
Capacity:   5Gi
Access Modes:   RWO
Events:
  FirstSeen LastSeen    Count   From                SubObjectPath   Type        Reason          Message
  --------- --------    -----   ----                -------------   --------    ------          -------
  2m        2m      1   persistentvolume-controller         Normal      ProvisioningIgnoreAlpha both "volume.alpha.kubernetes.io/storage-class" annotation and storageClassName are present, using storageClassName
  2m        2m      1   persistentvolume-controller         Normal      ProvisioningSucceeded   Successfully provisioned volume pvc-52f0d3d2-6d57-11e7-94f6-42010af002a5 using kubernetes.io/gce-pd

I want to have persistent storage and need to load a custom elasticsearch.yml from the elasticsearchconfig configMap.


text:
Q: Launching a steam game from a Java program I am trying to make a java program to open files and applications on my PC, now the problems only arise when I try to open a steam game (i.e. Planetside 2 or Terraria) from this program.  I have tried using Runtime, but that failed as well.  Here is where I am trying to open the game:
public void mousePressed(MouseEvent e) {
        try {
            Desktop.getDesktop().browse(new URL(path).toURI());
        } catch (URISyntaxException | IOException e1) {
            try {
                Desktop.getDesktop().open(new File(path));
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            e1.printStackTrace();
        }
    }

If anyone can try to figure it out, it would be greatly appreciated!
This is the output error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: steam:\rungameid\218230 doesn't exist.

The path variable was "steam://rungameid/218230".

A: You have to instruct the Steam.exe process to open your game by its app id or you can use the steam protocol:
import lombok.val;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;

import static java.awt.Desktop.getDesktop;
import static java.util.Arrays.asList;

public class SteamGameExecutor
{
    public static final String STEAM_INSTALLATION_PATH = "C:\\Program Files (x86)\\Steam\\Steam.exe";
    private static final boolean USE_STEAM_PROTOCOL = true;

    public static void startGameById(String id) throws Exception
    {
        if (USE_STEAM_PROTOCOL)
        {
            val desktop = getDesktop();
            val steamProtocol = new URI("steam://run/" + id);
            desktop.browse(steamProtocol);
        } else
        {
            startProcess("-applaunch", id);
        }
    }

    private static void startProcess(String... arguments) throws IOException
    {
        val allArguments = new ArrayList<String>();
        allArguments.add(STEAM_INSTALLATION_PATH);
        val argumentsList = asList(arguments);
        allArguments.addAll(argumentsList);
        val process = new ProcessBuilder(allArguments);
        process.start();
    }
}

The protocol version should be more portable/platform-independent unless it doesn't exist on Linux/Mac.
To find the app id you can use this search. An implementation of finding the app id programmatically is for instance the following:
import lombok.val;

import java.io.IOException;

import static java.net.URLEncoder.encode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.jsoup.Jsoup.connect;

public class SteamAppIdFinder
{
    private static final String SEARCH_URL = "https://steamdb.info/search/?a=app&q=";
    private static final String QUERY_SELECTOR = "#table-sortable > tbody > tr > td:nth-child(1) > a";

    public static String getAppId(String searchTerm) throws IOException
    {
        val completeSearchURL = SEARCH_URL + encode(searchTerm, UTF_8.name());
        val connection = connect(completeSearchURL);
        val document = connection.get();
        val selectedElements = document.select(QUERY_SELECTOR);
        val anchorElement = selectedElements.get(0);
        return anchorElement.text();
    }
}

Note that the second code snippet required JSoup. Furthermore I'm using Lombok for the val keyword.


text:
Q: Could not find or load main class BasicApp.Application I am new to spring boot and was trying to create a very basic application on spring boot. But, I am getting this error while creating my application.

Could not find or load main class BasicApp.Application

My Application is having two classes one Controller Class and one Main Class. Here is my code:
Application.java
package BasicApp;

import org.springframework.boot.SpringApplication;

public class Application
{
    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

MainController.java
package BasicApp;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class MainController
{
    @RequestMapping("/send")
    @ResponseBody
    public String sendMessage()
    {
        return("M sending message");
    }
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringBootSecond</groupId>
<artifactId>SpringBootSecond</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
    <!-- Spring version -->
    <spring-framework.version>4.1.0.RELEASE</spring-framework.version>
    <!-- ActiveMQ version -->
    <activemq.version>5.10.0</activemq.version>
</properties>

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

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.3.2.RELEASE</version>
    </dependency>

    <!-- Spring aritifacts -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>4.2.4.RELEASE</version>
    </dependency>

    <!-- ActiveMQ Artifacts -->
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-spring</artifactId>
        <version>${activemq.version}</version>
    </dependency>
</dependencies>

<!-- Using JDK 1.7 for compiling -->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<!--    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.3.2.RELEASE</version>
        </parent>

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

        <properties>
            <java.version>1.8</java.version>
        </properties>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

        <repositories>
            <repository>
                <id>spring-releases</id>
                <url>https://repo.spring.io/libs-release</url>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-releases</id>
                <url>https://repo.spring.io/libs-release</url>
            </pluginRepository>
        </pluginRepositories> -->
</project>

Could somebody please help me with this error?

A: Put @SpringBootApplication annotation to your Application class and it will do all the configuration for you.

A: see build errors, usually files is zero size , delete bad files in maven folder


text:
Q: Apply function to dataframe column based on combinations of values from other columns I have a dataframe that looks like this:

Region
Country
Product
Year
Price

Africa
South Africa
ABC
2016
500

Africa
South Africa
ABC
2017
400

Africa
South Africa
ABC
2018
15

Africa
South Africa
ABC
2019
450

Africa
Uganda
ABC
2016
750

Africa
Uganda
ABC
2017
670

Africa
Uganda
ABC
2018
1300

Africa
Uganda
ABC
2019
890

Asia
Japan
DEF
2016
500

Asia
Japan
DEF
2017
420

Asia
Japan
DEF
2018
415

Asia
Japan
DEF
2019
0

data = {'Region': ['Africa','Africa','Africa','Africa','Africa','Africa','Africa','Africa','Asia','Asia','Asia','Asia'],
         'Country': ['South Africa','South Africa','South Africa','South Africa','Uganda','Uganda','Uganda','Uganda','Japan','Japan','Japan','Japan'],
         'Product': ['ABC','ABC','ABC','ABC','XYZ','XYZ','XYZ','XYZ','DEF','DEF','DEF','DEF'],
         'Year': [2016, 2017, 2018, 2019,2016, 2017, 2018, 2019,2016, 2017, 2018, 2019],
         'Price': [500, 400, 15,450,750,670,1300,890,500,420,415,0]}
df = pd.DataFrame(data)

I want to calculate the Interquartile Range to identify outliers and extract the index positions of potential outliers.
I created a function however, I am having trouble applying the function to the Price column based on combinations of the Region and Product columns.
My function is below:
def tukeys_method(df, variable, iterable1, iterable2):
    itr1 = df[iterable1].unique() #create list of unique values for iterable 1
    itr2 = df[iterable2].unique() #create list of unique values for iterable 2
    for (i,j) in zip(itr1, itr2):

        #Takes two parameters: dataframe & variable of interest as string
        q1 = df.groupby([iterable1,iterable2])[variable].quantile(0.25) #calculate quantiles
        q3 = df.groupby([iterable1,iterable2])[variable].quantile(0.75) #calculate quantiles
        iqr = q3-q1
        inner_fence = 1.5*iqr
        outer_fence = 3*iqr

        #inner fence lower and upper end
        inner_fence_le = q1-inner_fence
        inner_fence_ue = q3+inner_fence

        #outer fence lower and upper end
        outer_fence_le = q1-outer_fence
        outer_fence_ue = q3+outer_fence

        outliers_prob = []
        outliers_poss = []
        for index, x in enumerate(df.groupby([iterable1,iterable2])[variable]):
            if x <= outer_fence_le or x >= outer_fence_ue:
                outliers_prob.append(index)
        for index, x in enumerate(df.groupby([iterable1,iterable2])[variable]):
            if x <= inner_fence_le or x >= inner_fence_ue:
                outliers_poss.append(index)
        return outliers_prob, outliers_poss

probable_outliers_tm, possible_outliers_tm = tukeys_method(df, "Price",'Region','Product')

I get the following error when I run the function:
ValueError: operands could not be broadcast together with shapes (570,) (2,)

Does anyone know what I need to do to fix this?

A: I managed to figure it out, if anyone is interested, the solution is below:
# Identify outliers using Tukey's method.
def outliers_tukey(df, variable, iterable1, iterable2):
    outliers_prob = []
    outliers_poss = []
    for (i,j) in itertools.product(df[iterable1].unique(), df[iterable2].unique()):

        #Takes two parameters: dataframe & variable of interest as string
        q1 = df.loc[(df[iterable1]==i) & (df[iterable2]==j)][variable].quantile(0.25)
        q3 = df.loc[(df[iterable1]==i) & (df[iterable2]==j)][variable].quantile(0.75)
        iqr = q3-q1
        inner_fence = 1.5*iqr
        outer_fence = 3*iqr

        #inner fence lower and upper end
        inner_fence_le = q1-inner_fence
        inner_fence_ue = q3+inner_fence

        #outer fence lower and upper end
        outer_fence_le = q1-outer_fence
        outer_fence_ue = q3+outer_fence

        for index, x in enumerate(df[variable]):
            if x <= outer_fence_le or x >= outer_fence_ue:
                outliers_prob.append(index)
        for index, x in enumerate(df[variable]):
            if x <= inner_fence_le or x >= inner_fence_ue:
                outliers_poss.append(index)
        return outliers_prob, outliers_poss

probable_outliers_tm, possible_outliers_tm = outliers_tukey(df, "Price",'Region','Product')


text:
Q: dialogClass not applying the given style class Am using 2 Jquery Dialog box in my xhtml page. There are 2 links and when a user clicks on those links each link will render a different Dialog box. Different Dialog box in the sense look and feel are different. Since both are referring to jquery-ui-rev.css whatever CSS changes are done in that .css file, it is getting applied to both the Dialog box.

So, I tried with dialogClass . I applied dialogClass for one of the Dialog box and left the other as it is.
And I came up with below code and deployed it.
$j("#dialog").dialog({
    dialogClass: 'ui-dialog',
      ....

<head>
<style type="text/css">
 .ui-dialog
{
padding: none;
overflow: hidden;
position: absolute;
width: 100px;
left: 100px;
top: 100px;
}
</style>
</head>

But, ui-dialog class I have written here is not overriding the standard ui-dialog class of jquery-ui-rev.css. Then, I also tried with a different name for ui-dialog. i.e., I renamed ui-dialog with my-dialog. Even then my-dialog is not getting applied for Dialog box. It still takes from standard CSS class of ui-dialog.
Then, I also tried with below code
$j("#dialog").addClass('my-dialog').dialog({

This also couldn't override the standard ui-dialog class.
PS Note : I have renamed jquery-ui-rev.css to jquery-ui-curretpacks.css. jquery-ui-currentpacks.css contains exact contents of jquery-ui-rev.css
@Dipaks I have tried the solution as you have mentioned. Code is as below,
$('.ui-dialog').addClass('new-ui-dialog');
$j("#dialog").dialog({
    dialogClass: 'new-ui-dialog',
....

But, as I have attached in the new image, it can be seen that though ui-dialog is getting replaced by new-ui-dialog, but css properties are still taken from ui-dialog.
I also gave a try without dialogClass like below,
    $j("#dialog").dialog({
    .....
<style type="text/css">
.new-ui-dialog
{
 //my new css
}
</style>

Am attaching 3rd image here. In this SS, new-ui-dialog attributes are overridden still.

A: .ui-dialog is adding inline css for the element. If you want to override these styles do this -
$('.ui-dialog').addClass('new-ui-dialog');

CSS -
.new-ui-dialog { color: red !important; }


text:
Q: select statement to return additional row I am  creating reports in SSIS using datasets and have the following SQL requirement:
The sql is returning three rows:
a
b
c

Is there anyway I can have the SQL return an additioanal row without adding data to the table?
Thanks in advance,
Bruce

A: select MyCol from MyTable
union all
select 'something' as MyCol

A: You can use a UNION ALL to include a new row.
SELECT *
FROM yourTable
UNION ALL
SELECT 'newRow'

The number of columns needs to be the same between the top query and the bottom one.  So if you first query has one column, then the second would also need one column.

A: If you need to add multiple values there is a stranger syntax available:
declare @Footy as VarChar(16) = 'soccer'
select 'a' as Thing, 42 as Thingosity -- Your original SELECT goes here.
  union all
  select *
    from ( values ( 'b', 2 ), ( 'c', 3 ), ( @Footy, Len( @Footy ) ) ) as Placeholder ( Thing, Thingosity )


text:
Q: How can I use a button within a listView such that when I click that button, I can get that selected item and run a query on it? I basically have this shopping cart app and in my listView it displays me all the items such as the item's description, store, brand, price, and the image of it and under each item, there's an add to cart button. So when I click on this button for an item, I want to run a query and add that item to my existing database. I am using a button onClickListener, but how do I first get that specific item in my listView for which I clicked the button and then run the query on that item's info such as the description, brand, store, price, etc.? I haven't posted my code, but I just need to know how to do this.

A: Every time if you create a item layout you can use the index of the row as tag for your button.
Here is an example:
private class MyListAdapter extends ArrayAdapter<MYItem> implements View.OnClickListener {

    public MyListAdapter () { [...] }

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

        View view = convertView;
        if (view == null) {
            LayoutInflater vi = LayoutInflater.from(getContext());
            view = vi.inflate(R.layout.my_item_layout, parent, false);
        }

        MYItem item = getItem(position);

        [...]

        View btn = view.findViewById(R.id.list_item_btn);
        btn.setTag(position);

        return view;
    }

    // now you can get row index in this way:

    @Override
    public void onClick(final View v) {
        Integer index = (Integer ) v.getTag();
        [...]
    }
}

A: <a href="addToCart?cartId=<%=product.getCartId()%>"><button type="button">Add to Cart</button>

*

*Suppose addToCart() is your method.

*Annotate your method as (If you are using spring framework)
@RequestMapping(value="addToCart",method=RequestMethod.GET)


text:
Q: Get Google Username with oAuth in XML I'm having trouble right now getting the username of the logged in Google User. I want to get the Data I need from this Link:
https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
state=%2Fprofile&
redirect_uri={REDIRECT_URL}
response_type=token&
client_id={CLIENT_ID}

this link authenticates with oAuth and gets my Account information, but i don't want to use a "Redirect_URL" i just want to get the data as an XML-File and use it with JavaScript. I want this link to run in my Gadget for Google Sites, so i can use the data from this link in my Gadget.

A: From your question I think you misunderstand the Oauth2 flow.
You redirect the user to Googles url where the user authenticates himself with his google credentials. So the user authenticates on the google website and not inside your application. This to make sure that a user doesn't have to fill in his credentials in any other application/site then google. When the user has accepted the use of their information by your app google will call your redirect url and provide you with a code which you can use to get the user data. So it is up to you to catch the redirect from Google and request the data you need with the code you get from Google inside the callback (your redirect url).
Also take a look at this image:


text:
Q: JSP Taglib PropertyNotFoundException I have a variable named user in JSP.
If I set user variable in mvc controller, I can handle ${user.userNo}.
On the contrary if I do not set user object, i can not use ${user.userNo}, and it throws PrpoertyNotFoundException.
I want to divide the two cases whether user is set or not.
So I coded like below:
<c:choose>
    <c:when test="${not empty user}">
        <c:set var="userNo"><c:out value="${user.userNo}" /></c:set>
    </c:when>
    <c:otherwise>
        <c:set var="userNo" value="anonymous" />
    </c:otherwise>
</c:choose>

but the problem is that If I do not set user object, it doesn't forward to <c:otherwise> code. And it throws an exception because ${user.userNo} is not defined.
in similar case, it throws PropertyNotFoundException beacuse of ${user.userNo}
<c:if test="${not empty user">
<c:set var="userNo" value="${user.userNo}" />
</c:if>

It seems like every values used in EL expressions must be set before running the code.
Is there a way not to throw an exception when I do not set ${user} variable?
EDIT
part of error stack:
Servlet.service() for servlet [appServlet] in context with path [/whiteboard] threw exception [Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException: org.apache.tiles.util.TilesIOException: JSPException including path '/WEB-INF/views/tiles/contents/viewArticle.jsp'.] with root cause
javax.el.PropertyNotFoundException: Property 'userNo' not found on type java.lang.String
    at javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:290)
    at javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:243)
    at javax.el.BeanELResolver.property(BeanELResolver.java:377)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
    at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:184)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
    at org.apache.jsp.WEB_002dINF.views.tiles.contents.viewArticle_jsp._jspx_meth_c_005fout_005f0(viewArticle_jsp.java:560)
    at org.apache.jsp.WEB_002dINF.views.tiles.contents.viewArticle_jsp._jspx_meth_c_005fset_005f0(viewArticle_jsp.java:533)
    at org.apache.jsp.WEB_002dINF.views.tiles.contents.viewArticle_jsp._jspx_meth_c_005fwhen_005f0(viewArticle_jsp.java:497)
    at org.apache.jsp.WEB_002dINF.views.tiles.contents.viewArticle_jsp._jspx_meth_c_005fchoose_005f0(viewArticle_jsp.java:460)
    at org.apache.jsp.WEB_002dINF.views.tiles.contents.viewArticle_jsp._jspService(viewArticle_jsp.java:119)


text:
Q: What jQuery modal popup or lightbox plugin works in IE7, IE8, IE9 Firefox, Chrome, Safari? We're looking to put a popup login window on the screen while dimming the background and disabling mouse clicks to it.
We're using jQuery, and this is a Rails 3 application, and we're looking for a lean plugin.
It's been bafflingly difficult to come up with a framework that supports IE7 and IE8 equally. The other browsers (Firefox, Chrome, Safari, IE9) haven't posed much of a problem.
We'd also like to avoid using background image overlays, if possible, due to lateny concerns. For the same reason we don't want to load the whole effects library, if possible.
Thoughts?
Thanks,
Wolf

A: Colorbox is what you're looking for.

A: I've used ColorBox in the past (and is good), but now I'm using jQuery UI Dialog because it's the most flexible and compatible dialog popup.
You can also run it from the Google CDN without even adding the script to your project.

A: in my opinion
http://fancybox.net/ Fancybox is a good option. it's work well for me. but i never tested in all browser so i can't say that "it's cross browser compatible".


text:
Q: The name of a game from the 2013 Putnam Does the following game from the 2013 Putnam have an official name?  Based on my searches, it seems to have been created just for the exam.
Let $n\geq 1$ be an odd integer.  Alice and Bob play the  following game, taking alternating turns, with Alice playing first. The playing area consists of $n$ spaces, arranged in a line. Initially all spaces are empty. At each turn, a player either
• places a stone in an empty space, or
• removes a stone from a nonempty space $s$, places a stone in the nearest empty space to the left of s (if such a space exists), and places a stone in the nearest empty space to the right of s (if such a space exists).
Furthermore, a move is permitted only if the resulting position has not occurred previously in the game. A player loses if he or she is unable to move. Assuming that both players play optimally throughout the game, what moves may Alice make on her first turn?


text:
Q: How to narrow an array for a specific condition? I have an array:
results = [
  {"Created Date ": "20181012", "Created By ": "A", "Job Number ": "001", "Department": "FS"},
  {"Created Date ": "20181012", "Created By ": "B", "Job Number ": "002", "Department": "DS"},
  {"Created Date ": "20181012", "Created By ": "C", "Job Number ": "004", "Department": "FS"}
]

Each value will like below sometime.(without blank char and column order changed, but the column name is fixed)
results = [
  {"Created By": "A", "Department": "FS", "Created Date": "20181012", "Job Number": "001" },
  {"Created By": "B", "Department": "DS", "Created Date": "20181012", "Job Number": "002"},
  {"Created By": "C", "Department": "FS", "Created Date": "20181012", "Job Number": "004"}
]

Now, I only want to get a new array that contains the value of 3 columns, "Created By", "Created Date", and "Job Number", with a specific order.  The expected value should like:
results = [
  {"20181012", "A", "001"},
  {"20181012", "B", "002"},
  {"20181012", "C", "004"}
]

Is there any good solution?

A: First note that objects don't have reliable ordering. So first or second column doesn't make any sense.
But since you know the keys for which you want the value, you can use map and at the same time account for the extra char by considering both variations of the key:

var results = [{
    "Created Date ": "20181012",
    "Created By ": "A",
    "Job Number ": "001",
    "Department": "FS"
  },
  {
    "Created Date": "20181012",
    "Created By ": "B",
    "Job Number ": "002",
    "Department": "DS"
  },
  {
    "Created Date": "20181012",
    "Created By ": "C",
    "Job Number ": "004",
    "Department": "FS"
  }
]

var output = results.map(d => [
  d['Created Date'] || d['Created Date '],
  d['Created By'] || d['Created By '],
  d['Job Number'] || d['Job Number ']
]);

console.log(output);

A: This demonstrates another way one might use an Array object's map() method, as follows:

var results = [{
"Created Date ": "20181012",
"Created By ": "A",
"Job Number ": "001",
"Department": "FS"
  },
  {
"Created Date": "20181012",
"Created By": "B",
"Job Number": "002",
"Department": "DS"
  },
  {
" Created Date": "20181012",
" Created By": "C",
" Job Number": "004",
"Department": "FS"
  }
];

Array.prototype.remove = function(index){
  this.splice(index,1);
}

var nu_arry = results.map(item => {
  let d = [];
  let keys = Object.keys(item);
  keys.remove(3);  // remove Department key name
  keys.forEach(function(key) {
    d.push(item[key]);
  });
  return d;
});
console.log(nu_arry);

Whether a space occurs or not prior to or at the end of a key name makes scant difference because the code is able to detect precisely the names of all the keys by utilizing Object.keys().  The advantage of this solution is that if ever a coder decided to modify the names of the keys, this code would still work, since there is no hard-coding of the variant keys. Note: the short arrow function syntax obviates the need to create a separate user-defined function.


text:
Q: How to store thumbnails for easy retrieval I'm currently creating thumbnails by using the ThumbnailUtils.createVideoThumbnail() method; which returns a bitmap. However, I want to store that thumbnail in a database so I can access it later and I don't have to keep recreating the thumbnails. My questions is how should I store this thumbnail in the database? Do thumbnails have filepaths? Or should I create the thumbnails and just retrieve them using the Mediastore every time I need to use it? If so how would I go about saving/storing the thumbnail so I can use the Mediastore to query it?
Thanks for your help.

A: If you're getting a Thumbnail object from video, you need to save it in either storage or database.
To save in database :
Bitmap thumbnailBitmap; // Get it with your approach
SQLiteDatabase writableDb; // Get it with your approach

if (thumbnailBitmap != null) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    thumbnailBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] thumbnailBitmapBytes = stream.toByteArray();

    ContentValues values = new ContentValues();
    values.put("IMAGEID", "your_image_id");
    values.put("BYTES", thumbnailBitmapBytes);
    writableDb.insert("TABLE_NAME", null, values);
}

To get it back from database :
public static synchronized Bitmap getImage(String imageID, Context context) {
    SQLiteDatabase writableDb; // Get it with your approach
    Bitmap bitmap = null;
    Cursor cs = null;

    try {
        String sql = "SELECT BYTES FROM TABLE_NAME WHERE IMAGEID = ?;";
        cs = writableDb.rawQuery(sql, new String[]{imageID});

        if (cs != null && cs.moveToFirst()) {
            do {
                byte[] bytes = cs.getBlob(0);

                if (bytes != null) {
                    try {
                        bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    } catch (Exception e) {
                        Log.e("TAG", "Exception", e);
                    }
                } else {
                    Log.e("TAG", "IMAGE NOT FOUND");
                }

            } while (cs.moveToNext());
        }

    } catch (Exception e) {
        Log.e("TAG", "Exception", e);
    } finally {
        if (cs != null) {
            cs.close();
        }
    }

    return bitmap;
}

The database structure:
String imageTable = "CREATE TABLE TABLE_NAME("
        + "IMAGEID TEXT PRIMARY KEY, "
        + "BYTES BLOB)";


text:
Q: You have uncommitted work pending. Please commit or rollback before calling out even if we put DML in future method I know as per documentation, we cannot perform DML and then callouts from apex class.
In my scenario, I have a callout then I am performing a DML which is placed inside a future method and again there is callout after the call to future method.
Still I am getting "You have uncommitted work pending" error.
Is the solution (apart from changing the order) only to make the callout in future and DML directly?
Can't we make DML's in future method to avoid this.
Relevant Code:
global class docuSignConnector {
    public static String callDummy(){
     // Making HTTP Callo
    // making call to future method to insert log object for integration
    createIntegLog.createIntegrationLogFuture(req.getBody(),res.getBody());
    //Making HTTP callouts again - getting mixed DML Error here
   }
}

public class createIntegLog{
  @future
  public static void createIntegrationLogFuture(String reqBody,String resBody)
  {
    // Insert the Log Object here with req , response data
  }
}

A: Enqueuing Asynchronous Apex, including future methods, for execution is a "DML-equivalent" operation. It counts just like DML for purposes of causing an exception in proximity to callouts.
You must call your future method after performing the callout. You can then execute DML in the future method, which executes in a separate transaction context.


text: Q: SVG background not filling canvas in fabricjs I have a canvas whose height and width attributes are not mentioned during creation. I update the height and width of it through javascript so that it always fills the viewport height and width. When I use a jpg for the canvas background, it works fine. But when I use a svg, I find that it gets clipped to the default canvas dimension ( 300px x 150px ). But if I set the height and width of the canvas as attributes directly in the tag, then the svg fills the entire canvas properly. Why does SVG behave this way and how can I fix i?


text:
Q: Replace word by matching to another data frame I have hunted around for an existing solution to this problem - without any luck!
Any help appreciated.
Data
long.name <- c("REPUBLIC OF BELARUS", "REPUBLIC OF VIETNAM"
, "GOVERNMENT OF JAMAICA", "LEBANESE REPLUBLIC")

result <- c(256, 578, 467, 698)

df1 <- data.frame(long.name, result)

country <- c("BELARUS", "VIETNAM", "JAMAICA", "LEBANESE")

country.code <- c("BLR", "VNM", "JAM", "LBN")

df2 <- data.frame(country, country.code)

Problem
I am hoping to replace the long version of the country name only df1$long.name with the corresponding code df2$country.code.
i.e. the final result will look like this:
df1$final.aim <- c("REPUBLIC OF BLR", "REPUBLIC OF VNM",
"GOVERNMENT OF JAM", "LBN REPLUBLIC")

A: One option with stringr,
library(stringr)
#pattern
ptrn1 <- str_extract(df1$long.name, paste(df2$country, collapse='|'))
#replacement
rpl <- df2$country.code[match(df2$country, ptrn1)]

df1$long.name <- str_replace_all(df1$long.name, ptrn1, rpl)
df1
#          long.name result
#1   REPUBLIC OF BLR    256
#2   REPUBLIC OF VNM    578
#3 GOVERNMENT OF JAM    467
#4     LBN REPLUBLIC    698

A: First, I would suggest converting the factor long.name column to character. This makes some string operations easier; in particular, it enables incremental replacement of values within the column without having to worry about factor levels. Alternatively, since you want to build the final result in a new column final.aim, you can assign a stringified copy of the long.name column to the new column and then work off of that
My solution uses a for-loop to iterate over one replacement candidate at a time, IOW to iterate over one row of df2 at a time. For each row, it constructs a regex around the target word (I assumed you want to match only whole words, hence the delimitation of \b word boundary assertions). Then it greps for the long names that match the pattern, and replaces the target word in all of them with the country code, again taken from df2, using a call to sub().
df1$final.aim <- as.character(df1$long.name);
for (sri in seq_len(nrow(df2))) {
    pat <- paste0('\\b',df2$country[sri],'\\b');
    lris <- grep(pat,df1$final.aim);
    df1$final.aim[lris] <- sub(pat,df2$country.code[sri],df1$final.aim[lris]);
};
df1;
##               long.name result         final.aim
## 1   REPUBLIC OF BELARUS    256   REPUBLIC OF BLR
## 2   REPUBLIC OF VIETNAM    578   REPUBLIC OF VNM
## 3 GOVERNMENT OF JAMAICA    467 GOVERNMENT OF JAM
## 4    LEBANESE REPLUBLIC    698     LBN REPLUBLIC


text: Q: Where can I find the Google Maps API Premium account client and signature? I recently upgrade my Google Maps API to a premium one and need to provide client and signature on calls to distance matrix, but can't find those information on the Google Cloud Console.


text:
Q: BindingAdpater is not working at recyclerview I set up BindingAdpater at recyclerview items. But when I get from data, it doesn't not work.
as you see below, myItem is working. But not working at items that is in parameter. I don't understand why items(in parameter) is not working.
BindingAdapter
@BindingAdapter("app:items")
fun setItems(view: RecyclerView, items: List<LaunchListQuery.Launch>?) {
    var myItem = arrayListOf<LaunchListQuery.Launch?>()
    myItem.add(LaunchListQuery.Launch("","Id : "+1,"Site : "+1,null))
    myItem.add(LaunchListQuery.Launch("","Id : "+2,"Site : "+2,null))
    myItem.add(LaunchListQuery.Launch("","Id : "+3,"Site : "+3,null))
    (view.adapter as MainAdapter).submitList(items)
}

xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/tools">
    <data>
        <import type="android.view.View" />

        <variable
            name="viewmodel"
            type="com.haii.graphqldemo.main.MainViewModel"/>
    </data>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/main_layout">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:items="@{viewmodel.items}"/>

</LinearLayout>
</layout>

ViewModel
class MainViewModel @Inject constructor(
    private val repository: DefaultRepository
) : ViewModel() {

    private var _items :MutableLiveData<List<LaunchListQuery.Launch?>> = MutableLiveData()
    val items : LiveData<List<LaunchListQuery.Launch?>> = _items
    fun getItems(){
        viewModelScope.launch {
            val items = repository.getLaunchList()
            _items.value = items.launches
        }
    }
}

A: I solved this by adding
onCreate at Activity
binding.lifecycleOwner = this
onActivityCreated at Fragment
binding.lifecycleOwner = this.viewLifecycleOwner


text:
Q: Moving across elements using Up-Down keys I make a program using PyQt5 and Python3.7. How to move across elements using arrow keys instead of tab key? (e.g. moving from button to textbox using down key)
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QMainWindow, QPushButton, QFileSystemModel, QTreeView, \
    QFileDialog, QComboBox
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

    def __init__(self):
        super(App, self).__init__()

        self.title = 'by Qt5 and python 3.7'
        self.left = 10
        self.top = 10
        self.width = 1000
        self.height = 500

        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = QLabel('File Name: ')
        self.label.move(20, 20)

        self.btn_browse = QPushButton('Browse', self)
        self.btn_browse.move(50, 20)
        self.btn_browse.clicked.connect(self.on_click)

        self.textbox = QLineEdit(self)
        self.textbox.move(170, 20)
        self.textbox.resize(280, 40)

        self.page_view = QLineEdit(self)
        self.page_view.move(20, 100)
        self.page_view.resize(800, 400)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')
        # self.openFileNameDialog()
        # self.saveFileDialog()

if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = App()
        sys.exit(app.exec_())

A: One possible solution is to overwrite the keyPressEvent() method to detect the desired key and use focusNextPrevChild() by passing False or True if you want the focus to go to the previous or next widget, respectively.
from PyQt5.QtCore import pyqtSlot, Qt

class App(QMainWindow):
    # ...
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Down:
            self.focusNextPrevChild(True)
        elif e.key() == Qt.Key_Up:
            self.focusNextPrevChild(False)
# ...


text:
Q: Cookiesdirective and Statcounter I have implemented cookiesdirective.js which can be found here cookiesdirective.com and Statcounter code is not working. I am using the following code (DoYourOwnSite, standard):
var sc_project=9181072;
var sc_invisible=1;
var sc_security="328a83d2";
var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www.");
document.write("<sc"+"ript type='text/javascript' src='" + scJsHost + "statcounter.com/counter/counter.js'></"+"script>");

Since cookiesdirective.js requires to remove the  tags, I have removed them, but it is still not working. On the other hand, Google Analytics code is working without a problem. I am sure it is about changing the code a bit so it will work inside another javascript, but I do not now how to do it.
Thanks,
Goran

A: Solved. I had to change the statcounter code a bit:
var sc_project=xxxxxxxxxx;
var sc_invisible=1;
var sc_security="xxxxxxxxxxx";
var imported = document.createElement('script');
imported.type = 'text/javascript';
imported.async = true;
var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www.");
imported.src = scJsHost + "statcounter.com/counter/counter_xhtml.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(imported, s);

Thanks anyway.


text:
Q: Python Cerberus JSON schema validation I have no clue why my code doesn't work, hence looking for some help.
That's my sample JSON array:
[
    {
        "bookingid": 1774
    },
    {
        "bookingid": 1020
    }
]

and my code is as follows:
def test_get_booking_ids_correct_schema():
    schema = {
        "type": "array",
        "items":
            {
                "properties":
                    {
                        "bookingid":
                            {
                                "type": "integer"
                            }
                    }
            }
    }

    response = requests.get("https://restful-booker.herokuapp.com/booking")
    response_body = response.json()

    v = Validator(schema)
    is_valid = v.validate(response_body)

    assert is_valid == True

and  the error I'm getting is as follows:
        if not self.schema_validator(test_schema, normalize=False):
>           raise SchemaError(self.schema_validator.errors)
E           cerberus.schema.SchemaError: {'items': [{'properties': ['unknown rule']}], 'type': ['must be of dict type']}

Do you see any obvious mistake in my schema?
On the contrary, the code below works perfectly fine:
def test_temp():
    schema = {"origin": {"type": "string"}}
    json = {
        "origin": "185.21.87.131"
    }

    v = Validator(schema)
    is_valid = v.validate(json)

    assert is_valid == True

A: It's not possible to validate a document which is an array as root element. As you can see on : https://github.com/pyeve/cerberus/issues/220
by the way, the type array didn't exist in the Cerberus schema, you should use list instead.


text:
Q: Returning constructor arguments in braces? I am new to C++ and the brace initialization (or uniform init) really is confusing. What exactly happens when a function returns a list of arguments in braces? Thanks a lot for claryfying.
std::vector<double> foo()
{
  return {1, 2}; // is this the same as: std::vector<double>{1, 2} or std::vector<double>(1, 2)? or something else?
}

A: return {1, 2};, the return value is list-initialized from {1, 2}, as the effect, the returned std::vector<double> contains 2 elements with value 1 and 2.
return std::vector<double>{1, 2};, the return value is copy-initialized from std::vector<double>{1, 2}, as the effect, the returned std::vector<double> contains 2 elements with value 1 and 2. In concept it'll construct a temporary std::vector<double> and the return value is copy-initialized from the temporary; because of mandatory copy elision (since C++17) the copy/move operation is ommitted and the effect is exactly the same as the 1st case.
return std::vector<double>(1, 2), the return value is copy-initialized from std::vector<double>(1, 2), as the effect, the returned std::vector<double> contains 1 elements with value 2. Mandatory copy elision takes effect in this case too.


text:
Q: JAVA: Getting the content of specific strings from text files I have a text file like this:
  text
  text
  text
  .
  .
  @data
  instances1
  instances2
  .
  .
  instancesN

I want to get the contents of this file from @data until the end of the file, how can I do?
I found this method of FileUtils (from apache commons-lang) class but it's usable only if I already know the line number.
String ln = FileUtils.readLines(new File("arff_file/"+results.get(0)))
    .get(lineNumber);

A: Since you are using Apache Commons, you can do it in one line:
String contents = FileUtils.readFileToString(new File("arff_file/"+results.get(0)), "UTF-16").replaceAll("^.*?(?=@data)", "");

This works by

*

*reading the whole file into a single String

*using regex-based replaceAll() to remove (by replacing with a blank) everything up to, but not including, @data
The regex breakdown of ^.*?(?=@data) is:

*

*^ start of input

*.*? a reluctantly quantified wildcard

*(?=@data) a positive (non-consuming) look ahead that asserts that the next input is @data
A reluctant quantifier could be important to use so it won't skip past the first @data, in case it appears more than once in the input.

A: try {
String file = "fileName";
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
    if (line.equals("@data"))
        nowRead(br);//I just do this for more efficiency, you can set a boolean flag instead
}
br.close();
}catch (IOException e) {
    //OMG Exception again!
}
}

static ArrayList<String> nowRead(BufferedReader br) throws IOException {
    ArrayList<String> s = new ArrayList<String>();// do it as you wish
    String line;
    while ((line = br.readLine()) != null) {
        s.add(line);
    }
    return s;
}

A: Path start = Paths.get("test.txt");
try
{
    List<String> lines = Files.readAllLines(start);

    for (Iterator<String> it = lines.iterator(); it.hasNext();)
    {
        String line = it.next();

        if (!"@data".equals(line.trim()))
        {
            it.remove();
        }
        else
        {
            break;
        }
    }

    System.out.println(lines);
}
catch (IOException e)
{
    e.printStackTrace();
}

I was reading about Path online so why not something like this as alternative to Bohemian code?
Maybe something could be done using stream() of Java 8 but not still nothing...


text:
Q: 302 Redirect RequestError -- Moved Temporarily - while deleting an google calendar event I try to delete an event in google calendar through my python code. Sometimes i succeed deleting but sometimes i get the below error. The problem is that it's not 100% reproducible
My Error
{'status': 302,
'body': '\n\n<TITLE>Moved Temporarily</TITLE>\n\n\n
Moved Temporarily
\nThe document has moved here.\n\n\n',
'reason': 'Redirect received, but redirects_remaining <= 0'}

My Code (just the same as api code)
def DeleteEvent(calendar_service, event):
  calendar_service.DeleteEvent(event.GetEditLink().href)

When i surfed i got to know that it's a reported issue. But i am unable to identify the status of the bug. And if the bug is fixed is there a patch or updated gdata module available. I am completely struck on how to proceed. Kindly suggest some way to fix this issue. Thanks a lot for your time and energy. :)


text:
Q: Try to parse html table in iOS I'm new in swift/iOS and I looking for best way to parse html table without WebView and display it on the screen. It is possible to do it with NSMutableAttributedString or NSAttributedString

A: You can display the HTML table using UITextView.
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
    super.viewDidLoad()
    if let data = htmlString.data(using: String.Encoding.unicode),
        let attString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil) {
        lbl.attributedText = attString
        textView.attributedText = attString
    }
}


text:
Q: How to serve images in a folder in Sailsjs? How to serve bunch of images in sails.js?
Suppose, my API server has a controller for user, to upload images and it's stored in each users' folder in server.
// Image upload
var userId = req.param('id');
req.file('image').upload({
  maxBytes: 2000000,
  // set custom upload dir path name
  dirname: require('path').resolve(sails.config.appPath, 'assets/images/', userId)
}, function whenDone(err, uploadedFiles){
  if (err) {
      return res.negotiate(err);
  }
  // if no file uploaded, response with error
  if (uploadedFiles.length === 0) {
      return res.badRequest('No file');
  } else {
      User_images.create({
         userId: userId,
         avatarFd: uploadedFiles[0].fd
      })
      .exec(function(err, result){
         if (err) {
            return res.serverError(err);
         } else {
            return res.ok('image saved');
         }
      })
  }

});

Basically, the image location successfully saved in User_images model, and the file saved in assets/images/{userid} folder. So, how can I serve all images of a particular user to a frontend application?

A: I have found the best approach for this is to save just the filename not the full file descriptor. Using your code above you can get the filename from the file descriptor using a simple regex:
// Image Upload
var userId = req.param('id');
req.file('image').upload({
  maxBytes: 2000000,
  // set custom upload dir path name
  dirname: '../../assets/images/'+userId,
}, function whenDone(err, uploadedFiles){
  if (err) {
    return res.negotiate(err);
  }
  // if no file uploaded, response with error
  if (uploadedFiles.length === 0) {
    return res.badRequest('No file');
  } else {
  // Get the file descriptor
  var f = uploadedFiles[0].fd;
  // return just the filename and use this instead
  var filename = f.replace(/^.*[\\\/]/, '');
  User_images.create({
     userId: userId,
     avatarFd: filename
  })
  .exec(function(err, result){
     if (err) {
        return res.serverError(err);
     } else {
        return res.ok('image saved');
     }
  })
  }
});

Now you can create a controller that returns images for a specific user by passing in that users id, lets call it myimages:
'myimages' : function (req, res) {
  var userId = req.param('id');
  // find images by userId
  User_images.find({userId : userId},function (err, images) {
    if(err) {
      console.log(err);
      return res.serverError('An error occured while finding images');
    }
    if(!images){
      console.log("No Images Found");
      return res.notFound();
    }
    res.view({
      images : images
    })
  });
},

In the myimages view, you can then iterate through the images, appending the userId and filename to the image src.
<% _.each(images, function(image) { %>
  <img src="/images/<%= image.userId %>/<%= image.avatarFd %>">
<% }) %>


text:
Q: Displaying Results After a Loop My class recently learned about loops and random number generators, so I wanted to try creating a game where you guessed the sum of two dice. At the end of each game, I want to show all of the user's guesses and a line that displays what the value was. My issue is displaying all the values the user inputted at the end. This is my code so far:
import java.util.Random;
import java.util.Scanner;
public class Dice2
{
   public static void main (String[] args)
   {
      Scanner kb = new Scanner(System.in);
      Random rn = new Random();
      int roll1= rn.nextInt(6)+1;
      int roll2= rn.nextInt(6)+1;
      int sum = roll1 +roll2;
      boolean retry = false;
      System.out.print("Guess a number: ");
      int guess = kb.nextInt();
      kb.nextLine();
      if (guess!=sum)
      {
         retry= true;
         while (retry)
         {
             System.out.print("Wrong, enter again: ");
             int newGuess = kb.nextInt();
             retry = true;
             if(newGuess==sum)
             {
                retry = false;
                System.out.printf("You guessed: %4d%4d\n", guess,newGuess);
                System.out.println("The number was: " + sum);
             }
             else
                continue;
         }
      }
      else
         System.out.println("The number was " + sum);
   }
}

The problem I'm getting is when I am trying to show all of the numbers the user guessed. I want to display all the guesses the user had, which is why I used the while loop. However I'm not sure how to go about displaying all the inputs the user guessed. For example if the correct answer was 8 and the user guessed 2,3,4,5,6,8 I want to be able to display something like the following:
You guessed: 2,3,4,5,6,8
The number was :8

I understand that after each iteration of the while loop I am overwriting the newGuess variable, however I am not sure what to do in order to display all numbers the user guessed. Any help or tips would be appreciated.

A: If all you want is a string with the user's guesses, use StringBuilder.
StringBuilder builder = new StringBuilder();
builder.append(5);
builder.append(",");
builder.append(4);
builder.append(",");
builder.append(9);
System.out.println(builder.toString());

Create one before the while loop, then append to it each time through the loop.

A: You could store the guessed values in a Vector. And then loop through it to show the results.


text:
Q: Serialize method of ajax not returning required values I am trying to get form inputs through ajax j query bootstrap modal and store it into the database but serialize method is not returning all the values required.
It should have returned the values of user_id and btn_action...
where did  I go wrong..??
I have tried many solutions but could not get any answer...
below are html  and javascript code. I am using all the required jquery resources.
<form method="post" id="user_form">

 Add User

  <button type="button" class="close" data-dismiss="modal">×
 </button>

Enter User Name
<input type="text" name="user_name" id="user_name" class="form-control" required />

Enter User Email

<input type="email" name="user_email" id="user_email" class="form-control" required />

Enter User Password
<input type="password" name="user_password" id="user_password" class="form-control" required />

  <input type="hidden" name="user_id" id="user_id" />
  <input type="hidden" name="btn_action" id="btn_action" />
  <input type="submit" name ="action" id= "action" class="btn btn-primary"
   value="Add" />
  <button type="button" class="btn btn-default" data-dismiss="mo
  dal">Close</button>

</form>

//script code:

$(document).on('submit', '#user_form', function(event){
event.preventDefault();
$('#action').attr('disabled','disabled');
var form_data = $('#user_form').serialize();
alert(form_data);
// console.log(form_data)
$.ajax({
url:"user_action.php",
method:"POST",
data:form_data,
success:function(data)

{
$('#user_form')[0].reset();
$('#userModal').modal('hide');
$('#alert_action').fadeIn().html('
'+data+'
');
$('#action').attr('disabled', false);## Heading ##

}
});
});

<form method="post" id="user_form">

 Add User

  <button type="button" class="close" data-dismiss="modal">×</button>

Enter User Name
<input type="text" name="user_name" id="user_name" class="form-control" required />

Enter User Email
<input type="email" name="user_email" id="user_email" class="form-control" required />

Enter User Password
<input type="password" name="user_password" id="user_password" class="form-control" required />

  <input type="hidden" name="user_id" id="user_id" />
  <input type="hidden" name="btn_action" id="btn_action" />
  <input type="submit" name ="action" id= "action" class="btn btn-primary" value="Add" />
  <button type="button" class="btn btn-default" data-dismiss="mo  dal">Close</button>

</form>

A: The two hidden inputs have no values attached to them so you will not find them in the serialized value, add some values to the inputs directly in the html or with javascript
 <input type="hidden" name="user_id" id="user_id" value="some user_id"/>
 <input type="hidden" name="btn_action" id="btn_action" value="some btn_action"/>


text:
Q: Not able to align nodes properly I have the following code:
\documentclass[11pt]{article}

\usepackage[utf8]{inputenc}

\usepackage{geometry}
\geometry{a4paper}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usetikzlibrary{calc}

\begin{document}

\begin{center}
\begin{tikzpicture}
\draw[step=2cm,color=gray] (-4.001,-6.001) grid (6,4);
\matrix[matrix of nodes,inner sep=1cm, nodes={align=center}]{
A & B & C & D & E \\
A & B & C & D & E \\
A & B & C & D & E \\
A & B & C & D & E \\
A & B & C & D & E \\};

\foreach \y in {-3, -2, -1, 0, 1, 2}
    \draw ($(-5, 2*\y)$) -- ($(-5, 2*\y)$) node {$\y$};
\foreach \x in {-2, -1, 0, 1, 2, 3}
    \draw ($(2*\x, 5)$) -- ($(2*\x, 5)$) node {$\x$};

\foreach \x in {-4, -2, 0, 2, 4, 6} {
  \foreach \y in {-6, -4, -2, 0, 2, 4}  {
    \node[draw,circle,inner sep=2pt,fill] at (\x,\y) {};
   }
}
\end{tikzpicture}
\end{center}

\end{document}

And I am trying to align the matrix such that each element of 0, A, B, ..., E is in the center of a square, but I am not able to get this to work. I don't understand why 'column sep' shifts the terms more and more.
Thanks!

A: I would do it completely with a matrix. If you set the nodes to
draw=gray, minimum size=+1cm, outer sep=+0pt, text depth=+-.5ex, text height=+1ex

you get a grid-like set of boxes. The column sep and row sep needs to bet set to -\pgflinewidth so that the nodes overlap.
The dots can then be added via two \foreach loops:
\foreach \row in {1,...,4}{
  \foreach \column in {1,...,6}
    \node at (m-\row-\column.north west) [dot]
     [if={\row==4}{insert path=node at (m-\row-\column.south west) [dot]}{}];
  \node at (m-\row-6.north east)[dot];
}
\node at (m-4-6.south east)[dot];

(This only adds one dot at each corner. Simpler loops can be constructed, they however add multiple dots at most corners.)
Code
\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
  dot/.style={fill,circle, inner sep=+0pt, minimum size=+4pt, node contents=},
]
\matrix[matrix of nodes, nodes in empty cells,
  column sep=-\pgflinewidth, row sep=-\pgflinewidth,
  nodes={draw=gray, minimum size=+1cm, outer sep=+0pt,
  text depth=+-.5ex, text height=1ex}
  ] (m) {
0 & A & B & C & D & E \\
  &   &   &   &   &   \\
  &   &   &   &   &   \\
  &   &   &   &   &   \\
};
\foreach \row in {1,...,4}{
  \foreach \column in {1,...,6}
    \node at (m-\row-\column.north west) [dot]
     [if={\row==4}{insert path=node at (m-\row-\column.south west) [dot]}{}];
  \node at (m-\row-6.north east)[dot];
}
\node at (m-4-6.south east)[dot];
\end{tikzpicture}
\end{document}

If you are feeling more adventurous, you can add these dots as part of labels of the matrix's nodes. This needs, however, two fixes:

*

*An override of the automatically selected anchor for the labels,
see How can I set the TikZ label anchor explicitly?

*As labels are nodes themselved, they also get the every node style applied. If we add those dots as labels to the every node style we would get an infinite amount of recursion. (Every label would get labels which get labels …)
For this I introduce the not if label key which argument will only get applied if the node it is used in is not a label. (For a pin a similar key can be constructed.)
Unfortunately, the labels will count to a cell's dimension, so you will either need to accommodate their sizes into the column sep and row sep or add overlay to the dot style. This might make them protrude outside of the picture if the inner seps of the matrix is smaller than half the size of the dots.
Again, the addition of the dots is done so that every dot is only drawn once.
Code
\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\makeatletter
\tikzset{not if label/.code={%
    \pgfutil@ifundefined{tikz@save@last@fig@name}{\pgfkeysalso{#1}}{}}}
\makeatother
\tikzset{
  label anchor/.style={tikz@label@post/.append style={anchor=#1}},
  label dots/.style={label={[dot,label anchor=center]#1:}},
  nw dots/.style={label dots=north west},
  sw dots/.style={label dots=south west},
  ne dots/.style={label dots=north east},
  se dots/.style={label dots=south east}}
\begin{document}
\begin{tikzpicture}[
  dot/.style={fill,circle, inner sep=+0pt, minimum size=+4pt, overlay},
]
\matrix[matrix of nodes, nodes in empty cells,
  column sep=-\pgflinewidth, row sep=-\pgflinewidth,
  nodes={not if label={
    nw dots, draw=gray, minimum size=+1cm,
    outer sep=+0pt, text depth=+-.5ex, text height=1ex}},
  column 6/.style      ={nodes={not if label=ne dots}},
  row 4/.style         ={nodes={not if label=sw dots}},
  row 4 column 6/.style={nodes={not if label=se dots}},
  ]{
0 & A & B & C & D & E \\
  &   &   &   &   &   \\
  &   &   &   &   &   \\
  &   &   &   &   &   \\
};
\end{tikzpicture}
\end{document}

Output


text:
Q: List.Find using a struct list I'm struggling with this specific topic.
I have a list of struct element which I need to use as argument in a method.
public struct MyStruct
{

    public string F1;
    public string F2;

}

List<MyStruct> NewList = new List<MyStruct>();
NewList.Add(new MyStruct { F1 = "AAA", F2 = "BBB" });
NewList.Add(new MyStruct { F1 = "CCC", F2 = "DDD" });

If I try to find on item of that list using LINQ I can use:
    var Element = NewList.Find(x => x.F1 == "AAA");
but Element returns something I cannot convert to a list?
I can use Element.F1 or Element.F2 but if I need to pass the Element itself to a method how should I do it?
Also, if I try to define Element as:
List<MyStruct> Element = NewList.Find(x => x.F1 == "AAA");

It fails! But why?
Isn't Element of that structure?
.Find searches for an element which are 2 strings defined in the struct fields F1 and F2.
If I use .FindAll the error seems to go away on the definition List<MyStruct> Element?
How can I define one single Element for NewList?
Can someone help me?
Thanks in advance

A: List<T>.Find returns with a single element and not with a List<T>. You should declare your Element variable as MyStruct:
MyStruct Element = NewList.Find(x => x.F1 == "AAA");

You should also think about that Find returns the default value of the type you store in your list when it couldn't find a matching value.


text:
Q: Website using PrimeNG not printed entirely I have an web-based app running Angular 2 and PrimeNG. The application uses an accordion as main control and renders one large canvas inside one of the accordion tabs. The entire page is so large, that the user needs to scroll down horizontally.
The requirement is to have that entire page printed as PDF. My first try was window.print(), however then only one part of the page (starting from the top) is printed and the canvas is omitted using Chrome.
Any ideas how to convert the entire web page into PDF?


text:
Q: VMware player: could not find component on update server I installed MacOS 10.15 "Catalina" on VMWare Workstation Player in Windows 10 as host.
Now I want to install VMWare Tools so I clicked Player -> Manage -> Install VMware tools but I got this error:

I am using this version of player:
VMware® Workstation 15 Player
15.5.2 build-15785246

A: You can download the latest version here:
https://packages.vmware.com/tools/releases/latest/windows/x64/
Notice this folder is for Windows x64, browse for your OS, if different.
Download to your VM and install... then close the VM to get everything in sync.


text:
Q: Laravel: injecting a dependency into an extended class I'm using the Sentinel bundle for Laravel.
The vendor class UserController has a constructor that injects a bunch of dependencies into it that looks like this:
<?php namespace Sentinel;

use Sentinel\Repo\User\UserInterface;
use Sentinel\Repo\Group\GroupInterface;
use Sentinel\Service\Form\Register\RegisterForm;
use Sentinel\Service\Form\User\UserForm;
use Sentinel\Service\Form\ResendActivation\ResendActivationForm;
use Sentinel\Service\Form\ForgotPassword\ForgotPasswordForm;
use Sentinel\Service\Form\ChangePassword\ChangePasswordForm;
use Sentinel\Service\Form\SuspendUser\SuspendUserForm;
use BaseController, View, Input, Event, Redirect, Session, Config;

class UserController extends BaseController {

    protected $user;
    protected $group;
    protected $registerForm;
    protected $userForm;
    protected $resendActivationForm;
    protected $forgotPasswordForm;
    protected $changePasswordForm;
    protected $suspendUserForm;

    /**
     * Instantiate a new UserController
     */
    public function __construct(
        UserInterface $user,
        GroupInterface $group,
        RegisterForm $registerForm,
        UserForm $userForm,
        ResendActivationForm $resendActivationForm,
        ForgotPasswordForm $forgotPasswordForm,
        ChangePasswordForm $changePasswordForm,
        SuspendUserForm $suspendUserForm)
    {
        $this->user = $user;
        $this->group = $group;
        $this->registerForm = $registerForm;
        $this->userForm = $userForm;
        $this->resendActivationForm = $resendActivationForm;
        $this->forgotPasswordForm = $forgotPasswordForm;
        $this->changePasswordForm = $changePasswordForm;
        $this->suspendUserForm = $suspendUserForm;

        //Check CSRF token on POST
        $this->beforeFilter('Sentinel\csrf', array('on' => array('post', 'put', 'delete')));

        // Set up Auth Filters
        $this->beforeFilter('Sentinel\auth', array('only' => array('change')));
        $this->beforeFilter('Sentinel\inGroup:Admins', array('only' => array('show', 'index', 'create', 'destroy', 'suspend', 'unsuspend', 'ban', 'unban', 'edit', 'update')));
        //array('except' => array('create', 'store', 'activate', 'resend', 'forgot', 'reset')));
    }

// The rest of the class code...

I've created model class in my app called ExtendedUserController so that I can add functionality to the existing controller. My controller class looks like this currently:
<?php

use Sentinel\UserController;
use Sentinel\Repo\Group\SentryGroup;

class ExtendedUserController extends UserController {

// The rest of the class code...

I don't have a constructor in my class because I'm letting the parent class construct when I extend it.
I have a new model that I would like to add to my controller class. My plan was to inject the dependency in a constructor for the ExtendedUserController and then call `parent::__construct()' to allow the parent class to be extended.
I'm running into errors when loading the class and I'm still green enough to laravel and dependency injection that I'm not exactly sure how to fix it or if this is even the proper way of accomplishing the task:
<?php

use Sentinel\UserController;
use Sentinel\Repo\Group\SentryGroup;
use CustomerLinks;

class ExtendedUserController extends UserController {

    protected $customerLinks;

    public function __construct(CustomerLinks $customerLinksClass){
        $this->customerLinks = $customerLinksClass;
        parent::__construct();
    }

I'm running into the error:

Argument 1 passed to Sentinel\UserController::__construct() must be an
  instance of Sentinel\Repo\User\UserInterface, none given, called in
  /var/www/app/controllers/ExtendedUserController.php on line 15 and
  defined

If I run the parent constructor, shouldn't the parent's code automatically pass in it's dependencies as outlined in the parent class' code?
Is this not the proper way to add the dependency? Any help and explanation would be greatly appreciated.

A: I realize the error now and I wanted to add it in rather than deleting the question.
I found an earlier stackoverflow post on this issue when searching with different criteria.
I needed to

*

*Add the parent class' dependencies to my extended class, pass them into my extended classes

*Inject the dependencies into my extended class' constructor

*Pass those injected variables into the parent::__construct() call

Here's what the working code looks like:
<?php

use Sentinel\UserController;
use Sentinel\Repo\Group\SentryGroup;
use CustomerLinks;

// Parent class' dependencies
use Sentinel\Repo\User\UserInterface;
use Sentinel\Repo\Group\GroupInterface;
use Sentinel\Service\Form\Register\RegisterForm;
use Sentinel\Service\Form\User\UserForm;
use Sentinel\Service\Form\ResendActivation\ResendActivationForm;
use Sentinel\Service\Form\ForgotPassword\ForgotPasswordForm;
use Sentinel\Service\Form\ChangePassword\ChangePasswordForm;
use Sentinel\Service\Form\SuspendUser\SuspendUserForm;
use BaseController, View, Input, Event, Redirect, Session, Config;

class ExtendedUserController extends UserController {

    protected $customerLinks;

    // Injecting both the parent class' dependencies and my new dependency into the constructor
    public function __construct(CustomerLinks $customerLinksClass,UserInterface $user, GroupInterface $group, RegisterForm $registerForm, UserForm $userForm,ResendActivationForm $resendActivationForm,ForgotPasswordForm $forgotPasswordForm,ChangePasswordForm $changePasswordForm,
SuspendUserForm $suspendUserForm){
        // passing the injected variables to the parent constructor call
        parent::__construct($user, $group, $registerForm, $userForm,$resendActivationForm,$forgotPasswordForm,$changePasswordForm,$suspendUserForm);

        // Adding my new injected class into the controller class
        $this->customerLinks = $customerLinksClass;
    }

//The rest of the class code...

It was a pretty big face-palm moment. Hopefully this will help someone out in the future.


text:
Q: PowerShell Scripts to report and alert on site and subsite size Can anyone help me to write PowerShell scripts that do the following:

*

*Report and alert on site and subsite size

*Report and alert on individual file size

*Collect search statistics

A: I take it you got a good reason for doing this in PowerShell -realize that you will only get a warning/report each time you run this script unless you in the script generate event log entries or similar for other monitoring devices.
Also consider using the OOB functionality for Quota and Quota warnings where you get notifications when site collections are getting near quotas.
If you use SharePoint 2010 consider using the Health Monitoring features. Besides the OOB rules and health checks you can define your own rules. You can get output as logs or reports.
Check out the Monitoring section of SharePoint 2010 on TechNet for an overview on what you can monitor.


text:
Q: TrustStore fails to init but KeyStore successful I am trying to configure Tomcat so that my web application can use LDAPS. It all works fine on the UAT server but for some reason the production server cannot initialize the trust store.
I have turned on debugging (via -Djavax.net.debug=all) and the error is:

default context init failed: java.io.IOException: Keystore was tampered with, or password was incorrect

I am 100% sure that the password is correct, as I have run keytool and listed the contents of the truststore, as well as taken the same file from the working UAT server.
As an experiment, I configured Tomcat to use the same store file for both keystore and truststore (I realise this is not a typical setup, but from my understanding the file formats etc are the same so they should both load):
-Djavax.net.ssl.trustStorePassword=xxx
-Djavax.net.ssl.trustStore=C:\Program Files\Apache Software Foundation\Tomcat 7.0\bin\.keystore
-Djavax.net.ssl.keyStorePassword=xxx
-Djavax.net.ssl.keyStore=C:\Program Files\Apache Software Foundation\Tomcat 7.0\bin\.keystore
and the keystore works:

keyStore is : C:\Program Files\Apache Software Foundation\Tomcat 7.0\bin.keystore
  keyStore type is : jks
  keyStore provider is :
  init keystore  init keymanager of type SunX509
  ***  found key for : tomcat

whilst the truststore fails.. for the same file and password!:

trustStore is: C:\Program Files\Apache Software Foundation\Tomcat 7.0\bin.keystore
  trustStore type is : jks
  trustStore provider is :
  init truststore
  default context init failed: java.io.IOException: Keystore was tampered with, or password was incorrect

From the web application the stack trace has some more detail (whether it helps I'm not sure.. I studied the java source for TrustManagerFactoryImpl and matched it with the logging but it didn't explain the behaviour)
javax.naming.CommunicationException: <ldap url>:636 [Root exception is java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)]
    at com.sun.jndi.ldap.Connection.<init>(Unknown Source)
    at com.sun.jndi.ldap.LdapClient.<init>(Unknown Source)
    at com.sun.jndi.ldap.LdapClient.getInstance(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.connect(Unknown Source)
    at com.sun.jndi.ldap.LdapCtx.<init>(Unknown Source)
    at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(Unknown Source)
    at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(Unknown Source)
    at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(Unknown Source)
    at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(Unknown Source)
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.init(Unknown Source)
    at javax.naming.InitialContext.<init>(Unknown Source)
    at javax.naming.directory.InitialDirContext.<init>(Unknown Source)
    at com.mycompany.fde.util.LDAPHelper.initialBindSSL(LDAPHelper.java:116)
    at com.mycompany.fde.util.LDAPHelper.<init>(LDAPHelper.java:91)
    at com.mycompany.fde.util.LDAPHelper.getInstance(LDAPHelper.java:58)
    at com.mycompany.fde.server.work.StartupWork.startupStage1(StartupWork.java:224)
    at com.mycompany.fde.server.work.StartupWork.call(StartupWork.java:121)
    at com.mycompany.fde.server.work.StartupWork.call(StartupWork.java:47)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at javax.net.ssl.DefaultSSLSocketFactory.throwException(Unknown Source)
    at javax.net.ssl.DefaultSSLSocketFactory.createSocket(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.jndi.ldap.Connection.createSocket(Unknown Source)
    ... 24 more
Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
    at java.security.Provider$Service.newInstance(Unknown Source)
    at sun.security.jca.GetInstance.getInstance(Unknown Source)
    at sun.security.jca.GetInstance.getInstance(Unknown Source)
    at javax.net.ssl.SSLContext.getInstance(Unknown Source)
    at javax.net.ssl.SSLContext.getDefault(Unknown Source)
    at javax.net.ssl.SSLSocketFactory.getDefault(Unknown Source)
    ... 29 more
Caused by: java.io.IOException: Keystore was tampered with, or password was incorrect
    at sun.security.provider.JavaKeyStore.engineLoad(Unknown Source)
    at sun.security.provider.JavaKeyStore$JKS.engineLoad(Unknown Source)
    at java.security.KeyStore.load(Unknown Source)
    at sun.security.ssl.TrustManagerFactoryImpl.getCacertsKeyStore(Unknown Source)
    at sun.security.ssl.SSLContextImpl$DefaultSSLContext.getDefaultTrustManager(Unknown Source)
    at sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    ... 35 more
Caused by: java.security.UnrecoverableKeyException: Password verification failed
    ... 45 more

I'm at a complete loss - any help/ideas would be much appreciated!

A: Thanks everyone for your help, I finally found that for some unknown reason, someone had indeed set the truststore password in Catalina.properties (via javax.net.ssl.trustStorePassword).  It seems that this takes priority even over the java variables set in the Tomcat UI :(

A: For the sake of completeness, this can also occur if the identically configured keystore file does not exist (here: erreneous file:/// prefix). It still leads to:
trustStore is: No File Available, using empty keystore.
trustStore type is : jks
trustStore provider is :
init truststore
keyStore is : file:///c:/my.jks
keyStore type is : jks
keyStore provider is :

Compared to OpenJDK 1.8.0.181, the keyStore is : line just misleadingly outputs javax.net.ssl.keyStore [1] while the given trustStore is checked for existance first [2].
[1] sun.security.ssl.SSLContextImpl
[2] sun.security.ssl.TrustManagerFactoryImpl

A: You don't need to supply the truststore password. So, don't.
NB keytool -list doesn't need the password at all, and it isn't proof you know the correct password. The error you're getting, on the other hand, is proof that the password is incorrect.
You should not use the same file for both keystore and truststore.


text:
Q: how to use preventDefault() with paste event in jquery I have a problem, i have a validation on TextBox to prevent the user to input the data more than 10 characters, i have applied the validation on keyprees but i am not able to restrict the user to paste the data with length more than 10.
i have searched and try paste event but its not working its not restricting the user to paste the value, preventDefault(); is not working.
code-
$('#EMName').bind('paste', function (e) {
        var self = $(this);
        var v = false;
        var flag = setTimeout(function () {

            var len = $(self).val().length;
            if (len > 10) {
                alert("false");
                v = false;
                return false
            }
            else {
                alert("true");
                v = true;
                return true;
            }

        }, 0);
        if (v == false)
            e.preventDefault();
});

A: This is a problem we experienced with our applications as well. It's not just pasted text, it's also various browser plugins that will pre-fill fields for you or stored form data in the browser itself that will not fire up any event.
The only way we were able to overcome this is to make a periodic checks with setInterval(), so we did not miss these events.

A: Okay so you actually wont to allow the user to Paste. If you don't the below will work
<input id="EMName" value="" onpaste="return false" maxlength="10" />

A: Essentially, you want to monitor as many events as you can for that input that allow the value to be changed. I use something similar on one of my websites, and this is what I do:
$(document).ready(function(){
    $('#target').on('propertychange keyup input paste', function(){
        var target = $(this);
        var text = target.val();
        if (text.length > 10) {
            target.val(text.substring(0, 9));
        }
    });
});

Demo
This works for typing, ctrl+v, right-click paste and most other things. I'm not sure if it will work if a browser plugin populates it.


text:
Q: How do I tell awk to use = as a separator (with white spaces removed too) Suppose I have the following file.
John=good
Tom   = ok
Tim =    excellent

I know the following let's me use = as a separator.
awk -F= '{print $1,$2}' file

This gives me the following results.
John good
Tom     ok
Tim      excellent

I would like the white spaces to be ignored, so that only the names and their performances are printed out.
One way to get around this is run another awk on the results.
awk -F= '{print$1,$2}' file | awk '{print $1,$2}'

But I wanted to know if I could do this in one awk?

A: Include them in the separator definition; it's a regexp.
jinx:1654 Z$ awk -F' *= *' '{print $1, $2}' foo.ds
John good
Tom ok
Tim excellent

A: The FS variable can be set to a regular expression.
From the AWK manual
The following table summarizes how fields are split, based on the value of FS.

FS == " "
    Fields are separated by runs of whitespace. Leading and trailing whitespace are ignored. This is the default.
FS == any single character
    Fields are separated by each occurrence of the character. Multiple successive occurrences delimit empty fields, as do leading and trailing occurrences.
FS == regexp
    Fields are separated by occurrences of characters that match regexp. Leading and trailing matches of regexp delimit empty fields.


text:
Q: Where to find wsgen tool? Where to find the wsgen tool?

A: If you mean the wsgen tool used to generate Java stubs from a WSDL file, it is included with JDK6 and located in the bin folder.

A: If you use maven, https://jax-ws-commons.dev.java.net/jaxws-maven-plugin/ is excellent.


text:
Q: Media files not appearing on a react site I am serving a react application with Nginx. I need my application to be hosted on <my_domain>/505. I am attaching the location section for your reference. The issue is that all the APIs are getting through, but nothing is displaying in the site. Also, I found that there is no media file showing up on the page sources section which is actually present in the same location as CSS and js.
I would like to know what is the right way to do this.
Thanks in advance for your time – if I've missed out anything, over-or under-emphasised a specific point let me know in the comments.

    location ^~ /static/ {
        autoindex on;
        alias /usr/share/nginx/html/8357/static/;
    }

    location ^~ /media/ {
       autoindex on;
       alias /usr/share/nginx/html/8357/static/media/;
    }

    location /505 {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
    }


text:
Q: Activar boton con javascript al clickar en un  Esto es lo que he intentado

<form action="<?php echo $result ?>">
<button id="buttone" disabled="true" style="background-color:#26a69a;" target="_blank" class="btn waves-effect waves-light" type="submit" name="action">Proceed to target site</button>
</form>

También me gustaria que fuera al clickar dos botones no uno :). Un saludo
Ahora mismo el problema de este código es que la etiqueta disabled = false no desactiva si no que sigue igual. (Da igual que pongas disabled=pepito que va a estar desactivado)
Mi codigo actual

Subscribe

Subscribe to <?php echo $refername; ?> to proceed.

Follow

Follow <?php echo $refername; ?> to proceed.

<form action="<?php echo $result["shortenedUrl"] ?>">
<button id="buttone" disabled="true" style="background-color:#26a69a;" target="_blank" class="btn waves-effect waves-light" type="submit" name="action">Proceed to target site</button>
</form>

<?php
require('inc/service.php');
require('inc/footer.php');
?>

A: Primero comentarte, que el metodo para encontrar un elemento por id es getElementById(). Aunque es más recomendable utilizar querySelector().
La solución a tu fallo:
Boton1

<form action="<?php echo $result ?>">
<button id="buttone" disabled="true" style="background-color:#26a69a;" target="_blank" class="btn waves-effect waves-light" type="submit" name="action">Proceed to target site</button>
</form>

Una manera de implementar que sean 2 o el numero de botones que quieras:
    Boton1

    Boton2

    <form action="<?php echo $result ?>">
    <button id="buttone" disabled="true" style="background-color:#26a69a;" target="_blank" class="btn waves-effect waves-light" type="submit" name="action">Proceed to target site</button>
    </form>

A: Veo algunas cosas que están mal puestas, como el onclick y el document.getElement

<form action="<?php echo $result ?>">
<button id="buttone" disabled="true" style="background-color:#26a69a;" target="_blank" class="btn waves-effect waves-light" type="submit" name="action">Proceed to target site</button>
</form>

El evento onclick lo he puesto en minúscula y en document.getElementById te sobraba un punto.