Programs & Examples On #Step

STEP (Standard for the Exchange of Product data), otherwise known as ISO 10303, provides a mechanism to describe product data throughout the life cycle of a product, independent from any particular system.

iPhone is not available. Please reconnect the device

I had the same issue with Xcode 11.6 and iOS 13.6. Unpairing the device and adding it again solved the problem.

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

According to TF 1:1 Symbols Map, in TF 2.0 you should use tf.compat.v1.Session() instead of tf.Session()

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

To get TF 1.x like behaviour in TF 2.0 one can run

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

but then one cannot benefit of many improvements made in TF 2.0. For more details please refer to the migration guide https://www.tensorflow.org/guide/migrate

Can't perform a React state update on an unmounted component

If you are fetching data from axios and the error still occurs, just wrap the setter inside the condition

let isRendered = useRef(false);
useEffect(() => {
    isRendered = true;
    axios
        .get("/sample/api")
        .then(res => {
            if (isRendered) {
                setState(res.data);
            }
            return null;
        })
        .catch(err => console.log(err));
    return () => {
        isRendered = false;
    };
}, []);

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.

So, I decided to upgrade all to latest versions:

npm -v : v12.13.0 
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2

This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.

  1. In version 4, you have to defined the task as a function, before call it as a gulp task by it's string name. In V3:

gulp.task('serve', ['sass'], function() {..});

But in V4 it should be like:

function serve() {
...
}
gulp.task('serve', gulp.series(sass));
  1. As @Arthur has mentioned, you need to change the way of passing arguments to the task function. It was like this in V3:

gulp.task('serve', ['sass'], function() { ... });

But in V4, it should be:

gulp.task('serve', gulp.series(sass));

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Many of them don't add this, especially in AWS EC2 Instance, I had the same issue and tried different solutions. Solution: one of my database URL inside the code was missing this parameter 'authSource', adding this worked for me.

mongodb://myUserName:MyPassword@ElasticIP:27017/databaseName?authSource=admin

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

  1. ReCheck Proxy Settings with following commands

    docker info | grep Proxy

  2. Check VPN Connectivity

  3. If VPN not using CHECK NET connectivity

  4. Reinsrtall Docker and repeat above steps.

  5. Enjoy

pull access denied repository does not exist or may require docker login

I solved this by inserting a language at the front of the docker image

FROM python:3.7-alpine

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Please add the JAVA_HOME in the System variable no in the user variable

  1. Create the Variable name as JAVA_HOME
  2. Please use these format in the value box --> C:\Program Files\Java\jdk(version) what you have or downloaded.

Failed to start mongod.service: Unit mongod.service not found

You are missing a 'b' I think?

sudo service mongod start

should be

sudo service mongodb start

I think this is the case?

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I got the same error and I solved this by :

  1. Apply command from cmd (run as administrator)

    git config --system --unset credential.helper

  2. And then I removed gitconfig file from C:\Program Files\Git\mingw64/etc/ location (Note: this path will be different in MAC like "/Users/username")

  3. After that use git command like git pull or git push, it asked me for username and password. applying valid username and password and git command working.

hope this will help you...

Save and load weights in keras

For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

How to debug when Kubernetes nodes are in 'Not Ready' state

Steps to debug:-

In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.

Command to check:- kubectl get pods -n kube-system

If you see any pod is crashing, check it's logs

if getting NotReady state error, verify network pod logs.

if not able to resolve with above, follow below steps:-

  1. kubectl get nodes # Check which node is not in ready state

  2. kubectl describe node nodename #nodename which is not in readystate

  3. ssh to that node

  4. execute systemctl status kubelet # Make sure kubelet is running

  5. systemctl status docker # Make sure docker service is running

  6. journalctl -u kubelet # To Check logs in depth

Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-

  1. systemctl daemon-reload
  2. systemctl restart kubelet

In case you still didn't get the root cause, check below things:-

  1. Make sure your node has enough space and memory. Check for /var directory space especially. command to check: -df -kh, free -m

  2. Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

The following structure in docker-compose.yaml will allow you to have the Dockerfile in a subfolder from the root:

version: '3'
services:
  db:
    image: postgres:11
    environment:
      - PGDATA=/var/lib/postgresql/data/pgdata
    volumes:
      - postgres-data:/var/lib/postgresql/data
    ports:
      - 127.0.0.1:5432:5432
  **web:
    build: 
      context: ".."
      dockerfile: dockerfiles/Dockerfile**
    command: ...
...

Then, in your Dockerfile, which is in the same directory as docker-compose.yaml, you can do the following:

ENV APP_HOME /home

RUN mkdir -p ${APP_HOME}

# Copy the file to the directory in the container
COPY test.json ${APP_HOME}/test.json
COPY test.py ${APP_HOME}/test.py

# Browse to that directory created above
WORKDIR ${APP_HOME}

You can then run docker-compose from the parent directory like:

docker-compose -f .\dockerfiles\docker-compose.yaml build --no-cache

How to add a new project to Github using VS Code

You can create a GitHub repo via the command line using the GitHub API. Outside of the API, there's no way to create a repo on GitHub via the command line.

Type:

curl -u 'username' https://api.github.com/user/repos -d '{"name":"projectname","description":"project desc"}'

git remote add origin [email protected]:nyeates/projectname.git

and now you can continue regular way

Angular: Cannot Get /

Check baseHref is set to "/" ( angular.cli )

    "architect": {
        "build": {
            "builder": "@angular-devkit/build-angular:browser",
            "options": {
                "baseHref": "/"

if it didn't work, check if your base href in your index.html is set to "/"

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Removing the JUnit library, and then adding it again fixed this issue for me.

Angular - ng: command not found

>> npm uninstall -g angular-cli
>> npm uninstall -g @angular/cli

>> npm cache clean

Restart you machine

then >> npm install -g @angular/cli@latest

set Path : C:\Users\admin\AppData\Roaming\npm\node_modules@angular\cli

Hope you never get 'ng' not found

How to use switch statement inside a React component?


function Notification({ text, status }) {
  return (
    <div>
      {(() => {
        switch (status) {
          case 'info':
            return <Info text={text} />;
          case 'warning':
            return <Warning text={text} />;
          case 'error':
            return <Error text={text} />;
          default:
            return null;
        }
      })()}
    </div>
  );
}

Vuex - Computed property "name" was assigned to but it has no setter

I was facing exact same error

Computed property "callRingtatus" was assigned to but it has no setter

here is a sample code according to my scenario

computed: {

callRingtatus(){
            return this.$store.getters['chat/callState']===2
      }

}

I change the above code into the following way

computed: {

callRingtatus(){
       return this.$store.state.chat.callState===2
    }
}

fetch values from vuex store state instead of getters inside the computed hook

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

Fixing a systemd service 203/EXEC failure (no such file or directory)

To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.

#!/bin/bash

python -u alwayson.py    

Constraint Layout Vertical Align Center

Two buttons one centered one below to the left of it

Showing it graphically.

Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.

Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

I had a similar problem:

module cv2 has no attribute "cv2.TrackerCSRT_create"

My Python version is 3.8.0 under Windows 10. The problem was the opencv version installation.

So I fixed this way (cmd prompt with administrator privileges):

  1. Uninstalled opencv-python: pip uninstall opencv-python
  2. Installed only opencv-contrib-python: pip install opencv-contrib-python

Anyway you can read the following guide:

https://github.com/skvark/opencv-python

Run bash command on jenkins pipeline

If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:

Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)

Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

There are three ways to solve this issue.

  1. Ignore Precompiled Headers #1
    Steps: Project > Properties > Configuration Properties > C/C++ > Command Line > in the Additional Options box add /Y-. (Screenshot of Property Pages) > Ok > Remove #include "stdafx.h"
  2. Ignore Precompiled Headers #2
    Steps: File > New > Project > ... > In the Application Wizard Window click Next > Uncheck the Precompiled Header box > Finish > Remove #include "stdafx.h"
  3. Reinstall Visual Studio
    This also worked for me, because I realized that maybe there was something wrong with my Windows SDK. I was using Windows 10, but with Windows SDK 8.1. You may have this problem as well.
    Steps: Open Visual Studio Installer > Click on the three-lined Menu Bar > Uninstall > Restart your computer > Open Visual Studio Installer > Install what you want, but make sure you install only the latest Windows SDK 10, not multiple ones nor the 8.1.

    The first time I installed Visual Studio, I would get an error stating that I needed to install Windows SDK 8.1. So I did, through Visual Studio Installer's Modify option. Perhaps this was a problem because I was installed it after Visual Studio was already installed, or because I needed SDK 10 instead. Just to be safe I did a complete reinstall.

How to enable Google Play App Signing

While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...

When building .aab file you get prompted for the location to store key export path as below:

enter image description here
enter image description here In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.

Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing enter image description here

you will find the Google App Signing Certification window ACCEPT it.

After that you will find three radio button select **

Upload a key exported from Android Studio radio button

**, it will expand you APP SIGNING PRIVATE KEY button as below

enter image description here

click on the button and choose the .pepk file (We Stored while generating .aab file as above)

Read the all other option and submit.

Once Successfully you can go back to app release and browse the .aab file and complete RollOut...

@Ambilpura

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

Jenkins pipeline if else not working

It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

stage ('Test 3: Master') {
    when { branch 'master' }
    steps { 
        echo 'I only execute on the master branch.' 
    }
}

stage ('Test 3: Dev') {
    when { not { branch 'master' } }
    steps {
        echo 'I execute on non-master branches.'
    }
}

How to predict input image using trained model in Keras?

You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

Angular cli generate a service and include the provider in one step

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts

Visual Studio 2017 - Git failed with a fatal error

I ran into this issue as well. I had sync'd my code earlier in the day so it made no sense that it suddenly gave this Git error. Restarting Visual Studio did not make any difference. After reviewing the above answers and not finding any clear solution, I decided to try syncing outside of Visual Studio using TortoiseGit which I already had installed. This worked. I was then able to sync within Visual Studio normally. If you don't already have TortoiseGit, you may download it (free) from tortoisegit.org.

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)
#!/usr/bin/python3

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

I happen to be consulting for a Fortune 500 company and it's sadly Windows 7 and no administrator privileges. Thus Node.js, Npm, Visual Studio Code, etc.. were pushed to my machine - I cannot change a lot, etc...

For this computer running Windows 7:

Below are my new settings. The one not working is commented out.

{
    "update.channel": "none",
    "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
    //"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe"
}

How to set and reference a variable in a Jenkinsfile

The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

So in your case:

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.FILENAME = readFile 'output.txt'
                }
                echo "${env.FILENAME}"
            }
        }
    }
}

How can I regenerate ios folder in React Native project?

UPDATE 2020. React Native 0.63.3 no longer support this command react-native eject. Also react-native upgrade responsible for - Upgrade your app's template files to the specified or latest npm version using rn-diff-purge project.

Available options can be found thought this command react-native --help

Jenkins: Can comments be added to a Jenkinsfile?

The official Jenkins documentation only mentions single line commands like the following:

// Declarative //

and (see)

pipeline {
    /* insert Declarative Pipeline here */
}

The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:

/* a standalone multiline comment
   spanning two lines */
println "hello" /* a multiline comment starting
                   at the end of a statement */
println 1 /* one */ + 2 /* two */

or

/**
 * such a nice comment
 */

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Unable to set default python version to python3 in ubuntu

Just follow these steps to help change the default python to the newly upgrade python version. Worked well for me.

  • sudo apt-install python3.7 Install the latest version of python you want
  • cd /usr/bin Enter the root directory where python is installed
  • sudo unlink python or sudo unlink python3 . Unlink the current default python
  • sudo ln -sv /usr/bin/python3.7 python Link the new downloaded python version
  • python --version Check the new python version and you're good to go

denied: requested access to the resource is denied : docker

This answer is as much for my future self as for anyone else. I have encountered this exact problem when I am logged in correctly, but I am attempting to push to a private repo when my number of private repos is greater than or equal to the limit allowed by my plan.

I'm not exactly sure how I was able to create too many private repos, but if my plan includes 5 private repos, and somehow I have 6, then this is the error that I will receive:

denied: requested access to the resource is denied

In my case it's possible that I ended up with too many private repositories because I have my default visibility set to private:

Default Visibility

This is where you determine how many private repos you can have:

Billing Plans

Once I made the problematic repo public, the issue became apparent:

Make Repository Private 5 of 5

Bootstrap 4 responsive tables won't take up 100% width

Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

just wrap table with .table-responsive{-sm|-md|-lg|-xl}

for example

<div class="table-responsive-md">
    <table class="table">
    </table>
</div>

bootstrap 4 tables

Getting json body in aws Lambda via API gateway

You may have forgotten to define the Content-Type header. For example:

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ items }),
  }

How to refresh a Page using react-route Link

I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:

function refreshPage() {
    setTimeout(()=>{
        window.location.reload(false);
    }, 500);
    console.log('page to reload')
}

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

How to upgrade Angular CLI project?

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

See the reference https://github.com/angular/angular-cli

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

Vue 2 - Mutating props vue-warn

If you're using Lodash, you can clone the prop before returning it. This pattern is helpful if you modify that prop on both the parent and child.

Let's say we have prop list on component grid.

In Parent Component

<grid :list.sync="list"></grid>

In Child Component

props: ['list'],
methods:{
    doSomethingOnClick(entry){
        let modifiedList = _.clone(this.list)
        modifiedList = _.uniq(modifiedList) // Removes duplicates
        this.$emit('update:list', modifiedList)
    }
}

VMware Workstation and Device/Credential Guard are not compatible

Well Boys and Girls after reading through the release notes for build 17093 in the wee small hours of the night, I have found the change point that affects my VMware Workstation VM's causing them not to work, it is the Core Isolation settings under Device Security under windows security (new name for windows defender page) in settings.

By default it is turned on, however when I turned it off and restarted my pc all my VMware VM's resumed working correctly. Perhaps a by device option could be incorporated in the next build to allow us to test individual devices / Apps responses to allow the core isolation to be on or off per device or App as required .

Jenkins: Cannot define variable in pipeline stage

The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.

Angular 2 : No NgModule metadata found

I'll give you few suggestions.Remove all these as mentioned below

1)<script src="polyfills.bundle.js"></script>(index.html)  //<<<===not sure as Angular2.0 final version doesn't require this.

2)platform.bootstrapModule(App); (main.ts)

3)import { NgModule } from '@angular/core'; (app.ts)

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How to add multiple columns to pandas dataframe in one assignment?

if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It's based on the second variant of the accepted answer.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How to sort dates from Oldest to Newest in Excel?

I figured it out!

Follow these steps:

  1. Highlight the dates you want to filter
  2. Switch from "date" format to "number" format. You'll get a weird number, but that's Ok.
  3. That's when you sort from "smallest to largest"
  4. Now switch it back to "date" format

You're welcome!

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

This may work

CREATE USER 'user'@'localhost' IDENTIFIED BY 'pwd';

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

Conditional step/stage in Jenkins pipeline

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       

how to get docker-compose to use the latest image from repository

If the docker compose configuration is in a file, simply run:

docker-compose -f appName.yml down && docker-compose -f appName.yml pull && docker-compose -f appName.yml up -d

How to markdown nested list items in Bitbucket?

Use 4 spaces.

# Unordered list

* Item 1
* Item 2
* Item 3
    * Item 3a
    * Item 3b
    * Item 3c

# Ordered list

1. Step 1
2. Step 2
3. Step 3
    1. Step 3.1
    2. Step 3.2
    3. Step 3.3

# List in list

1. Step 1
2. Step 2
3. Step 3
    * Item 3a
    * Item 3b
    * Item 3c

Here's a screenshot from that updated repo:

screenshot

Thanks @Waylan, your comment was exactly right.

Jenkins "Console Output" log location in filesystem

You can install this Jenkins Console log plugin to write the log in your workspace as a post build step.

You have to build the plugin yourself and install the plugin manually.

Next, you can add a post build step like that:

enter image description here

With an additional post build step (shell script), you will be able to grep your log.

I hope it helped :)

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

you should be sure

to add this line at your manifest

https://developer.android.com/studio/run/index.html#instant-run

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Go to Android SDK Manager and install the latest version of below two libraries

  1. Google Play Services
  2. Google Repository

git status (nothing to commit, working directory clean), however with changes commited

I had the same issue because I had 2 .git folders in the working directory.

Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git folders, and, if so, deleting one of them.

That allowed me to upload the project successfully.

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

react-native: command not found

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install yarn
brew install node
brew install watchman
brew tap AdoptOpenJDK/openjdk
brew cask install adoptopenjdk8
npm install -g react-native-cli

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Angular 2: import external js file into component

Ideally you need to have .d.ts file for typings to let Linting work.

But It seems that d3gauge doesn't have one, you can Ask the developers to provide and hope they will listen.


Alternatively, you can solve this specific issue by doing this

declare var drawGauge: any;

import '../../../../js/d3gauge.js';
export class MemMonComponent {
    createMemGauge() {
        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js
    }
}

If you use it in multiple files, you can create a d3gauage.d.ts file with the content below

declare var drawGauge: any;

and reference it in your boot.ts (bootstrap) file at the top, like this

///<reference path="../path/to/d3gauage.d.ts"/>

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

How to sum the values of one column of a dataframe in spark/scala

Not sure this was around when this question was asked but:

df.describe().show("columnName")

gives mean, count, stdtev stats on a column. I think it returns on all columns if you just do .show()

How to run bootRun with spring profile via gradle task

Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.

def profiles = 'prod'

bootRun {
  args = ["--spring.profiles.active=" + profiles]
}

To run dev:

./gradlew bootRun -Pdev

To add dependencies on your task you can do something like this:

task setDevProperties(dependsOn: bootRun) << {
  doFirst {
    System.setProperty('spring.profiles.active', profiles)
  }
}

There are lots of ways achieving this in Gradle.

Edit:

Configure separate configuration files per environment.

if (project.hasProperty('prod')) {
  apply from: 'gradle/profile_prod.gradle'
} else {
  apply from: 'gradle/profile_dev.gradle'
}

Each configuration can override tasks for example:

def profiles = 'prod'
bootRun {
  systemProperty "spring.profiles.active", activeProfile
}

Run by providing prod flag in this case just like that:

./gradlew <task> -Pprod

Running stages in parallel with Jenkins workflow / pipeline

As @Quartz mentioned, you can do something like

stage('Tests') {
    parallel(
        'Unit Tests': {
            container('node') {
                sh("npm test --cat=unit")
            }
        },
        'API Tests': {
            container('node') {
                sh("npm test --cat=acceptance")
            }
        }
    )
}

Connection refused on docker container

Command EXPOSE in your Dockerfile lets you bind container's port to some port on the host machine but it doesn't do anything else. When running container, to bind ports specify -p option.

So let's say you expose port 5000. After building the image when you run the container, run docker run -p 5000:5000 name. This binds container's port 5000 to your laptop/computers port 5000 and that portforwarding lets container to receive outside requests.

This should do it.

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

How do I add a custom script to my package.json file that runs a javascript file?

Steps are below:

  1. In package.json add:

    "bin":{
        "script1": "bin/script1.js" 
    }
    
  2. Create a bin folder in the project directory and add file runScript1.js with the code:

    #! /usr/bin/env node
    var shell = require("shelljs");
    shell.exec("node step1script.js");
    
  3. Run npm install shelljs in terminal

  4. Run npm link in terminal

  5. From terminal you can now run script1 which will run node script1.js

Reference: http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm

Solving sslv3 alert handshake failure when trying to use a client certificate

The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.

Once changing this value to DEFAULT, run the following command:

/usr/bin/update-crypto-policies --set DEFAULT

Rerun the curl command and it should work.

How to Extract Year from DATE in POSTGRESQL

You may try to_char(now()::date, 'yyyy')
If text, you've to cast your text to date to_char('2018-01-01'::date, 'yyyy')

See the PostgreSQL Documentation Data Type Formatting Functions

TensorFlow: "Attempting to use uninitialized value" in variable initialization

run both:

sess.run(tf.global_variables_initializer())

sess.run(tf.local_variables_initializer())

No 'Access-Control-Allow-Origin' header in Angular 2 app

If you are creating a mock-up with SoapUI,a free testing tool for REST and SOAP request and response, for Angular 2+ application you should remember to set inside your http header request

 Access-Control-Allow-Origin :  *

I add two images for helping your insert. The first shows the header you should add. If you want to add the header before you have to click the plus button(it's green).

First image

The second image shows the insert the *. The value * permits to accept all the request from different hosts.

Second image

After this work my Angular application removed this annoying error in my console.

error inside console

A big recourse that helped me to understand for creating my first mock up is this video. It will help you for creating a new mock-up inside SoapUi's environment without a server-side.

How to create multiple output paths in Webpack config

The problem is already in the language:

  • entry (which is a object (key/value) and is used to define the inputs*)
  • output (which is a object (key/value) and is used to define outputs*)

the idea to differentiate the output based on limited placeholder like '[name]' defines limitations.

I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.

All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.

Although this comment doesn't help much but we can learn from our mistakes by pointing at them.

Vinod Kumar: Good workaround, its:

module.exports = {
   plugins: [
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [
            {source: 'www', destination: './vinod test 1/'},
            {source: 'www', destination: './vinod testing 2/'},
            {source: 'www', destination: './vinod testing 3/'},
          ],
        },
      }
    }),
  ],
};

BTW. this is my first comment on stackoverflow (after 10 years as a programmer) and stackoverflow sucks in usability, like why is there so much text everywhere ? my eyes are bleeding.

How to force Docker for a clean build of an image

The command docker build --no-cache . solved our similar problem.

Our Dockerfile was:

RUN apt-get update
RUN apt-get -y install php5-fpm

But should have been:

RUN apt-get update && apt-get -y install php5-fpm

To prevent caching the update and install separately.

See: Best practices for writing Dockerfiles

How to count duplicate rows in pandas dataframe?

df.groupby(df.columns.tolist()).size().reset_index().\
    rename(columns={0:'records'})

   one  two  records
0    1    1        2
1    1    2        1

Display number always with 2 decimal places in <input>

Use currency filter with empty symbol ($)

{{val | currency:''}}

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

I erroneously created Dockerfile.txt in my working directory leading to the above-mentioned error while build

The fix was to remove the .txt extension from the file.

The file name should be Dockerfile only without any extension.

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Build and Install unsigned apk on device without the development server?

I found a solution changing buildTypes like this:

buildTypes {
  release {
    signingConfig signingConfigs.release
  }
}

Angular: conditional class with *ngClass

You should use something ([ngClass] instead of *ngClass) like that:

<ol class="breadcrumb">
  <li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
  (...)

Eclipse not recognizing JVM 1.8

Here are steps:

  • download 1.8 JDK from this site
  • install it
  • copy the jre folder & paste it in "C:\Program Files (x86)\EclipseNeon\"
  • rename the folder to "jre"
  • start the eclipse again

It should work.

Async await in linq select

With current methods available in Linq it looks quite ugly:

var tasks = items.Select(
    async item => new
    {
        Item = item,
        IsValid = await IsValid(item)
    });
var tuples = await Task.WhenAll(tasks);
var validItems = tuples
    .Where(p => p.IsValid)
    .Select(p => p.Item)
    .ToList();

Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

On running node server shows Following Errors and solutions:

nodemon server.js

[nodemon] 1.17.2

[nodemon] to restart at any time, enter rs

[nodemon] watching: .

[nodemon] starting node server.js

[nodemon] Internal watch failed: watch /home/aurum304/jin ENOSPC

sudo pkill -f node

or

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Passing data to components in vue.js

A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.

index.html:

<script>
    var rspData; // global - transfer data between components
</script>

Ammlogin.vue:

....    
export default {
data: function() {return vueData}, 
methods: {
    login: function(event){
        event.preventDefault(); // otherwise the page is submitted...
        vueData.errortxt = "";
        axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
            .then(function (response) {
                vueData.user = '';
                vueData.password = '';
                // activate v-link via JS click...
                // JSON.parse is not needed because it is already an object
                if (response.data.result === "ok") {
                    rspData = response.data; // set global rspData
                    document.getElementById("loginid").click();
                } else {
                    vueData.errortxt = "Felaktig avändare eller lösenord!"
                }
            })
            .catch(function (error) {
                // Wu oh! Something went wrong
                vueData.errortxt = error.message;
            });
    },
....

Options.vue:

<template>
<main-layout>
  <p>Alternativ</p>
  <p>Resultat: {{rspData.result}}</p>
  <p>Meddelande: {{rspData.data}}</p>
  <v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
 import MainLayout from '../layouts/Main.vue'
 import VLink from '../components/VLink.vue'
 var optData = { rspData: rspData}; // rspData is global
 export default {
   data: function() {return optData},
   components: {
     MainLayout,
     VLink
   }
 }
</script>

How can I move HEAD back to a previous location? (Detached head) & Undo commits

The question can be read as:

I was in detached-state with HEAD at 23b6772 and typed git reset origin/master (because I wanted to squash). Now I've changed my mind, how do I go back to HEAD being at 23b6772?

The straightforward answer being: git reset 23b6772

But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD and was Googling to see if there were any kind of shorthand.

It turns out there is!

git reset - (or in my case git cherry-pick -)

Which incidentally was the same as cd - to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.

Angular2 QuickStart npm start is not working correctly

I had the same error on windows 10. It looks like it's problem with concurrently npm package. I found 2 options how to solve this error:

  • 1. Run both commands in 2 separate cmds:

    • in the first one run: npm run tsc:w
    • in the second one: npm run lite
  • 2. Change package.json

    • just change the start option to this: "start": "tsc && npm run tsc:w | npm run lite",

Cannot install signed apk to device manually, got error "App not installed"

Above shubham soni answer works for me,actually it happens to android version >=5.0.In above you able to install just use this while creating your apkenter image description here...

Find nginx version?

My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v if you just want that...

A column-vector y was passed when a 1d array was expected

With neuraxle, you can easily solve this :

p = Pipeline([
   # expected outputs shape: (n, 1)
   OutputTransformerWrapper(NumpyRavel()), 
   # expected outputs shape: (n, )
   RandomForestRegressor(**RF_tuned_parameters)
])

p, outputs = p.fit_transform(data_inputs, expected_outputs)

Neuraxle is a sklearn-like framework for hyperparameter tuning and AutoML in deep learning projects !

Allow 2 decimal places in <input type="number">

On input:

step="any"
class="two-decimals"

On script:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

Failed to authenticate on SMTP server error using gmail

This is how I solved this issue:

  1. Change the .env file as follow

Screenshot Reference

  1. Never forget to restart the server after you change the .env file

How to set adaptive learning rate for GradientDescentOptimizer?

Tensorflow provides an op to automatically apply an exponential decay to a learning rate tensor: tf.train.exponential_decay. For an example of it in use, see this line in the MNIST convolutional model example. Then use @mrry's suggestion above to supply this variable as the learning_rate parameter to your optimizer of choice.

The key excerpt to look at is:

# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
batch = tf.Variable(0)

learning_rate = tf.train.exponential_decay(
  0.01,                # Base learning rate.
  batch * BATCH_SIZE,  # Current index into the dataset.
  train_size,          # Decay step.
  0.95,                # Decay rate.
  staircase=True)
# Use simple momentum for the optimization.
optimizer = tf.train.MomentumOptimizer(learning_rate,
                                     0.9).minimize(loss,
                                                   global_step=batch)

Note the global_step=batch parameter to minimize. That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains.

Docker error cannot delete docker container, conflict: unable to remove repository reference

you can use -f option to force delete the containers .

sudo docker rmi -f training/webapp

You may stop the containers using sudo docker stop training/webapp before deleting

How to use refs in React with Typescript

To use the callback style (https://facebook.github.io/react/docs/refs-and-the-dom.html) as recommended on React's documentation you can add a definition for a property on the class:

export class Foo extends React.Component<{}, {}> {
// You don't need to use 'references' as the name
references: {
    // If you are using other components be more specific than HTMLInputElement
    myRef: HTMLInputElement;
} = {
    myRef: null
}
...
 myFunction() {
    // Use like this
    this.references.myRef.focus();
}
...
render() {
    return(<input ref={(i: any) => { this.references.myRef = i; }}/>)
}

npm install -g less does not work: EACCES: permission denied

enter image description hereUse sudo -i to switch to $root, then execute npm install -g xxxx

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

had the same issue as described by @scottyab.

all references were 8.4.0 but it failed due to a reference to app-measurement 8.3.0 that i did not reference anywhere (but one of the dependencies?). you can see the problem if you hover over the bad(red) dependency in Android Studio. explicitly adding

compile 'com.google.android.gms:play-services-measurement:8.4.0'

to app.gradle solved the issue.

How to run TypeScript files from command line?

Like Zeeshan Ahmad's answer, I also think ts-node is the way to go. I would also add a shebang and make it executable, so you can just run it directly.

  1. Install typescript and ts-node globally:

    npm install -g ts-node typescript
    

    or

    yarn global add ts-node typescript
    
  2. Create a file hello with this content:

    #!/usr/bin/env ts-node-script
    
    import * as os from 'os'
    
    function hello(name: string) {
        return 'Hello, ' + name
    }
    const user = os.userInfo().username
    console.log(`Result: ${hello(user)}`)
    

    As you can see, line one has the shebang for ts-node

  3. Run directly by just executing the file

    $ ./hello
    Result: Hello, root
    

Some notes:


Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script instead of ts-node, link to issues in ts-node.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

You need to install the es2015 preset:

npm install babel-preset-es2015

and then configure babel-loader:

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015']
    }
}

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

In my case, I got the error when I had my Web Application in 4.5.2 and the referenced class libaries in 4.6.1. When I updated the Web Application to 4.5.2 version the error went away.

How do I connect to my existing Git repository using Visual Studio Code?

Another option is to use the built-in Command Palette, which will walk you right through cloning a Git repository to a new directory.

From Using Version Control in VS Code:

You can clone a Git repository with the Git: Clone command in the Command Palette (Windows/Linux: Ctrl + Shift + P, Mac: Command + Shift + P). You will be asked for the URL of the remote repository and the parent directory under which to put the local repository.

At the bottom of Visual Studio Code you'll get status updates to the cloning. Once that's complete an information message will display near the top, allowing you to open the folder that was created.

Note that Visual Studio Code uses your machine's Git installation, and requires 2.0.0 or higher.

Foreach with JSONArray and JSONObject

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}

Scroll to the top of the page after render in react.js

None of the above answers is currently working for me. It turns out that .scrollTo is not as widely compatible as .scrollIntoView.

In our App.js, in componentWillMount() we added

this.props.history.listen((location, action) => {
        setTimeout(() => { document.getElementById('root').scrollIntoView({ behavior: "smooth" }) }, 777)
    })

This is the only solution that is working universally for us. root is the ID of our App. The "smooth" behavior doesn't work on every browser / device. The 777 timeout is a bit conservative, but we load a lot of data on every page, so through testing this was necessary. A shorter 237 might work for most applications.

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

Difference between Spring MVC and Spring Boot

Spring MVC and Spring Boot are well described in other answers, and so without repeating that, let me jump straight to the specifics. Spring Boot and Spring MVC are not comparable or mutually exclusive. If you want to do web application development using Spring, you would use Spring MVC anyway. Your question then becomes whether to use Spring Boot or not.

For developing common Spring applications or starting to learn Spring, I think using Spring Boot would be recommended. It considerably eases the job, is production ready and is rapidly being widely adopted.

I have seen sometimes beginners asking this question because in STS (Spring Tool Suite) there are two wizards: one for creating a Spring Boot project, and another for creating a Spring MVC project. So, my recommendation would be to create a Spring Boot project and choose Web as a module in that.

Error: Execution failed for task ':app:clean'. Unable to delete file

I solved it by global searching the missing directory in the project. then delete any files containing that keyword. it can clean successfully after I remove all the build and .externalNativeBuild directories manually.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

The target principal name is incorrect. Cannot generate SSPI context

In my Case since I was working in my development environment, someone had shut down the Domain Controller and Windows Credentials couldn't be authenticated. After turning on the Domain Controller, the error disappeared and everything worked just fine.

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

It works for me.

git remote add origin https://github.com/repo.git
git push origin master

add the repository URL to the origin in the local working directory

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit https://console.cloud.google.com/apis/credentials
  2. Click on CREATE CREDENTIALS
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

Eclipse: How to install a plugin manually?

  1. Download your plugin
  2. Open Eclipse
  3. From the menu choose: Help / Install New Software...
  4. Click the Add button
  5. In the Add Repository dialog that appears, click the Archive button next to the Location field
  6. Select your plugin file, click OK

You could also just copy plugins to the eclipse/plugins directory, but it's not recommended.

Java - Check Not Null/Empty else assign default value

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
    return value == null ? defaultValue : value;
}

Installing ADB on macOS

Option 3 - Using MacPorts

Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:

  1. Install the Android SDK:

    sudo port install android
    
  2. Run the SDK manager:

    sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. As @brismuth suggested, uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

    echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

Delay/Wait in a test case of Xcode UI testing

In my case sleep created side effect so I used wait

let _ = XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)

SQL Developer with JDK (64 bit) cannot find JVM

Installing jdk1.8.0_211 and setting the below variable in product.conf (located in C:\Users\\AppData\Roaming\sqldeveloper\19.1.0) to JDK8 home worked for me

SetJavaHome D:\jdk1.8.0_211

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

Easiest way to use SVG in Android?

First you need to import svg files by following simple steps.

  1. Right click on drawable
  2. Click new
  3. Select Vector Asset

If image is available in your computer then select local svg file. After that select the image path and an option to change the size of the image is also available at the right side of dialog if you want to . in this way svg image is imported in your project After that for using this image use the same procedure

@drawable/yourimagename

wget ssl alert handshake failure

I was having this problem on Ubuntu 12.04.3 LTS (well beyond EOL, I know...) and got around it with:

sudo apt-get update && sudo apt-get install ca-certificates

How to run a program in Atom Editor?

You can try to use the runner in atom Hit Ctrl+R (Alt+R on Win/Linux) to launch the runner for the active window. Hit Ctrl+Shift+R (Alt+Shift+R on Win/Linux) to run the currently selected text in the active window. Hit Ctrl+Shift+C to kill a currently running process. Hit Escape to close the runner window

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

Go doing a GET request and building the Querystring

Use r.URL.Query() when you appending to existing query, if you are building new set of params use the url.Values struct like so

package main

import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    // if you appending to existing query this works fine 
    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    // or you can create new url.Values struct and encode that like so
    q := url.Values{}
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

How to copy file from host to container using Dockerfile

I was able to copy a file from my host to the container within a dockerfile as such:

  1. Created a folder on my c driver --> c:\docker
  2. Create a test file in the same folder --> c:\docker\test.txt
  3. Create a docker file in the same folder --> c:\docker\dockerfile
  4. The contents of the docker file as follows,to copy a file from local host to the root of the container: FROM ubuntu:16.04

    COPY test.txt /

  5. Pull a copy of ubuntu from docker hub --> docker pull ubuntu:16.04
  6. Build the image from the dockerfile --> docker build -t myubuntu c:\docker\
  7. Build the container from your new image myubuntu --> docker run -d -it --name myubuntucontainer myubuntu "/sbin/init"
  8. Connect to the newly created container -->docker exec -it myubuntucontainer bash
  9. Check if the text.txt file is in the root --> ls

You should see the file.

Run a command shell in jenkins

This is happens because Jenkins is not aware about the shell path. In Manage Jenkins -> Configure System -> Shell, set the shell path as

  • C:\Windows\system32\cmd.exe

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

ngrok command not found

I have also faced this issue on my MacOS, I used these simple steps and it worked for me.

Just open the terminal and go to your project folder where you what to start ngrok and then unzip downloaded file.

$ unzip /path/to/ngrok.zip

After doing this you don't need to authenticate ngrok, just run this command:

./ngrok  http 80

It should work now.

How to install Intellij IDEA on Ubuntu?

Recent IntelliJ versions allows automatic creation of desktop entry. See this gist

  1. Launch from commandline. If launching for the first time, setup will ask about creating a desktop launcher icon; say yes. Or else after launching (ie. from the commandline) any time, use the IDEA menu Configure > Create Desktop Entry . That should create /usr/share/applications/intellij-idea-community.desktop
  2. Trigger the Ubuntu desktop search (ie. Windows key), find the Intellij IDEA you used to create the desktop entry.
  3. Drag the icon it's showing into the Ubuntu Launcher.

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

Open the ~/.bashrc file using vi/vim $ vi ~/.bashrc

Enter the following by pressing i to insert:

code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}

Save the file using :wq

Reflect the settings in ~/.bashrc using the following command:

source ~/.bashrc

Android transparent status bar and actionbar

It supports after KITKAT. Just add following code inside onCreate method of your Activity. No need any modifications to Manifest file.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Window w = getWindow(); // in Activity's onCreate() for instance
                w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }

cURL error 60: SSL certificate: unable to get local issuer certificate

All of the answers are correct ; but the most important thing is You have to find the right php.ini file. check this command in cmd " php --ini " is not the right answer for finding the right php.ini file.

if you edit

curl.cainfo ="PATH/cacert.pem"

and check

var_dump(openssl_get_cert_locations()); 

then curl.cainfo should have a value. if not then that's not right php.ini file;

*I recommend you to search *.ini in wamp/bin or xxamp/bin or any server you use and change them one by one and check it. *

Access denied for user 'homestead'@'localhost' (using password: YES)

Two way to solve it

First way (Not recommended)

Open your database config file (laravel_root/config/database.php) & search for the below code block.

        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'blog'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),

Change the code block as below

        'host'      => 'yourHostName',
        'database'  => 'YourDatabastName',
        'username'  => 'YoutDatabaseUsername',
        'password'  => 'YourDatabasePassword',

Second way (Recommended by Laravel)

Check your Laravel root there have a file call .env if not exist, look for .env.example, copy/rename it as .env after that the file looks blow !

APP_ENV=local
APP_DEBUG=true
APP_KEY=someRandomNumber

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Modify the below block as follow

DB_HOST=yourHostName
DB_DATABASE=yourDatabaseName
DB_USERNAME=yourDatabaseUsername
DB_PASSWORD=youPassword

Now it will work fine.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

check your image cmd using the command docker inspect image_name . The output might be like this:

"Cmd": [
    "/bin/bash",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/bash\"]"
],

So use the command docker exec -it container_id /bin/bash. If your cmd output is different like this:

"Cmd": [
    "/bin/sh",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/sh\"]"
],

Use /bin/sh instead of /bin/bash in the command above.

Cancel a vanilla ECMAScript 6 Promise chain

I am still working through this idea, but here is how I have implemented a cancellable Promise using setTimeout as an example.

The idea is that a promise is resolved or rejected whenever you have decided it is, so it should be a matter of deciding when you want to cancel, satisfying the criterion, and then calling the reject() function yourself.

  • First, I think there are two reasons to finish a promise early: to get it over and done with (which I have called resolve) and to cancel (which I have called reject). Of course, that’s just my feeling. Of course there is a Promise.resolve() method, but it’s in the constructor itself, and returns a dummy resolved promise. This instance resolve() method actually resolves an instantiated promise object.

  • Second, you can happily add anything you like to a newly created promise object before you return it, and so I have just added resolve() and reject() methods to make it self-contained.

  • Third, the trick is to be able to access the executor resolve and reject functions later, so I have simply stored them in a simple object from within the closure.

I think the solution is simple, and I can’t see any major problems with it.

_x000D_
_x000D_
function wait(delay) {_x000D_
  var promise;_x000D_
  var timeOut;_x000D_
  var executor={};_x000D_
  promise=new Promise(function(resolve,reject) {_x000D_
    console.log(`Started`);_x000D_
    executor={resolve,reject};  //  Store the resolve and reject methods_x000D_
    timeOut=setTimeout(function(){_x000D_
      console.log(`Timed Out`);_x000D_
      resolve();_x000D_
    },delay);_x000D_
  });_x000D_
  //  Implement your own resolve methods,_x000D_
  //  then access the stored methods_x000D_
      promise.reject=function() {_x000D_
        console.log(`Cancelled`);_x000D_
        clearTimeout(timeOut);_x000D_
        executor.reject();_x000D_
      };_x000D_
      promise.resolve=function() {_x000D_
        console.log(`Finished`);_x000D_
        clearTimeout(timeOut);_x000D_
        executor.resolve();_x000D_
      };_x000D_
  return promise;_x000D_
}_x000D_
_x000D_
var promise;_x000D_
document.querySelector('button#start').onclick=()=>{_x000D_
  promise=wait(5000);_x000D_
  promise_x000D_
  .then(()=>console.log('I have finished'))_x000D_
  .catch(()=>console.log('or not'));_x000D_
};_x000D_
document.querySelector('button#cancel').onclick=()=>{ promise.reject(); }_x000D_
document.querySelector('button#finish').onclick=()=>{ promise.resolve(); }
_x000D_
<button id="start">Start</button>_x000D_
<button id="cancel">Cancel</button>_x000D_
<button id="finish">Finish</button>
_x000D_
_x000D_
_x000D_

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Here is Kotlin version.
Thanks you :)

         fun unSafeOkHttpClient() :OkHttpClient.Builder {
            val okHttpClient = OkHttpClient.Builder()
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts:  Array<TrustManager> = arrayOf(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                    override fun getAcceptedIssuers(): Array<X509Certificate>  = arrayOf()
                })

                // Install the all-trusting trust manager
                val  sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                if (trustAllCerts.isNotEmpty() &&  trustAllCerts.first() is X509TrustManager) {
                    okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
                    okHttpClient.hostnameVerifier { _, _ -> true }
                }

                return okHttpClient
            } catch (e: Exception) {
                return okHttpClient
            }
        }

Maven Installation OSX Error Unsupported major.minor version 51.0

I solved it putting a old version of maven (2.x), using brew:

brew uninstall maven
brew tap homebrew/versions 
brew install maven2

Error: Unable to run mksdcard SDK tool

Here's what you need to do to fix the issue on Arch Linux :

  1. Enable the multilib repository on your system if you have not already done so by uncommenting the [multilib] section in /etc/pacman.conf :

    [multilib]
    Include = /etc/pacman.d/mirrorlist
    
  2. Update pacman :

    # pacman -Suy
    
  3. Install the 32 bit version of libstdc++5 :

    # pacman -S lib32-libstdc++5
    

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

Updating a dataframe column in spark

importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.

from pyspark.sql.functions import col, when 

data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))

Android Studio Run/Debug configuration error: Module not specified

I had the same issue after update on Android Studio 3.2.1 I had to re-import project, after that everything works

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I've created a pared-down demo project for you.

You can try the above API Link from your local Fiddler to see the headers. Here is an explanation.

Global.ascx

All this does is call the WebApiConfig. It's nothing but code organization.

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }
}

WebApiConfig.cs

The key method for your here is the EnableCrossSiteRequests method. This is all that you need to do. The EnableCorsAttribute is a globally scoped CORS attribute.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        AddRoutes(config);
    }

    private static void AddRoutes(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/"
        );
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*", 
            headers: "*", 
            methods: "*");
        config.EnableCors(cors);
    }
}

Values Controller

The Get method receives the EnableCors attribute that we applied globally. The Another method overrides the global EnableCors.

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { 
            "This is a CORS response.", 
            "It works from any origin." 
        };
    }

    // GET api/values/another
    [HttpGet]
    [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")]
    public IEnumerable<string> Another()
    {
        return new string[] { 
            "This is a CORS response. ", 
            "It works only from two origins: ",
            "1. www.bigfont.ca ",
            "2. the same origin." 
        };
    }
}

Web.config

You do not need to add anything special into web.config. In fact, this is what the demo's web.config looks like - it's empty.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>

Demo

_x000D_
_x000D_
var url = "https://cors-webapi.azurewebsites.net/api/values"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
  console.log("We expect this to succeed.");_x000D_
  console.log(data);_x000D_
});_x000D_
_x000D_
var url = "https://cors-webapi.azurewebsites.net/api/values/another"_x000D_
_x000D_
$.get(url, function(data) {_x000D_
  console.log(data);_x000D_
}).fail(function(xhr, status, text) {_x000D_
  console.log("We expect this to fail.");_x000D_
  console.log(status);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

E: Unable to locate package mongodb-org

I faced same issue but fix it by the changing the package file section command. The whole step that i followed was:

At first try with this command: sudo apt-get install -y mongodb

This is the unofficial mongodb package provided by Ubuntu and it is not maintained by MongoDB and conflict with MongoDB’s offically supported packages.

If the above command not working then you can fix the issue by one of the bellow procedure:

#Step 1:  Import the MongoDB public key
#In Ubuntu 18.*+, you may get invalid signatures. --recv value may need to be updated to EA312927. 
#See here for more details on the invalid signature issue: [https://stackoverflow.com/questions/34733340/mongodb-gpg-invalid-signatures][1]

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

#Step 2: Generate a file with the MongoDB repository url
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

#Step 3: Refresh the local database with the packages
sudo apt-get update

#Step 4: Install the last stable MongoDB version and all the necessary packages on our system
sudo apt-get install mongodb-org

         #Or
# The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB and conflict with MongoDB’s offically supported packages. Use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
sudo apt-get install -y mongodb 

Hope this will work for you also. You can follow this MongoDB

Update The above instruction will install mongodb 2.6 version, if you want to install latest version for Uubuntu 12.04 then just replace above step 2 and follow bellow instruction instead of that:

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list

If you are using Ubuntu 14.04 then use bellow step instead of above step 2

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Update cordova plugins in one command

I too would LOVE something like this - plugin management with the PhoneGap/Cordova CLI is so annoying. This blog post here may be a start to something like this - but I'm not quite sure A) how to leverage it yet or B) how well it would work.

http://nocurve.com/cordova-update-all-plugins-in-project

My initial attempt at running the entire script right in the terminal command line did create an output of text with add/remove plugin commands ... but they didn't actually execute they just echoed into the terminal. I've reached out to the author hoping they will explain a bit more.

Hadoop cluster setup - java.net.ConnectException: Connection refused

In my experaince

15/02/22 18:23:04 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable

You may have 64 bit version OS, and hadoop installation 32bit. refer this

java.net.ConnectException: Call From marta-komputer/127.0.1.1 to
localhost:9000 failed on connection exception: java.net.ConnectException: 
connection refused; For more details see:   
http://wiki.apache.org/hadoop/ConnectionRefused

this problem refers to your ssh public key authorization. please provide details about your ssh set up.

Please refer this link to check the complete steps.

also provide info if

cat $HOME/.ssh/authorized_keys

returns any result or not.

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

One graph can replace many words:

enter image description here

Enjoy! :-)

# I have updated the correct image...

Laravel 5 – Remove Public from URL

I would like to add to @Humble Learner and note that the proper location to "fix" the url path for assets is /Illuminate/Routing/UrlGenerator.php/asset().

Update the method to match:

public function asset($path, $secure = null)
{
    if ($this->isValidUrl($path)) return $path;
    $root = $this->getRootUrl($this->getScheme($secure));
    return $this->removeIndex($root).'/public/'.trim($path, '/');
}

This will fix scripts, styles and image paths. Anything for asset paths.

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

How to connect Robomongo to MongoDB

  1. Comment out the /etc/mongod.conf file's bind_ip

  2. Download https://download.robomongo.org/0.9.0-rc9/windows/robomongo-0.9.0-rc9-windows-x86_64-0bb5668.exe

  3. Connection tab:

    3.1 Name (whatever)

    3.2 Address (IP address of the server) : Port number (27017)

  4. SSH tab (I used my normal PuTTY connection details)

    4.1 SSH Address: (IP address of server)

    4.2 SSH User Name (User Name)

    4.3 User Password (password)

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        setSerializationInclusion(JsonInclude.Include.NON_NULL); 
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    }
}

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

Git push error pre-receive hook declined

Seems the problem is with some services, like sidekiq. Running sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production outputs all the problems with config.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

How many bits is a "word"?

"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)

With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.

How to clear/delete the contents of a Tkinter Text widget?

this works

import tkinter as tk
inputEdit.delete("1.0",tk.END)

How to include vars file in a vars file with ansible?

Unfortunately, vars files do not have include statements.

You can either put all the vars into the definitions dictionary, or add the variables as another dictionary in the same file.

If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:

---
- hosts: myhosts

  vars_files:
    - default_step.yml

or in a task:

---
- hosts: myhosts

  tasks:
    - name: include default step variables
      include_vars: default_step.yml

How to add users to Docker container?

Ubuntu

Try the following lines in Dockerfile:

RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu

useradd options (see: man useradd):

  • -r, --system Create a system account. see: Implications creating system accounts
  • -m, --create-home Create the user's home directory.
  • -d, --home-dir HOME_DIR Home directory of the new account.
  • -s, --shell SHELL Login shell of the new account.
  • -g, --gid GROUP Name or ID of the primary group.
  • -G, --groups GROUPS List of supplementary groups.
  • -u, --uid UID Specify user ID. see: Understanding how uid and gid work in Docker containers
  • -p, --password PASSWORD Encrypted password of the new account (e.g. ubuntu).

Setting default user's password

To set the user password, add -p "$(openssl passwd -1 ubuntu)" to useradd command.

Alternatively add the following lines to your Dockerfile:

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd

The first shell instruction is to make sure that -o pipefail option is enabled before RUN with a pipe in it. Read more: Hadolint: Linting your Dockerfile.

Installing Python library from WHL file

First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.

If pip is not installed, and you are using Windows: How to install pip on Windows?

Am I trying to connect to a TLS-enabled daemon without TLS?

Everything that you need to run Docker on Linux Ubuntu/Mint:

sudo apt-get -y install lxc
sudo gpasswd -a ${USER} docker
newgrp docker
sudo service docker restart

Optionally, you may need to install two additional dependencies if the above doesn't work:

sudo apt-get -y install apparmor cgroup-lite
sudo service docker restart

Debugging with Android Studio stuck at "Waiting For Debugger" forever

I just managed this problem, after several days of trying the above solutions. So I closed the emulator, run AVD manager and in device menu choose - "wipe data" So in next run I was free from stucked debugger. AVD manager

How do I import material design library to Android Studio?

If you migrated to AndroidX you should add the dependency in graddle like this:

com.google.android.material:material:1.0.0-rc01

Installing Node.js (and npm) on Windows 10

The reason why you have to modify the AppData could be:

  1. Node.js couldn't handle path longer then 256 characters, windows tend to have very long PATH.
  2. If you are login from a corporate environment, your AppData might be on the server - that won't work. The npm directory must be in your local drive.

Even after doing that, the latest LTE (4.4.4) still have problem with Windows 10, it worked for a little while then whenever I try to:

$ npm install _some_package_ --global 

Node throw the "FATAL ERROR CALL_AND_RETRY_LAST Allocation failed - process out of memory" error. Still try to find a solution to that problem.

The only thing I find works is to run Vagrant or Virtual box, then run the Linux command line (must matching the path) which is quite a messy solution.

How to properly make a http web GET request

var request = (HttpWebRequest)WebRequest.Create("sendrequesturl");
var response = (HttpWebResponse)request.GetResponse();
string responseString;
using (var stream = response.GetResponseStream())
{
    using (var reader = new StreamReader(stream))
    {
        responseString = reader.ReadToEnd();
    }
}

How to include files outside of Docker's build context?

You can also create a tarball of what the image needs first and use that as your context.

https://docs.docker.com/engine/reference/commandline/build/#/tarball-contexts

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

phpmyadmin "Not Found" after install on Apache, Ubuntu

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf

sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin

sudo service apache2 restart

Run above commands issue will be resolved.

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

user 'guest' can only connect via localhost

That's true since RabbitMQ 3.3.x. Hence you should upgrade to the same version the client library, or just upgrade Spring AMQP to the latest version (if you use dependency managent system).

Previous version of client used 127.0.0.1 as default value for the host option of ConnectionFactory.

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Homebrew: Could not symlink, /usr/local/bin is not writable

I found for my particular setup the following commands worked

brew doctor

And then that showed me where my errors were, and then this slightly different command from the comment above.

sudo chown -R $(whoami) /usr/local/opt

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

Resource u'tokenizers/punkt/english.pickle' not found

The same thing happened to me recently, you just need to download the "punkt" package and it should work.

When you execute "list" (l) after having "downloaded all the available things", is everything marked like the following line?:

[*] punkt............... Punkt Tokenizer Models

If you see this line with the star, it means you have it, and nltk should be able to load it.

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

I had this issue after upgrading Android Studio to 3.2 and even upgrade some SDK-Packages.

The cause was that the path to emulator had changed, so don't use ...../Android/Sdk/tools/emulator but instead ....../Android/Sdk/emulator/emulator.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to set ANDROID_HOME path in ubuntu?

In the console just type these :

export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools

If you want to make it permanent just add those lines in the ~/.bashrc file

How to add constraints programmatically using Swift

Basically it involved 3 steps

fileprivate func setupName() { 

    lblName.text = "Hello world"

    // Step 1
    lblName.translatesAutoresizingMaskIntoConstraints = false

    //Step 2
    self.view.addSubview(lblName)

    //Step 3
    NSLayoutConstraint.activate([
        lblName.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        lblName.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
    ])
}

This puts label "hello world" in center of screen.

Please refer link Autolayout constraints programmatically

ReactJS call parent method

Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

 const handleParentFun = (value) =>{
   console.log("Call to Parent Component!",value);
 }
 return (<>
           This is Parent Component
           <ChildComponent 
             handleParentFun={(value)=>{
               console.log("your value -->",value);
               handleParentFun(value);
             }}
           />
        </>);
}

Child Component

import React from "react";


export default function ChildComponent(props){
  return(
         <> This is Child Component 
          <button onClick={props.handleParentFun("YoureValue")}>
            Call to Parent Component Function
          </button>
         </>
        );
}

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

How to mount host volumes into docker containers in Dockerfile during build

If you are looking for a way to "mount" files, like -v for docker run, you can now use the --secret flag for docker build

echo 'WARMACHINEROX' > mysecret.txt
docker build --secret id=mysecret,src=mysecret.txt .

And inside your Dockerfile you can now access this secret

# syntax = docker/dockerfile:1.0-experimental
FROM alpine

# shows secret from default secret location:
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret

# shows secret from custom secret location:
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar

More in-depth information about --secret available on Docker Docs

Verify a certificate chain using openssl verify

After breaking an entire day on the exact same issue , with no prior knowledge on SSL certificates, i downloaded the CERTivity Keystores Manager and imported my keystore to it, and got a clear-cut visualisation of the certificate chain.

Screenshot :

enter image description here

How to set up Spark on Windows?

Here's the fixes to get it to run in Windows without rebuilding everything - such as if you do not have a recent version of MS-VS. (You will need a Win32 C++ compiler, but you can install MS VS Community Edition free.)

I've tried this with Spark 1.2.2 and mahout 0.10.2 as well as with the latest versions in November 2015. There are a number of problems including the fact that the Scala code tries to run a bash script (mahout/bin/mahout) which does not work of course, the sbin scripts have not been ported to windows, and the winutils are missing if hadoop is not installed.

(1) Install scala, then unzip spark/hadoop/mahout into the root of C: under their respective product names.

(2) Rename \mahout\bin\mahout to mahout.sh.was (we will not need it)

(3) Compile the following Win32 C++ program and copy the executable to a file named C:\mahout\bin\mahout (that's right - no .exe suffix, like a Linux executable)

#include "stdafx.h"
#define BUFSIZE 4096
#define VARNAME TEXT("MAHOUT_CP")
int _tmain(int argc, _TCHAR* argv[]) {
    DWORD dwLength;     LPTSTR pszBuffer;
    pszBuffer = (LPTSTR)malloc(BUFSIZE*sizeof(TCHAR));
    dwLength = GetEnvironmentVariable(VARNAME, pszBuffer, BUFSIZE);
    if (dwLength > 0) { _tprintf(TEXT("%s\n"), pszBuffer); return 0; }
    return 1;
}

(4) Create the script \mahout\bin\mahout.bat and paste in the content below, although the exact names of the jars in the _CP class paths will depend on the versions of spark and mahout. Update any paths per your installation. Use 8.3 path names without spaces in them. Note that you cannot use wildcards/asterisks in the classpaths here.

set SCALA_HOME=C:\Progra~2\scala
set SPARK_HOME=C:\spark
set HADOOP_HOME=C:\hadoop
set MAHOUT_HOME=C:\mahout
set SPARK_SCALA_VERSION=2.10
set MASTER=local[2]
set MAHOUT_LOCAL=true
set path=%SCALA_HOME%\bin;%SPARK_HOME%\bin;%PATH%
cd /D %SPARK_HOME%
set SPARK_CP=%SPARK_HOME%\conf\;%SPARK_HOME%\lib\xxx.jar;...other jars...
set MAHOUT_CP=%MAHOUT_HOME%\lib\xxx.jar;...other jars...;%MAHOUT_HOME%\xxx.jar;...other jars...;%SPARK_CP%;%MAHOUT_HOME%\lib\spark\xxx.jar;%MAHOUT_HOME%\lib\hadoop\xxx.jar;%MAHOUT_HOME%\src\conf;%JAVA_HOME%\lib\tools.jar
start "master0" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.master.Master --ip localhost --port 7077 --webui-port 8082 >>out-master0.log 2>>out-master0.err
start "worker1" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.worker.Worker spark://localhost:7077 --webui-port 8083 >>out-worker1.log 2>>out-worker1.err
...you may add more workers here...
cd /D %MAHOUT_HOME%
"%JAVA_HOME%\bin\java" -Xmx4g -classpath "%MAHOUT_CP%" "org.apache.mahout.sparkbindings.shell.Main"

The name of the variable MAHOUT_CP should not be changed, as it is referenced in the C++ code.

Of course you can comment-out the code that launches the Spark master and worker because Mahout will run Spark as-needed; I just put it in the batch job to show you how to launch it if you wanted to use Spark without Mahout.

(5) The following tutorial is a good place to begin:

https://mahout.apache.org/users/sparkbindings/play-with-shell.html

You can bring up the Mahout Spark instance at:

"C:\Program Files (x86)\Google\Chrome\Application\chrome" --disable-web-security http://localhost:4040

adb shell su works but adb root does not

In some developer-friendly ROMs you could just enable Root Access in Settings > Developer option > Root access. After that adb root becomes available. Unfortunately it does not work for most stock ROMs on the market.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

After spending an hour on this error I found that the module file is duplicated. delete the extra file, and shift+cmd+k to clean and the error is gone.

Python: How to get values of an array at certain index positions?

The one liner "no imports" version

a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]

Two-dimensional array in Swift

You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24).

If the value is an object, which is initialized by MyClass(), then they will use the same reference.

Array(repeating: Array(repeating: MyClass(), count: 80), count: 24) doesn't create a new instance of MyClass in each array element. This method only creates MyClass once and puts it into the array.

Here's a safe way to initialize a multidimensional array.

private var matrix: [[MyClass]] = MyClass.newMatrix()

private static func newMatrix() -> [[MyClass]] {
    var matrix: [[MyClass]] = []

    for i in 0...23 {
        matrix.append( [] )

        for _ in 0...79 {
            matrix[i].append( MyClass() )
        }
    }

    return matrix
}

Why am I getting a "401 Unauthorized" error in Maven?

Also had 401's from Nexus. Having tried all the suggestions above and more without success I eventually found that it was a Jenkins setting that was in error.

In the Jenkins configuration for the failing project, we have a section in the 'Post Build' actions entitled 'Deploy Artifacts To Maven Repository'. This has a 'Repository ID' field which was set to the wrong value. It has to be the same as the repository ID in settings.xml for Jenkins to read the user and password fields:

Jenkins Project Configuration

 <servers>
    <server>
      <id>snapshot-repository</id>  <!-- must match this -->
      <username>deployment</username>
      <password>password</password>
    </server>
  </servers>

javac: invalid target release: 1.8

None of the previous solutions worked for me.

I solved it by editing .idea/compiler.xml There were "extra" (1) and (2) copies of the bad module with different targets. I deleted the extraneous entried and changed the targets in the section to 1.8 and it worked.

How to set editor theme in IntelliJ Idea

IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar files.

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

How can I change the image of an ImageView?

if (android.os.Build.VERSION.SDK_INT >= 21) {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}

How does the JPA @SequenceGenerator annotation work

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

CSV parsing in Java - working example..?

Basically you will need to read the file line by line.

Then you will need to split each line by the delimiter, say a comma (CSV stands for comma-separated values), with

String[] strArr=line.split(",");

This will turn it into an array of strings which you can then manipulate, for example with

String name=strArr[0];
int yearOfBirth = Integer.valueOf(strArr[1]);
int monthOfBirth = Integer.valueOf(strArr[2]);
int dayOfBirth = Integer.valueOf(strArr[3]);
GregorianCalendar dob=new GregorianCalendar(yearOfBirth, monthOfBirth, dayOfBirth);
Student student=new Student(name, dob); //lets pretend you are creating instances of Student

You will need to do this for every line so wrap this code into a while loop. (If you don't know the delimiter just open the file in a text editor.)

Java generics - get class?

I like the solution from

http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/

public class Dada<T> {

    private Class<T> typeOfT;

    @SuppressWarnings("unchecked")
    public Dada() {
        this.typeOfT = (Class<T>)
                ((ParameterizedType)getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
...

How to convert int to Integer

int iInt = 10;
Integer iInteger = new Integer(iInt);

Convert absolute path into relative path given a current directory using Bash

This answer does not address the Bash part of the question, but because I tried to use the answers in this question to implement this functionality in Emacs I'll throw it out there.

Emacs actually has a function for this out of the box:

ELISP> (file-relative-name "/a/b/c" "/a/b/c")
"."
ELISP> (file-relative-name "/a/b/c" "/a/b")
"c"
ELISP> (file-relative-name "/a/b/c" "/c/b")
"../../a/b/c"

What is the C# equivalent of NaN or IsNumeric?

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

Concatenating multiple text files into a single file in Bash

You can do like this: cat [directory_path]/**/*.[h,m] > test.txt

if you use {} to include the extension of the files you want to find, there is a sequencing problem.

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

MySQL: Check if the user exists and drop it

Since MySQL 5.7 you can do a DROP USER IF EXISTS test

More info: http://dev.mysql.com/doc/refman/5.7/en/drop-user.html

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

findViewById in Fragment

agreed with calling findViewById() on the View.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView) V.findViewById(R.id.my_image);

    return V;
}

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

jvmtop is a command-line tool which provides a live-view at several metrics, including heap.

Example output of the VM overview mode:

 JvmTop 0.3 alpha (expect bugs)  amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
 http://code.google.com/p/jvmtop

  PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
 3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

How do I get textual contents from BLOB in Oracle SQL

You can use below SQL to read the BLOB Fields from table.

SELECT DBMS_LOB.SUBSTR(BLOB_FIELD_NAME) FROM TABLE_NAME;

How to SELECT WHERE NOT EXIST using LINQ?

The outcome sql will be different but the result should be the same:

var shifts = Shifts.Where(s => !EmployeeShifts.Where(es => es.ShiftID == s.ShiftID).Any());

Storing integer values as constants in Enum manner in java

You can use ordinal. So PAGE.SIGN_CREATE.ordinal() returns 1.

EDIT:

The only problem with doing this is that if you add, remove or reorder the enum values you will break the system. For many this is not an issue as they will not remove enums and will only add additional values to the end. It is also no worse than integer constants which also require you not to renumber them. However it is best to use a system like:

public enum PAGE{
  SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)

  private int id;

  PAGE(int id){
    this.id = id;
  }

  public int getID(){
    return id;
  }

}

You can then use getID. So PAGE.SIGN_CREATE.getID() returns 1.

Generate a random number in a certain range in MATLAB

r = 13 + 7.*rand(100,1);

Where 100,1 is the size of the desidered vector

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

How can I create an executable JAR with dependencies using Maven?

Add to pom.xml:

  <dependency>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
            <version>1.4.4</version>
  </dependency>

and

<plugin>
       <groupId>com.jolira</groupId>
       <artifactId>onejar-maven-plugin</artifactId>
       <version>1.4.4</version>
       <executions>
              <execution>
                     <goals>
                         <goal>one-jar</goal>
                     </goals>
              </execution>
       </executions>
</plugin>

Thats it. Next mvn package will also create one fat jar additionally, including all dependency jars.

What is Unicode, UTF-8, UTF-16?

  • Unicode
    • is a set of characters used around the world
  • UTF-8
    • a character encoding capable of encoding all possible characters (called code points) in Unicode.
    • code unit is 8-bits
    • use one to four code units to encode Unicode
    • 00100100 for "$" (one 8-bits);11000010 10100010 for "¢" (two 8-bits);11100010 10000010 10101100 for "" (three 8-bits)
  • UTF-16
    • another character encoding
    • code unit is 16-bits
    • use one to two code units to encode Unicode
    • 00000000 00100100 for "$" (one 16-bits);11011000 01010010 11011111 01100010 for "" (two 16-bits)

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

How to handle configuration in Go

I have started using Gcfg which uses Ini-like files. It's simple - if you want something simple, this is a good choice.

Here's the loading code I am using currently, which has default settings and allows command line flags (not shown) that override some of my config:

package util

import (
    "code.google.com/p/gcfg"
)

type Config struct {
    Port int
    Verbose bool
    AccessLog string
    ErrorLog string
    DbDriver string
    DbConnection string
    DbTblPrefix string
}

type configFile struct {
    Server Config
}

const defaultConfig = `
    [server]
    port = 8000
    verbose = false
    accessLog = -
    errorLog  = -
    dbDriver     = mysql
    dbConnection = testuser:TestPasswd9@/test
    dbTblPrefix  =
`

func LoadConfiguration(cfgFile string, port int, verbose bool) Config {
    var err error
    var cfg configFile

    if cfgFile != "" {
        err = gcfg.ReadFileInto(&cfg, cfgFile)
    } else {
        err = gcfg.ReadStringInto(&cfg, defaultConfig)
    }

    PanicOnError(err)

    if port != 0 {
        cfg.Server.Port = port
    }
    if verbose {
        cfg.Server.Verbose = true
    }

    return cfg.Server
}

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Changing Java Date one hour back

tl;dr

In UTC:

Instant.now().minus( 1 , ChronoUnit.HOURS ) 

Or, zoned:

Instant.now()
       .atZone( ZoneId.of ( "America/Montreal" ) )
       .minusHours( 1 )

Using java.time

Java 8 and later has the new java.time framework built-in.

Instant

If you only care about UTC (GMT), then use the Instant class.

Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );

instant: 2015-10-29T00:37:48.921Z | instantHourEarlier: 2015-10-28T23:37:48.921Z

Note how in this instant happened to skip back to yesterday’s date.

ZonedDateTime

If you care about a time zone, use the ZonedDateTime class. You can start with an Instant and the assign a time zone, a ZoneId object. This class handles the necessary adjustments for anomalies such as Daylight Saving Time (DST).

Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );

Dump to console.

System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );

instant: 2015-10-29T00:50:30.778Z

zdt: 2015-10-28T20:50:30.778-04:00[America/Montreal]

zdtHourEarlier: 2015-10-28T19:50:30.778-04:00[America/Montreal]

Conversion

The old java.util.Date/.Calendar classes are now outmoded. Avoid them. They are notoriously troublesome and confusing.

When you must use the old classes for operating with old code not yet updated for the java.time types, call the conversion methods. Here is example code going from an Instant or a ZonedDateTime to a java.util.Date.

java.util.Date date = java.util.Date.from( instant );

…or…

java.util.Date date = java.util.Date.from( zdt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Select tableview row programmatically

Swift 3/4/5 Solution

Select Row

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath)

DeSelect Row

let deselectIndexPath = IndexPath(row: 7, section: 0)
tblView.deselectRow(at: deselectIndexPath, animated: true)
tblView.delegate?.tableView!(tblView, didDeselectRowAt: indexPath)

How do you count the number of occurrences of a certain substring in a SQL varchar?

In SQL 2017 or higher, you can use this:

declare @hits int = 0
set @hits = (select value from STRING_SPLIT('F609,4DFA,8499',','));
select count(@hits)

How to write a PHP ternary operator

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);

Twitter bootstrap 3 two columns full height

This was not mentioned here with offsetting.

You can use absolute to position for the left sidebar.

CSS

.sidebar-fixed{
  width: 16.66666667%;
  height: 100%;
}

HTML

<div class="row">
  <div class="sidebar-fixed">
    Side Bar
  </div>
  <div class="col-md-10 col-md-offset-2">
    CONTENT
  </div>
</div>

milliseconds to time in javascript

Here is a filter that use:

app.filter('milliSecondsToTimeCode', function () {
    return function msToTime(duration) {
        var milliseconds = parseInt((duration % 1000) / 100)
            , seconds = parseInt((duration / 1000) % 60)
            , minutes = parseInt((duration / (1000 * 60)) % 60)
            , hours = parseInt((duration / (1000 * 60 * 60)) % 24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
    };
});

Just add it to your expression as such

{{milliseconds | milliSecondsToTimeCode}}

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

What should be the sizeof(int) on a 64-bit machine?

Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.

How do I parse JSON from a Java HTTPResponse?

Two things which can be done more efficiently:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

If the JSON is actually a single line, then you can also remove the loop and builder.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

Send inline image in email

    MailMessage mail = new MailMessage();
    //set the addresses
    mail.From = new MailAddress("[email protected]");
    mail.To.Add("[email protected]");

    //set the content
    mail.Subject = "Sucessfully Sent the HTML and Content of mail";

    //first we create the Plain Text part
    string plainText = "Non-HTML Plain Text Message for Non-HTML enable mode";
    AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain");
    XmlTextReader reader = new XmlTextReader(@"E:\HTMLPage.htm");
    string[] address = new string[30];
    string finalHtml = "";
    var i = -1;
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { // The node is an element.
            if (reader.AttributeCount <= 1)
            {
                if (reader.Name == "img")
                {
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                    {
                        if (reader.Name == "src")
                        {
                            i++;
                            address[i] = reader.Value;
                            address[i] = address[i].Remove(0, 8);
                            finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString();
                        }
                        else
                        {
                            finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                        }
                    }
                    finalHtml += ">";
                }
                else
                {
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                    {
                        finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                    }
                    finalHtml += ">";
                }
            }

        }
        else if (reader.NodeType == XmlNodeType.Text)
        { //Display the text in each element.
            finalHtml += reader.Value;
        }
        else if (reader.NodeType == XmlNodeType.EndElement)
        {
            //Display the end of the element.
            finalHtml += "</" + reader.Name;
            finalHtml += ">";
        }

    }

    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html");
    LinkedResource[] logo = new LinkedResource[i + 1];
    for (int j = 0; j <= i; j++)
    {
        logo[j] = new LinkedResource(address[j]);
        logo[j].ContentId = "chartlogo" + j;
        htmlView.LinkedResources.Add(logo[j]);
    }
    mail.AlternateViews.Add(plainView);
    mail.AlternateViews.Add(htmlView);
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.Credentials = new NetworkCredential(
        "[email protected]", "Password");
    smtp.EnableSsl = true;
    Console.WriteLine();
    smtp.Send(mail);
}

Padding a table row

give the td padding

Clear back stack using fragments

Works for me and easy way without using loop:

 FragmentManager fragmentManager = getSupportFragmentManager();
 //this will clear the back stack and displays no animation on the screen
 fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

How to rename a component in Angular CLI?

Here is a checklist I use to rename a component:

1.Rename the component class (VSCode Rename Symbool will update all the references)

<Old Name>Component => <New Name>Component

2.Rename @Component selector along with references (use VSCode's Replace in Files):

app-<old-name> => app-<new-name>

Result:
@Component({
  selector: 'app-<old-name>' => 'app-<new-name>',
  ...
})

<app-{old-name}></app-{old-name}> => <app-{new-name}></app-{new-name}>

3.Rename component folder (when renaming folder in VSCode, it will update references in module and other components)

src\app\<module>\<old-name> => src\app\<module>\<new-name>

4.Rename component files (renaming manually will be the fastest, but you can also use a terminal to rename all at once)

<old-name>.compoonent.* => <new-name>.compoonent.*

Bash:
find . -name "<old-name>.component.*" -exec rename 's/\/<old-name>\.component/\/<new-name>.component/' '{}' +

PowerShell: 
Get-Item <old-name>.component.* | % { Rename-Item $_ <new-name>.component.$($_.Extension) }

Cmd:
rename <old-name>.component.* <new-name>.component.*

5.Replace file references in @Component (use VSCode's Replace in Files):

<old-name>.component => <new-name>.component

Result:
@Component({
  ...
  templateUrl: './<old-name>.component.html' => './<old-name>.component.html',
  styleUrls: ['./<old-name>.component.scss'] => ['./<new-name>.component.scss']
})

That should be sufficient

Word wrap for a label in Windows Forms

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

CSS: Center block, but align contents to the left

Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question

How to recognize vehicle license / number plate (ANPR) from an image?

The blurring is not a problem but is there a library or component (open source preferred) that will help with finding a licence within a photo?

Ans: The CARMEN FreeFlow ANPR Software engine (Commerical)

Is there shorthand for returning a default value if None in Python?

x or "default"

works best — i can even use a function call inline, without executing it twice or using extra variable:

self.lineEdit_path.setText( self.getDir(basepath) or basepath )

I use it when opening Qt's dialog.getExistingDirectory() and canceling, which returns empty string.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

PostgreSQL - query from bash script as database user 'postgres'

You can connect to psql as below and write your sql queries like you do in a regular postgres function within the block. There, bash variables can be used. However, the script should be strictly sql, even for comments you need to use -- instead of #:

#!/bin/bash
psql postgresql://<user>:<password>@<host>/<db> << EOF
       <your sql queries go here>
EOF

Corrupted Access .accdb file: "Unrecognized Database Format"

Open access, go to the database tools tab, select compact and repair database. You can choose the database from there.

Count the number of Occurrences of a Word in a String

If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).

int c=0;
String found="male cat";
 for(int j=0; j<text.length();j++){
     if(text.contains(found)){
         c+=1;
         j+=found.length()-1;
     }
 }
 System.out.println("counter="+c);

Create a folder if it doesn't already exist

Recursively create directory path:

function makedirs($dirpath, $mode=0777) {
    return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}

Inspired by Python's os.makedirs()

Cannot connect to Database server (mysql workbench)

It looks like there are a lot of causes of this error.

My Cause / Solution

In my case, the cause was that my server was configured to only accept connections from localhost. I fixed it by following this article: How Do I Enable Remote Access To MySQL Database Server?. My my.cnf file had no skip-networking line, so I just changed the line

bind-address = 127.0.0.1

to

bind-address = 0.0.0.0

This allows connections from any IP, not just 127.0.0.1.

Then, I created a MySql user that could connect from my client machine by running the following terminal commands:

# mysql -u root -p
mysql> CREATE USER 'username'@'1.2.3.4' IDENTIFIED BY 'password';
    -> GRANT ALL PRIVILEGES ON *.* TO 'username'@'1.2.3.4' WITH GRANT OPTION;
    -> \q

where 1.2.3.4 is the IP of the client you are trying to connect from. If you really have trouble, you can use '%' instead of '1.2.3.4' to allow the user to connect from any IP.

Other Causes

For a fairly extensive list, see Causes of Access-Denied Errors.

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

The code you have is correct. JSX code needs to be compiled to JS:

http://facebook.github.io/react/jsx-compiler.html

Auto height of div

make sure the content inside your div ended with clear:both style

Simple mediaplayer play mp3 from file path?

It works like this:

mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
        mpintro.start();

It did not work properly as string filepath...

Response.Redirect to new window

I always use this code... Use this code

String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;

// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
    {
     StringBuilder sb = new StringBuilder ();
     sb.Append ("<script type='text/javascript'>");
     sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
     sb.Append ("</script>");
     clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
     }

How to read connection string in .NET Core?

The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.

In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the whole configuration object here.
    services.AddSingleton<IConfiguration>(Configuration);
}

In your controller add a field for the configuration and a parameter for it on a constructor

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
{
    configuration = config;
}

Now later in your view code you can access it like:

connectionString = configuration.GetConnectionString("DefaultConnection");

Checking if a folder exists (and creating folders) in Qt, C++

If you need an empty folder you can loop until you get an empty folder

    QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    while(QDir(folder).exists())
    {
         folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    QDir().mkdir(folder);

This case you will get a folder name with a number .

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

animating addClass/removeClass with jQuery

Since you are not worried about IE, why not just use css transitions to provide the animation and jQuery to change the classes. Live example: http://jsfiddle.net/tw16/JfK6N/

#someDiv{
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

convert php date to mysql format

This site has two pretty simple solutions - just check the code, I provided the descriptions in case you wanted them - saves you some clicks.

http://www.richardlord.net/blog/dates-in-php-and-mysql

1.One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -

$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );

2.Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -

$query = "UPDATE table SET
    datetimefield = FROM_UNIXTIME($phpdate)
    WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
    FROM table WHERE...";

Backup/Restore a dockerized PostgreSQL database

I had this issue while trying to use a db_dump to restore a db. I normally use dbeaver to restore- however received a psql dump, so had to figure out a method to restore using the docker container.

The methodology recommended by Forth and edited by Soviut worked for me:

cat your_dump.sql | docker exec -i your-db-container psql -U postgres -d dbname

(since this was a single db dump and not multiple db's i included the name)

However, in order to get this to work, I had to also go into the virtualenv that the docker container and project were in. This eluded me for a bit before figuring it out- as I was receiving the following docker error.

read unix @->/var/run/docker.sock: read: connection reset by peer

This can be caused by the file /var/lib/docker/network/files/local-kv.db .I don't know the accuracy of this statement: but I believe I was seeing this as I do not user docker locally, so therefore did not have this file, which it was looking for, using Forth's answer.

I then navigated to correct directory (with the project) activated the virtualenv and then ran the accepted answer. Boom, worked like a top. Hope this helps someone else out there!

How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

OR condition in Regex

I think what you need might be simply:

\d( \w)?

Note that your regex would have worked too if it was written as \d \w|\d instead of \d|\d \w.

This is because in your case, once the regex matches the first option, \d, it ceases to search for a new match, so to speak.

Add items to comboBox in WPF

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

How to hide collapsible Bootstrap 4 navbar on click

You can add the collapse component to the links like this..

<ul class="navbar-nav mr-auto">
     <li class="nav-item active">
         <a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
     </li>
 </ul>

BS3 demo using 'data-toggle' method

Or, (perhaps a better way) use jQuery like this..

$('.navbar-nav>li>a').on('click', function(){
    $('.navbar-collapse').collapse('hide');
});

BS3 demo using jQuery method


Update 2019 - Bootstrap 4

The navbar has changed, but the "close after click" method is still the same:

BS4 demo jQuery method
BS4 demo data-toggle method


Update 2021 - Bootstrap 5 (beta)

Use javascript to add a click event listener on the menu items to close the Collapse navbar..

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
})

BS5 demo javascript method

Or, Use the data-bs-toggle and data-bs-target data attributes in the markup on each link to toggle the Collapse navbar...

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
                </li>
            </ul>
            <form class="d-flex my-2 my-lg-0">
                <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </div>
    </div>
</nav>

BS5 demo data-attributes method

How can I set the value of a DropDownList using jQuery?

$("#mydropdownlist").val("thevalue");

just make sure the value in the options tags matches the value in the val method.

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

Google Maps V3 marker with label

I doubt the standard library supports this.

But you can use the google maps utility library:

http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker = new MarkerWithLabel({
   position: myLatlng,
   map: map,
   draggable: true,
   raiseOnDrag: true,
   labelContent: "A",
   labelAnchor: new google.maps.Point(3, 30),
   labelClass: "labels", // the CSS class for the label
   labelInBackground: false
 });

The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers

How do I declare an array of undefined or no initial size?

The way it's often done is as follows:

  • allocate an array of some initial (fairly small) size;
  • read into this array, keeping track of how many elements you've read;
  • once the array is full, reallocate it, doubling the size and preserving (i.e. copying) the contents;
  • repeat until done.

I find that this pattern comes up pretty frequently.

What's interesting about this method is that it allows one to insert N elements into an empty array one-by-one in amortized O(N) time without knowing N in advance.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

How to write a cron that will run a script every day at midnight?

You can execute shell script in two ways,either by using cron job or by writing a shell script

Lets assume your script name is "yourscript.sh"

First check the user permission of the script. use below command to check user permission of the script

ll script.sh

If the script is in root,then use below command

sudo crontab -e

Second if the script holds the user "ubuntu", then use below command

crontab -e

Add the following line in your crontab:-

55 23 * * * /path/to/yourscript.sh

Another way of doing this is to write a script and run it in the backgroud

Here is the script where you have to put your script name(eg:- youscript.sh) which is going to run at 23:55pm everyday

#!/bin/bash while true do /home/modassir/yourscript.sh sleep 1d done

save it in a file (lets name it "every-day.sh")

sleep 1d - means it waits for one day and then it runs again.

now give the permission to your script.use below command:-

chmod +x every-day.sh

now, execute this shell script in the background by using "nohup". This will keep executing the script even after you logout from your session.

use below command to execute the script.

nohup ./every-day.sh &

Note:- to run "yourscript.sh" at 23:55pm everyday,you have to execute "every-day.sh" script at exactly 23:55pm.

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I too had the "Uncaught TypeError: Cannot read property 'fn' of undefined" with:

$.fn.circleType = function(options) {

CODE...

};

But fixed it by wrapping it in a document ready function:

jQuery(document).ready.circleType = function(options) {

CODE...

};

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

docker entrypoint running bash script gets "permission denied"

This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.

In my working directory I have two files: Dockerfile & provision.sh

Dockerfile:

FROM centos:6.8

# put the script in the /root directory of the container
COPY provision.sh /root

# execute the script inside the container
RUN /root/provision.sh

EXPOSE 80

# Default command
CMD ["/bin/bash"]

provision.sh:

#!/usr/bin/env bash

yum upgrade

I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh then running docker build . .

How to pass variables from one php page to another without form?

You want sessions if you have data you want to have the data held for longer than one page.

$_GET for just one page.

<a href='page.php?var=data'>Data link</a>

on page.php

<?php
echo $_GET['var'];
?>

will output: data

How to fill color in a cell in VBA?

  1. Select all cells by left-top corner
  2. Choose [Home] >> [Conditional Formatting] >> [New Rule]
  3. Choose [Format only cells that contain]
  4. In [Format only cells with:], choose "Errors"
  5. Choose proper formats in [Format..] button

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

Is it possible to import a whole directory in sass using @import?

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

How to assign a NULL value to a pointer in python?

left = None

left is None #evaluates to True

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Print range of numbers on same line

>>>print(*range(1,11)) 
1 2 3 4 5 6 7 8 9 10

Python one liner to print the range

Difference between java.lang.RuntimeException and java.lang.Exception

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).

In the classes that you design you should subclass Exception and throw instances of it to signal any exceptional scenarios. Doing so you will be explicitly signaling the clients of your class that usage of your class might throw exception and they have to take steps to handle those exceptional scenarios.

Below code snippets explain this point:

//Create your own exception class subclassing from Exception
class MyException extends Exception {
    public MyException(final String message) {
        super(message);
    }
}

public class Process {
    public void execute() {
        throw new RuntimeException("Runtime");
    }  
    public void process() throws MyException {
        throw new MyException("Checked");
    }
}

In the above class definition of class Process, the method execute can throw a RuntimeException but the method declaration need not specify that it throws RuntimeException.

The method process throws a checked exception and it should declare that it will throw a checked exception of kind MyException and not doing so will be a compile error.

The above class definition will affect the code that uses Process class as well.

The call new Process().execute() is a valid invocation where as the call of form new Process().process() gives a compile error. This is because the client code should take steps to handle MyException (say call to process() can be enclosed in a try/catch block).

Return HTTP status code 201 in flask

In my case I had to combine the above in order to make it work

return Response(json.dumps({'Error': 'Error in payload'}), 
status=422, 
mimetype="application/json")

Create a new database with MySQL Workbench

This answer is for Ubuntu users looking for a solution without writing SQL queries.

The following is the initial screen you'll get after opening it

Initial screen

In the top right, where it says Administration, click in the arrow to the right

From Administration to Schemas

This will show Schema (instead of Administration) and it's possible to see a sys database.

Schema menu with databases

Right click in the grey area after functions and click Create Schema...

Create Schema

This will open the following where I'm creating a table named StackOverflow_db

Create new Schema

Clicking in the bottom right button that says "Apply",

Create a new Schema in Workbench

And in this new view click in "Apply" too. In the end you'll get a database called StackOverflow_db

Database created

Making sure at least one checkbox is checked

You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.

Reference Link

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

http://localhost:50070 does not work HADOOP

After installing and configuring Hadoop, you can quickly run the command netstat -tulpn

to find the ports open. In the new version of Hadoop 3.1.3 the ports are as follows:-

localhost:8042 Hadoop, localhost:9870 HDFS, localhost:8088 YARN

Spring Boot - How to log all requests and responses with exceptions in single place?

If somebody still need it here is simple implementation with Spring HttpTrace Actuator. But as they have told upper it doesn't log bodies.

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.boot.actuate.trace.http.HttpTrace;
import org.springframework.boot.actuate.trace.http.InMemoryHttpTraceRepository;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class LoggingInMemoryHttpTraceRepository extends InMemoryHttpTraceRepository {
    public void add(HttpTrace trace) {
        super.add(trace);
        log.info("Trace:" + ToStringBuilder.reflectionToString(trace));
        log.info("Request:" + ToStringBuilder.reflectionToString(trace.getRequest()));
        log.info("Response:" + ToStringBuilder.reflectionToString(trace.getResponse()));
    }
}

var.replace is not a function

Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?

Otherwise, I don't see a problem with your code - the example below works as expected

function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}


trim('    hello   ');  // --> 'hello'

However, if you call your functoin with something non-string, you will indeed get the error above:

trim({});  // --> TypeError: str.replace is not a function

Inverse dictionary lookup in Python

This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.

key = dict_obj.keys()[dict_obj.values().index(value)]

Or if you prefer brevity over readability you can save one more character with

key = list(dict_obj)[dict_obj.values().index(value)]

And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:

key = (key for key, value in dict_obj.items() if value == 'value').next()

List and kill at jobs on UNIX

You should be able to find your command with a ps variant like:

ps -ef
ps -fubob # if your job's user ID is bob.

Then, once located, it should be a simple matter to use kill to kill the process (permissions permitting).

If you're talking about getting rid of jobs in the at queue (that aren't running yet), you can use atq to list them and atrm to get rid of them.

How to count days between two dates in PHP?

Simple way to count is,

$currentdate = date('Y-m-d H:i:s');
$after1yrdate =  date("Y-m-d H:i:s", strtotime("+1 year", strtotime($data)));

$diff = (strtotime($after1yrdate) - strtotime($currentdate)) / (60 * 60 * 24);

echo "<p style='color:red'>The difference is ".round($diff)." Days</p>";

ERROR! MySQL manager or server PID file could not be found! QNAP

After doing setup of PHPMyAdmin, I was also facing the same problem,

Something . Like this

  • Then I just stopped the MYSQL server by going into System settings, and then started again, and it worked.

Telling Python to save a .txt file to a certain directory on Windows and Mac

Another simple way without using import OS is,

outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()

writing integer values to a file using out.write()

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you'll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it's worth learning/knowing.

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

jQuery Determine if a matched class has a given id

Just to say I eventually solved this using index().

NOTHING else seemed to work.

So for sibling elements this is a good work around if you are first selecting by a common class and then want to modify something differently for each specific one.

EDIT: for those who don't know (like me) index() gives an index value for each element that matches the selector, counting from 0, depending on their order in the DOM. As long as you know how many elements there are with class="foo" you don't need an id.

Obviously this won't always help, but someone might find it useful.

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

What is the difference between explicit and implicit cursors in Oracle?

As stated in other answers, implicit cursors are easier to use and less error-prone.

And Implicit vs. Explicit Cursors in Oracle PL/SQL shows that implicit cursors are up to two times faster than explicit ones too.

It's strange that no one had yet mentioned Implicit FOR LOOP Cursor:

begin
  for cur in (
    select t.id from parent_trx pt inner join trx t on pt.nested_id = t.id
    where t.started_at > sysdate - 31 and t.finished_at is null and t.extended_code is null
  )
  loop
    update trx set finished_at=sysdate, extended_code = -1 where id = cur.id;
    update parent_trx set result_code = -1 where nested_id = cur.id;
  end loop cur;
end;

Another example on SO: PL/SQL FOR LOOP IMPLICIT CURSOR.

It's way more shorter than explicit form.

This also provides a nice workaround for updating multiple tables from CTE.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

How can I switch to another branch in git?

[git checkout "branch_name"]

is another way to say:

[git checkout -b branch_name origin/branch_name]

in case "branch_name" exists only remotely.

[git checkout -b branch_name origin/branch_name] is useful in case you have multiple remotes.

Regarding [git checkout origin 'another_branch'] I'm not sure this is possible, AFAK you can do this using "fetch" command -- [git fetch origin 'another_branch']

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

How can I have a newline in a string in sh?

Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf utility, doing away with all the problems.

So to get a newline in a string:

FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf now and never look back.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

On newer versions of Android, I was receiving this error because the adapter was still discovering when I attempted to connect to the socket. Even though I called the cancelDiscovery method on the Bluetooth adapter, I had to wait until the callback to the BroadcastReceiver's onReceive() method was called with the action BluetoothAdapter.ACTION_DISCOVERY_FINISHED.

Once I waited for the adapter to stop discovery, then the connect call on the socket succeeded.

Untrack files from git temporarily

To remove all Untrack files. Try this terminal command

 git clean -fdx

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

SQLite select where empty?

There are several ways, like:

where some_column is null or some_column = ''

or

where ifnull(some_column, '') = ''

or

where coalesce(some_column, '') = ''

of

where ifnull(length(some_column), 0) = 0

How do I make a relative reference to another workbook in Excel?

The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:

http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651

Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1 with no folder names to traverse.

How can I de-install a Perl module installed via `cpan`?

Since at the time of installing of any module it mainly put corresponding .pm files in respective directories. So if you want to remove module only for some testing purpose or temporarily best is to find the path where module is stored using perldoc -l <MODULE> and then simply move the module from there to some other location. This approach can also be tried as a more permanent solution but i am not aware of any negative consequences as i do it mainly for testing.

Creating a zero-filled pandas data frame

It's best to do this with numpy in my opinion

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

How to force maven update?

I used the IntelliJ IDE and I had a similar problem and to solve I clicked in "Generate Sources and Update Folders for All Projects" in Maven tab.

enter image description here

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.

How to get access to job parameters from ItemReader, in Spring Batch?

As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step") annotation. It should work for you if you add that annotation to your reader, like the following:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }

  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

This scope is not available by default, but will be if you are using the batch XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:

<bean class="org.springframework.batch.core.scope.StepScope" />

javax.net.ssl.SSLException: Received fatal alert: protocol_version

Not sure if you found an answer but I had this problem and needed to upgrade TLS version to 1.2

private HttpsURLConnection getSSlConnection(String url, String username, String password){
    SSLContext sc = SSLContext.getInstance("TLSv1.2")
    // Create a trust manager that accepts all SSL sites
    TrustManager[] trustAllCerts = new TrustManager[1]
    def tm = new X509TrustManager(){
        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0]
        }
    }
    trustAllCerts[0] = tm

    sc.init(null, trustAllCerts, new SecureRandom())
    HttpsURLConnection connection = (HttpsURLConnection) getConnection(url, username, password)
    connection.setSSLSocketFactory(sc.getSocketFactory())
    return connection
}

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

How do I create a list of random numbers without duplicates?

You can first create a list of numbers from a to b, where a and b are respectively the smallest and greatest numbers in your list, then shuffle it with Fisher-Yates algorithm or using the Python's random.shuffle method.

Editing hosts file to redirect url?

You can't. A redirect requires a webserver to accept the first request and send back the redirect. The "hosts" file just lets you set your own DNS records.

Chart.js canvas resize

Add div and it will solve the problem

<div style="position:absolute; top:50px; left:10px; width:500px; height:500px;"></div>

Creating random colour in Java?

A one-liner for random RGB values:

new Color((int)(Math.random() * 0x1000000))

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

Asynchronous vs synchronous execution, what does it really mean?

Simply said asynchronous execution is doing stuff in the background.

For example if you want to download a file from the internet you might use a synchronous function to do that but it will block your thread until the file finished downloading. This can make your application unresponsive to any user input.

Instead you could download the file in the background using asynchronous method. In this case the download function returns immediately and program execution continues normally. All the download operations are done in the background and your program will be notified when it's finished.

How do I restrict an input to only accept numbers?

Easy way, use type="number" if it works for your use case:

<input type="number" ng-model="myText" name="inputName">

Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

Hackish? way, $watch the ng-model in your controller:

<input type="text"  ng-model="myText" name="inputName">

Controller:

$scope.$watch('myText', function() {
   // put numbersOnly() logic here, e.g.:
   if ($scope.myText  ... regex to look for ... ) {
      // strip out the non-numbers
   }
})

Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945

All of the above solutions involve using ng-model, which make finding this unnecessary.

Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)

Hide options in a select list using jQuery

I found a better way, and it is very simple:

$("option_you_want_to_hide").wrap('<span/>')

To show again, just find that option(not span) and $("option_you_want_to_show").unwrap().

It was tested on Chrome and Firefox.

Android EditText view Floating Hint in Material Design

For an easier way to use the InputTextLayout, I have created this library that cuts your XML code to less than the half, and also provides you with the ability to set an error message as well as a hint message and an easy way to do your validations. https://github.com/TeleClinic/SmartEditText

Simply add

compile 'com.github.TeleClinic:SmartEditText:0.1.0'

Then you can do something like this:

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/emailSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Email"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Wrong email format"
    app:setRegexType="EMAIL_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/passwordSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Password"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setPasswordField="true"
    app:setRegexErrorMsg="Weak password"
    app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/ageSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Age"
    app:setMandatory="false"
    app:setRegexErrorMsg="Is that really your age :D?"
    app:setRegexString=".*\\d.*" />

How should I unit test multithreaded code?

I handle unit tests of threaded components the same way I handle any unit test, that is, with inversion of control and isolation frameworks. I develop in the .Net-arena and, out of the box, the threading (among other things) is very hard (I'd say nearly impossible) to fully isolate.

Therefore, I've written wrappers that looks something like this (simplified):

public interface IThread
{
    void Start();
    ...
}

public class ThreadWrapper : IThread
{
    private readonly Thread _thread;
     
    public ThreadWrapper(ThreadStart threadStart)
    {
        _thread = new Thread(threadStart);
    }

    public Start()
    {
        _thread.Start();
    }
}
    
public interface IThreadingManager
{
    IThread CreateThread(ThreadStart threadStart);
}

public class ThreadingManager : IThreadingManager
{
    public IThread CreateThread(ThreadStart threadStart)
    {
         return new ThreadWrapper(threadStart)
    }
}

From there, I can easily inject the IThreadingManager into my components and use my isolation framework of choice to make the thread behave as I expect during the test.

That has so far worked great for me, and I use the same approach for the thread pool, things in System.Environment, Sleep etc. etc.

How to parse a month name (string) to an integer for comparison in C#?

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Creating a 3D sphere in Opengl using Visual C++

Here's the code:

glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

localhost refused to connect Error in visual studio

For me the issue was the configuration was set to a custom AsLive instead of Debug.

enter image description here

Setting that back sorted it for me.

An efficient compression algorithm for short text strings

Check out Smaz:

Smaz is a simple compression library suitable for compressing very short strings.

jquery function setInterval

Don't pass the result of swapImages to setInterval by invoking it. Just pass the function, like this:

setInterval(swapImages, 1000);

getting "No column was specified for column 2 of 'd'" in sql server cte?

evidently, as stated in the parser response, a column name is needed for both cases. In either versions the columns of "d" are not named.

in case 1: your column 2 of d is sum(totalitems) which is not named. duration will retain the name "duration"

in case 2: both month(clothdeliverydate) and SUM(CONVERT(INT, deliveredqty)) have to be named

Is floating point math broken?

It's actually pretty simple. When you have a base 10 system (like ours), it can only express fractions that use a prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10. In contrast, 1/3, 1/6, and 1/7 are all repeating decimals because their denominators use a prime factor of 3 or 7. In binary (or base 2), the only prime factor is 2. So you can only express fractions cleanly which only contain 2 as a prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly as decimals. While, 1/5 or 1/10 would be repeating decimals. So 0.1 and 0.2 (1/10 and 1/5) while clean decimals in a base 10 system, are repeating decimals in the base 2 system the computer is operating in. When you do math on these repeating decimals, you end up with leftovers which carry over when you convert the computer's base 2 (binary) number into a more human readable base 10 number.

From https://0.30000000000000004.com/

Use dynamic variable names in JavaScript

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).

So if you create variables like this:

var a = 1,
    b = 2,
    c = 3;

In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

Those can get accessed by using the "dot" or "bracket" notation:

var name = window.a;

or

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

function foobar() {
   this.a = 1;
   this.b = 2;

   var name = window['a']; // === undefined
   alert(name);
   name = this['a']; // === 1
   alert(name);
}

new foobar();

new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:

var a = 1,
    b = 2;

Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).

What is the easiest way to parse an INI file in Java?

As mentioned, ini4j can be used to achieve this. Let me show one other example.

If we have an INI file like this:

[header]
key = value

The following should display value to STDOUT:

Ini ini = new Ini(new File("/path/to/file"));
System.out.println(ini.get("header", "key"));

Check the tutorials for more examples.

CryptographicException 'Keyset does not exist', but only through WCF

This issue is got resolved after adding network service role.

CERTIFICATE ISSUES 
Error :Keyset does not exist means System might not have access to private key
Error :Enveloped data … 
Step 1:Install certificate in local machine not in current user store
Step 2:Run certificate manager
Step 3:Find your certificate in the local machine tab and right click manage privatekey and check in allowed personnel following have been added:
a>Administrators
b>yourself
c>'Network service'
And then provide respective permissions.

## You need to add 'Network Service' and then it will start working.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Regex: Remove lines containing "help", etc

This is also possible with Notepad++:

  • Go to the search menu, Ctrl + F, and open the Mark tab.
  • Check Bookmark line (if there is no Mark tab update to the current version).

  • Enter your search term and click Mark All

    • All lines containing the search term are bookmarked.
  • Now go to the menu SearchBookmarkRemove Bookmarked lines

  • Done.

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

UITextField border color

Update for swift 5.0

textField.layer.masksToBounds = true
textField.layer.borderColor = UIColor.blue.cgColor
textField.layer.borderWidth = 1.0

How can I convert IPV6 address to IPV4 address?

While there are IPv6 equivalents for the IPv4 address range, you can't convert all IPv6 addresses to IPv4 - there are more IPv6 addresses than there are IPv4 addresses.

The only sane way around this issue is to update your application to be able to understand and store IPv6 addresses.

How to change a package name in Eclipse?

Try creating a new package and then move your files in there.

A short overview : http://www.tutorialspoint.com/eclipse/eclipse_create_java_package.htm

How can I compare time in SQL Server?

convert(varchar(5), thedate, 108) between @leftTime and @rightTime

Explanation:

if you have varchar(5) you will obtain HH:mm

if you have varchar(8) you obtain HH:mm ss

108 obtains only the time from the SQL date

@leftTime and @rightTime are two variables to compare

Nested ifelse statement

# Read in the data.

idnat=c("french","french","french","foreign")
idbp=c("mainland","colony","overseas","foreign")

# Initialize the new variable.

idnat2=as.character(vector())

# Logically evaluate "idnat" and "idbp" for each case, assigning the appropriate level to "idnat2".

for(i in 1:length(idnat)) {
  if(idnat[i] == "french" & idbp[i] == "mainland") {
    idnat2[i] = "mainland"
} else if (idnat[i] == "french" & (idbp[i] == "colony" | idbp[i] == "overseas")) {
  idnat2[i] = "overseas"
} else {
  idnat2[i] = "foreign"
} 
}

# Create a data frame with the two old variables and the new variable.

data.frame(idnat,idbp,idnat2) 

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

How to test if a string is JSON or not?

If the server is responding with JSON then it would have an application/json content-type, if it is responding with a plain text message then it should have a text/plain content-type. Make sure the server is responding with the correct content-type and test that.

How do I use Comparator to define a custom sort order?

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

and

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

Collections.sort(carList, new ColorComparator());

the MySQL service on local computer started and then stopped

In my case, I tried to open a DOS prompt and go to the MySQL bin\ directory and issue the below command:

mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" --standalone --console

And it shows me I was missing the "C:\Program Files\MySQL\MySQL Server 5.0\Uploads" folder; I built one and problem solved.

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

Step 1: Right button mouse > Select "Edit Top 200 Rows"

Edit top 200 rows

Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

Navigate to Query Designer > Pane > SQL

Step 3: Modify the query

Modify the query

Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

enter image description here

MySQL Install: ERROR: Failed to build gem native extension

Attention: You need to specify -- key, and than --with-mysql-config=/usr/local/mysql/bin/mysql_config

To check if string contains particular word

It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.

boolean checkWordExistence(String word, String sentence) {
    if (sentence.contains(word)) {
        int start = sentence.indexOf(word);
        int end = start + word.length();

        boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
        boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));

        return valid_left && valid_right;
    }
    return false;
}

Output:

checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true

P.S Make sure you have filtered out any commas or full stops beforehand.

Facebook Callback appends '#_=_' to Return URL

This can become kind of a serious issue if you're using a JS framework with hashbang (/#!/) URLs, e.g. Angular. Indeed, Angular will consider URLs with a non-hashbang fragment as invalid and throw an error :

Error: Invalid url "http://example.com/#_=_", missing hash prefix "#!".

If you're in such a case (and redirecting to your domain root), instead of doing :

window.location.hash = ''; // goes to /#, which is no better

Simply do :

window.location.hash = '!'; // goes to /#!, which allows Angular to take care of the rest

What USB driver should we use for the Nexus 5?

This worked for me:

  1. Download the Nexus 5 Drivers from Google USB Driver
  2. Extract the ZIP contents and place all files in a single folder on your desktop.
  3. Connect your device to your computer.
  4. Launch the Device Manager on your PC.
  5. Now you should see the Nexus 5 listed in the hardware list.
  6. Right-click the ‘Nexus 5' line and then click on Update Driver Software.
  7. Next, click the ‘browse my computer’ option.
  8. In the new window, click on ‘Browse…’ button.
  9. Go to folder unzipped at step 2. Select the folder where you extract the USB drivers. Click Next.
    • Make sure to tick the subfolder box too.
  10. Now, the Windows installer will search for Nexus 5 drivers. Click Install when asked for permission.
  11. Wait for the process to complete and then check the Device Manager list to confirm that the installation was successful.

Source: Download and Install Google Nexus 5 USB Drivers (ADB / Fastboot)

iReport not starting using JRE 8

I fixed this on my PC, on my environment iReport was iReport-5.1.0 , both jdk 7 and jdk 8 had been installed.

but iReport did not load

fix:- 1. Find the iReport.conf //C:\Program Files (x86)\Jaspersoft\iReport-5.1.0\etc

  1. Open it on text editor

  2. copy your jdk installation path //C:\Program Files (x86)\Java\jdk1.8.0_60

  3. add jdkhome= into the ireport.conf file jdkhome="C:/Program Files (x86)/Java/jdk1.8.0_60"

enter image description here

Now iReport will work

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

Ignore self-signed ssl cert using Jersey Client

After some searching and trawling through some old stackoverflow questions I've found a solution in a previously asked SO question:

Here's the code that I ended up using.

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){return null;}
    public void checkClientTrusted(X509Certificate[] certs, String authType){}
    public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
    ;
}

How to process POST data in Node.js?

You can use the express middleware, which now has body-parser built into it. This means all you need to do is the following:

import express from 'express'

const app = express()

app.use(express.json())

app.post('/thing', (req, res) => {
  console.log(req.body) // <-- this will access the body of the post
  res.sendStatus(200)
})

That code example is ES6 with Express 4.16.x

Git keeps asking me for my ssh key passphrase

I would try the following:

  1. Start GitBash
  2. Edit your ~/.bashrc file
  3. Add the following lines to the file

SSH_ENV=$HOME/.ssh/environment

# start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."
    # spawn ssh-agent
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
    echo succeeded
    chmod 600 ${SSH_ENV}
    . ${SSH_ENV} > /dev/null
    /usr/bin/ssh-add
}

if [ -f "${SSH_ENV}" ]; then
     . ${SSH_ENV} > /dev/null
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
        start_agent;
    }
else
    start_agent;
fi
  1. Save and close the file
  2. Close GitBash
  3. Reopen GitBash
  4. Enter your passphrase

iPad WebApp Full Screen in Safari

Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.

Here's my full article on how to implement fullscreen capability on your web app.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host=127.0.0.1 -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';

mysql>FLUSH PRIVILEGES;

mysql> SELECT host FROM mysql.user WHERE User = 'root';

How do you determine the ideal buffer size when using FileInputStream?

As already mentioned in other answers, use BufferedInputStreams.

After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.

Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.

(Hmm... with multiple cores, threads might help.)

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

in the first you should make form like this :

<form method="post" enctype="multipart/form-data" >
   <input type="file" name="file[]" multiple id="file"/>
   <input type="submit" name="ok"  />
</form> 

that is right . now add this code under your form code or on the any page you like

<?php
if(isset($_POST['ok']))
   foreach ($_FILES['file']['name'] as $filename) {
    echo $filename.'<br/>';
}
?>

it's easy... finish

How to terminate a thread when main program ends?

If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.

http://docs.python.org/library/threading.html#threading.Thread.daemon

Multiple ping script in Python

To ping several hosts at once you could use subprocess.Popen():

#!/usr/bin/env python3
import os
import time
from subprocess import Popen, DEVNULL

p = {} # ip -> process
for n in range(1, 100): # start ping processes
    ip = "127.0.0.%d" % n
    p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL)
    #NOTE: you could set stderr=subprocess.STDOUT to ignore stderr also

while p:
    for ip, proc in p.items():
        if proc.poll() is not None: # ping finished
            del p[ip] # remove from the process list
            if proc.returncode == 0:
                print('%s active' % ip)
            elif proc.returncode == 1:
                print('%s no response' % ip)
            else:
                print('%s error' % ip)
            break

If you can run as a root you could use a pure Python ping script or scapy:

from scapy.all import sr, ICMP, IP, L3RawSocket, conf

conf.L3socket = L3RawSocket # for loopback interface
ans, unans = sr(IP(dst="127.0.0.1-99")/ICMP(), verbose=0) # make requests
ans.summary(lambda (s,r): r.sprintf("%IP.src% is alive"))

How to create a popup window (PopupWindow) in Android

are you done with the layout inflating? maybe you can try this!!

View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p

LINQ Aggregate algorithm explained

A picture is worth a thousand words

Reminder:
Func<X, Y, R> is a function with two inputs of type X and Y, that returns a result of type R.

Enumerable.Aggregate has three overloads:


Overload 1:

A Aggregate<A>(IEnumerable<A> a, Func<A, A, A> f)

Aggregate1

Example:

new[]{1,2,3,4}.Aggregate((x, y) => x + y);  // 10


This overload is simple, but it has the following limitations:

  • the sequence must contain at least one element,
    otherwise the function will throw an InvalidOperationException.
  • elements and result must be of the same type.



Overload 2:

B Aggregate<A, B>(IEnumerable<A> a, B bIn, Func<B, A, B> f)

Aggregate2

Example:

var hayStack = new[] {"straw", "needle", "straw", "straw", "needle"};
var nNeedles = hayStack.Aggregate(0, (n, e) => e == "needle" ? n+1 : n);  // 2


This overload is more general:

  • a seed value must be provided (bIn).
  • the collection can be empty,
    in this case, the function will yield the seed value as result.
  • elements and result can have different types.



Overload 3:

C Aggregate<A,B,C>(IEnumerable<A> a, B bIn, Func<B,A,B> f, Func<B,C> f2)


The third overload is not very useful IMO.
The same can be written more succinctly by using overload 2 followed by a function that transforms its result.


The illustrations are adapted from this excellent blogpost.

init-param and context-param

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:/META-INF/PersistenceContext.xml
    </param-value>
</context-param>

I have initialized my PersistenceContext.xml within <context-param> because all my servlets will be interacting with database in MVC framework.

Howerver,

<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:ApplicationContext.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.organisation.project.rest</param-value>
    </init-param>
</servlet>

in the aforementioned code, I am configuring jersey and the ApplicationContext.xml only to rest layer. For the same I am using </init-param>

How to compare numbers in bash?

The bracket stuff (e.g., [[ $a -gt $b ]] or (( $a > $b )) ) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") )).

For example,

a=2.00
b=1

if (( $(bc <<<"$a > $b") )); then 
    echo "a is greater than b"
else
    echo "a is not greater than b"
fi

You can include more than one comparison in the if statement. For example,

a=2.
b=1
c=1.0000

if (( $(bc <<<"$b == $c && $b < $a") )); then 
    echo "b is equal to c but less than a"
else
    echo "b is either not equal to c and/or not less than a"
fi

That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.

How to put a UserControl into Visual Studio toolBox

I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.

Solution:

  1. From Solution Explorer I Right-Clicked the offending user control file and selected Exclude From Project
  2. Rebuild the solution
  3. Right-Click the user control and select Include in Project (assuming you have the Show All Files enabled in the Solution Explorer)

Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.

Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.

Definitive way to trigger keypress events with jQuery

Slightly more concise now with jQuery 1.6+:

var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } );

$('input').trigger(e);

(If you're not using jQuery UI, sub in the appropriate keycode instead.)

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to pass a variable to the SelectCommand of a SqlDataSource?

You can use the built in OnSelecting parameter of asp:SqlDataSource

Example: [.aspx file]

<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [SomeColumn], [AnotherColumn] 
               FROM [SomeTable]
               WHERE [Dynamic_Variable_Column] = @DynamicVariable"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
    <asp:Parameter Name="DynamicVariable" Type="String"/>
</SelectParameters>

Then in your code behind implement your OnSelecting method: [.aspx.cs]

protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
     e.Command.Parameters["@DynamicVariable"].Value = (whatever value you want);
}

You can also use this for the other types of DB operations just implement your own methods:

OnInserting="SqldsExample_Inserting"
OnUpdating="SqldsExample_Updating"
OnDeleting="SqldsExample_Deleting"

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Try using ChromeDriverManager

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager 
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.set_headless()
browser =webdriver.Chrome(ChromeDriverManager().install(),chrome_options=chrome_options)
browser.get('https://google.com')
# capture the screen
browser.get_screenshot_as_file("capture.png")

Event system in Python

If you wanted to do more complicated things like merging events or retry you can use the Observable pattern and a mature library that implements that. https://github.com/ReactiveX/RxPY . Observables are very common in Javascript and Java and very convenient to use for some async tasks.

from rx import Observable, Observer


def push_five_strings(observer):
        observer.on_next("Alpha")
        observer.on_next("Beta")
        observer.on_next("Gamma")
        observer.on_next("Delta")
        observer.on_next("Epsilon")
        observer.on_completed()


class PrintObserver(Observer):

    def on_next(self, value):
        print("Received {0}".format(value))

    def on_completed(self):
        print("Done!")

    def on_error(self, error):
        print("Error Occurred: {0}".format(error))

source = Observable.create(push_five_strings)

source.subscribe(PrintObserver())

OUTPUT:

Received Alpha
Received Beta
Received Gamma
Received Delta
Received Epsilon
Done!

How to indent HTML tags in Notepad++

Building on Constantin's answer, here's the essence of what I learned while transitioning to Notepad++ as my primary HTML editor.

Install Notepad++ 32-bit

There's no 64-bit version of Tidy2 and some other popular plugins. The 32-bit version of NPP has few practical downsides, so axe the 64-bit version.

Install the Plugin Manager

Plugin Manager isn't strictly necessary for plugin usage. It does make things much easier, though.

Plugin Manager was eliminated from the core package apparently because the developer didn't like some included attribution linking.

You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.

It's a manual install, but it's not difficult.

  1. Download the UNI (32-bit) zip package and extract it. Inside you'll see folders called plugins and updater. Each contains one file.
  2. Drag those two files to the respective identically-named folders in your Notepad++ installation directory. Typically that's C:\Program Files (x86)\Notepad++.
  3. Restart Notepad++ and follow any install/update prompts.

Now you'll see a new entry under Plugins for Plugin Manager.

Install Tidy2 (or your preferred alternative)

In Plugin Manager, check the box for Tidy2. Click Install. Restart when prompted.

To use Tidy2, select one of the preconfigured profiles in its Plugins submenu item, or create your own.

release Selenium chromedriver.exe from memory

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.

// Capabilities to be passed to the webdriver instance.
capabilities: {
  'directConnect': true,
  'browserName': 'chrome',
  chromeOptions: {
      args: [
        //"--headless",
        //"--hide-scrollbars",
        "--disable-software-rasterizer",
        '--disable-dev-shm-usage',
        //"--no-sandbox",
        "incognito",
        "--disable-gpu",
        "--window-size=1920x1080"]
  }
},

How to ensure a <select> form field is submitted when it is disabled?

Just add a line before submit.

$("#XYZ").removeAttr("disabled");

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

How to get a table cell value using jQuery?

a less-jquerish approach:

$('#mytable tr').each(function() {
    if (!this.rowIndex) return; // skip first row
    var customerId = this.cells[0].innerHTML;
});

this can obviously be changed to work with not-the-first cells.

Chart.js v2 hide dataset labels

add:

Chart.defaults.global.legend.display = false;

in the starting of your script code;

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

i had this issue before and the comments here helped in the past but this time it did not. i checked my proguard configuration and i removed the following lines and then it worked so proguard can have something to do with this error:

 -optimizationpasses 5
        -overloadaggressively
        -repackageclasses ''
        -allowaccessmodification
        -dontskipnonpubliclibraryclassmembers

What is the purpose of the vshost.exe file?

I'm not sure, but I believe it is a debugging optimization. However, I usually turn it off (see Debug properties for the project) and I don't notice any slowdown and I see no limitations when it comes to debugging.

Accept function as parameter in PHP

According to @zombat's answer, it's better to validate the Anonymous Functions first:

function exampleMethod($anonFunc) {
    //execute anonymous function
    if (is_callable($anonFunc)) {
        $anonFunc();
    }
}

Or validate argument type since PHP 5.4.0:

function exampleMethod(callable $anonFunc) {}