Programs & Examples On #V4l

v4l ("Video For Linux") is a video capture infrastructure provided by the linux kernel. the historic "v4l" has been obsoleted by the "v4l2" ("Video for Linux 2") infastructure and has been removed from the linux-kernel starting with 2.6.38.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

sudo apt-get install libv4l-dev

Editing for RH based systems :

On a Fedora 16 to install pygame 1.9.1 (in a virtualenv):

sudo yum install libv4l-devel
sudo ln -s /usr/include/libv4l1-videodev.h   /usr/include/linux/videodev.h 

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

json_encode function: special characters

Your input has to be encoded as UTF-8 or ISO-8859-1.

http://www.php.net/manual/en/function.json-encode.php

Because if you try to convert an array of non-utf8 characters you'll be getting 0 as return value.


Since 5.5.0 The return value on failure was changed from null string to FALSE.

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

DISCLAIMER: Please, @juanpa.arrivillaga, if you see this answer, feel free to write your own and I will remove this post.

@juanpa.arrivillaga had mentioned above:

Is there a file name enum.py in your working directory, by any chance?

This was the issue I encountered. I was not aware of the enum module on python at the time and had named my test file enum.py.

Since the file name is the module name, there was a conflict. More info on modules here: https://docs.python.org/2/tutorial/modules.html

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
        return;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
                .getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {

    }
}

public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);
}

public boolean isChunked() {
    return false;
}

public boolean isRepeatable() {
    return false;
}

public boolean isStreaming() {
    return false;
}

public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

public Header getContentEncoding() {
    return null;
}

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");
    }
}

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}

}

Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        post.setEntity(reqEntity);
        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
    } catch (Exception e) {
        Log.e("Upload Exception", "");
        e.printStackTrace();
    }
}

Service for uploading

   <?php
$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    
$flag=0;                 

if (file_exists("Images/".$new_image_name))
{
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
}else{  
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;
}   

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
            if((isset($_REQUEST['email'])))
            {
                     $email = $_REQUEST['email'];
            }

    $sql ="insert into alert(images) values('$static_url')";

     $result=mysql_query($sql);

     if($result){
    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else
       {

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
        }
}
    else{
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
    }
    ?>

How do I push to GitHub under a different username?

I couldn't figure out how to have a 2nd github identity on the one machine (none of these answers worked for me for that), but I did figure out how to be able to push to multiple different github accounts as myself.

Push as same username, but to different github accounts

  1. Set up a 2nd SSH key (like so) for your 2nd github account

  2. Change between accounts thus :

Push with my new 2nd github account

ssh-add -D
ssh-add ~/.ssh/ssh_key_for_my_2nd_account
git push

Push with my main account

ssh-add -D
ssh-add ~/.ssh/id_rsa   
git push

force line break in html table cell

I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out. (I've just been trying to do the same thing!)

You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

How to align input forms in HTML

css I used to solve this problem, similar to Gjaa but styled better

p
{
    text-align:center;
        }
.styleform label
{
    float:left;
    width: 40%;
    text-align:right;
    }
.styleform input
{
    float:left;
    width: 30%;
    }

Here is my HTML, used specifically for a simple registration form with no php code

<form id="registration">
    <h1>Register</h1>
    <div class="styleform">
    <fieldset id="inputs">
        <p><label>Name:</label> 
          <input id="name" type="text" placeholder="Name" autofocus required>
        </p>
        <p><label>Email:</label>   
          <input id="email" type="text" placeholder="Email Address" required>
        </p>
        <p><label>Username:</label>
          <input id="username" type="text" placeholder="Username" autofocus required>
        </p>
        <p>   
          <label>Password:</label>
          <input id="password" type="password" placeholder="Password" required>
        </p>
    </fieldset>
    <fieldset id="actions">

    </fieldset>
    </div>
    <p>
          <input type="submit" id="submit" value="Register">
          </p>

It's very simple, and I'm just beginning, but it worked quite nicely

Timeout a command in bash without unnecessary delay

OS X doesn't use bash 4 yet, nor does it have /usr/bin/timeout, so here's a function that works on OS X without home-brew or macports that is similar to /usr/bin/timeout (based on Tino's answer). Parameter validation, help, usage, and support for other signals are an exercise for reader.

# implement /usr/bin/timeout only if it doesn't exist
[ -n "$(type -p timeout 2>&1)" ] || function timeout { (
    set -m +b
    sleep "$1" &
    SPID=${!}
    ("${@:2}"; RETVAL=$?; kill ${SPID}; exit $RETVAL) &
    CPID=${!}
    wait %1
    SLEEPRETVAL=$?
    if [ $SLEEPRETVAL -eq 0 ] && kill ${CPID} >/dev/null 2>&1 ; then
      RETVAL=124
      # When you need to make sure it dies
      #(sleep 1; kill -9 ${CPID} >/dev/null 2>&1)&
      wait %2
    else
      wait %2
      RETVAL=$?
    fi
    return $RETVAL
) }

How to use jQuery to get the current value of a file input field

In Chrome 8 the path is always 'C:\fakepath\' with the correct file name.

Generate random integers between 0 and 9

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

Android java.lang.NoClassDefFoundError

You can also get this error if you try to include a jar which was compiled with jdk 1.7 instead of 1.6.

In my case, I figured this out by trying to package my app with the Ant scripts provided by the SDK, instead of ADT, and I noticed these errors, which ADT did not show me:

  [dex] Pre-Dexing libjingle_peerconnection.jar -> libjingle_peerconnection-2f82c9bf868a6c58eaf2c3b2fe6a09f3.jar
   [dx]
   [dx] trouble processing:
   [dx] bad class file magic (cafebabe) or version (0033.0000)
   [dx] ...while parsing org/webrtc/StatsReport$Value.class
   [dx] ...while processing org/webrtc/StatsReport$Value.class

I recompiled my jar with jdk 1.6 and the error was fixed.

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

Javascript: how to validate dates in format MM-DD-YYYY?

This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.

function isValidDate(date)
{
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[1];
    var m = matches[2]-1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
           composedDate.getMonth() == m &&
           composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

How to install pip in CentOS 7?

There is a easy way of doing this by just using easy_install (A Setuptools to package python librarie).

  • Assumption. Before doing this check whether you have python installed into your Centos machine (at least 2.x).

  • Steps to install pip.

    1. So lets do install easy_install,

      sudo yum install python-setuptools python-setuptools-devel

    2. Now lets do pip with easy_install,

      sudo easy_install pip

That's Great. Now you have pip :)

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

How should I have explained the difference between an Interface and an Abstract class?

Here’s an explanation centred around Java 8, that tries to show the key differences between abstract classes and interfaces, and cover all the details needed for the Java Associate Exam.

Key concepts:

  • A class can extend only one class, but it can implement any number of interfaces
  • Interfaces define what a class does, abstract classes define what it is
  • Abstract classes are classes. They can’t be instantiated, but otherwise behave like normal classes
  • Both can have abstract methods and static methods
  • Interfaces can have default methods & static final constants, and can extend other interfaces
  • All interface members are public (until Java 9)

Interfaces define what a class does, abstract classes define what it is

Per Roedy Green:

Interfaces are often used to describe the abilities of a class, not its central identity, e.g. An Automobile class might implement the Recyclable interface, which could apply to many unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Dalmatian descendants are Dogs, they are not merely dogable.

Pre Java 8, @Daniel Lerps’s answer was spot on, that interfaces are like a contract that the implementing class has to fulfil.

Now, with default methods, they are more like a Mixin, that still enforces a contract, but can also give code to do the work. This has allowed interfaces to take over some of the use cases of abstract classes.

The point of an abstract class is that it has missing functionality, in the form of abstract methods. If a class doesn’t have any abstract behaviour (which changes between different types) then it could be a concrete class instead.

Abstract classes are classes

Here are some of the normal features of classes which are available in abstract classes, but not in interfaces:

  • Instance variables / non-final variables. And therefore…
  • Methods which can access and modify the state of the object
  • Private / protected members (but see note on Java 9)
  • Ability to extend abstract or concrete classes
  • Constructors

Points to note about abstract classes:

  • They cannot be final (because their whole purpose is to be extended)
  • An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods

Abstract methods

Both abstract classes and interfaces can have zero to many abstract methods. Abstract methods:

  • Are method signatures without a body (i.e. no {})
  • Must be marked with the abstract keyword in abstract classes. In interfaces this keyword is unnecessary
  • Cannot be private (because they need to be implemented by another class)
  • Cannot be final (because they don’t have bodies yet)
  • Cannot be static (because reasons)

Note also that:

  • Abstract methods can be called by non-abstract methods in the same class/interface
  • The first concrete class that extends an abstract class or implements an interface must provide an implementation for all the abstract methods

Static methods

A static method on an abstract class can be called directly with MyAbstractClass.method(); (i.e. just like for a normal class, and it can also be called via a class that extends the abstract class).

Interfaces can also have static methods. These can only be called via the name of the interface (MyInterface.method();). These methods:

  • Cannot be abstract, i.e. must have a body (see ‘because reasons’ above)
  • Are not default (see below)

Default methods

Interfaces can have default methods which must have the default keyword and a method body. These can only reference other interface methods (and can’t refer to a particular implementation's state). These methods:

  • Are not static
  • Are not abstract (they have a body)
  • Cannot be final (the name “default” indicates that they may be overridden)

If a class implements two interfaces with default methods with the same signatures this causes a compilation error, which can be resolved by overriding the method.

Interfaces can have static final constants

Interfaces can only contain the types of methods describe above, or constants.

Constants are assumed to be static and final, and can be used without qualification in classes that implement the interface.

All interface members are public

In Java 8 all members of interfaces (and interfaces themselves) are assumed to be public, and cannot be protected or private (but Java 9 does allow private methods in interfaces).

This means that classes implementing an interface must define the methods with public visibility (in line with the normal rule that a method cannot be overridden with lower visibility).

How to create a bash script to check the SSH connection?

Try:

echo quit | telnet IP 22 2>/dev/null | grep Connected

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

jQuery preventDefault() not triggered

Try this:

$("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
});

Inject service in app.config

I don't think you're supposed to be able to do this, but I have successfully injected a service into a config block. (AngularJS v1.0.7)

angular.module('dogmaService', [])
    .factory('dogmaCacheBuster', [
        function() {
            return function(path) {
                return path + '?_=' + Date.now();
            };
        }
    ]);

angular.module('touch', [
        'dogmaForm',
        'dogmaValidate',
        'dogmaPresentation',
        'dogmaController',
        'dogmaService',
    ])
    .config([
        '$routeProvider',
        'dogmaCacheBusterProvider',
        function($routeProvider, cacheBuster) {
            var bust = cacheBuster.$get[0]();

            $routeProvider
                .when('/', {
                    templateUrl: bust('touch/customer'),
                    controller: 'CustomerCtrl'
                })
                .when('/screen2', {
                    templateUrl: bust('touch/screen2'),
                    controller: 'Screen2Ctrl'
                })
                .otherwise({
                    redirectTo: bust('/')
                });
        }
    ]);

angular.module('dogmaController', [])
    .controller('CustomerCtrl', [
        '$scope',
        '$http',
        '$location',
        'dogmaCacheBuster',
        function($scope, $http, $location, cacheBuster) {

            $scope.submit = function() {
                $.ajax({
                    url: cacheBuster('/customers'),  //server script to process data
                    type: 'POST',
                    //Ajax events
                    // Form data
                    data: formData,
                    //Options to tell JQuery not to process data or worry about content-type
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function() {
                        $location
                            .path('/screen2');

                        $scope.$$phase || $scope.$apply();
                    }
                });
            };
        }
    ]);

How do you generate dynamic (parameterized) unit tests in Python?

I use metaclasses and decorators for generate tests. You can check my implementation python_wrap_cases. This library doesn't require any test frameworks.

Your example:

import unittest
from python_wrap_cases import wrap_case


@wrap_case
class TestSequence(unittest.TestCase):

    @wrap_case("foo", "a", "a")
    @wrap_case("bar", "a", "b")
    @wrap_case("lee", "b", "b")
    def testsample(self, name, a, b):
        print "test", name
        self.assertEqual(a, b)

Console output:

testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar
FAIL
testsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo
ok
testsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee
ok

Also you may use generators. For example this code generate all possible combinations of tests with arguments a__list and b__list

import unittest
from python_wrap_cases import wrap_case


@wrap_case
class TestSequence(unittest.TestCase):

    @wrap_case(a__list=["a", "b"], b__list=["a", "b"])
    def testsample(self, a, b):
        self.assertEqual(a, b)

Console output:

testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok
testsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok

How to style a select tag's option element?

It's a choice (from browser devs or W3C, I can't find any W3C specification about styling select options though) not allowing to style select options.

I suspect this would be to keep consistency with native choice lists.
(think about mobile devices for example).

3 solutions come to my mind:

  • Use Select2 which actually converts your selects into uls (allowing many things)
  • Split your selects into multiple in order to group values
  • Split into optgroup

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

Could not find a version that satisfies the requirement tensorflow

Tensorflow seems to need special versions of tools and libs. Pip only takes care of python version.

To handle this in a professional way (means it save tremendos time for me and others) you have to set a special environment for each software like this.

An advanced tool for this is conda.

I installed Tensorflow with this commands:

sudo apt install python3

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1

sudo apt install python3-pip

sudo apt-get install curl

curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-latest-Linux-x86_64.sh

yes

source ~/.bashrc

  • installs its own phyton etc

nano .bashrc

  • maybe insert here your proxies etc.

conda create --name your_name python=3

conda activate your_name

conda install -c conda-forge tensorflow

  • check everything went well

python -c "import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))"

PS: some commands that may be helpful conda search tensorflow

https://www.tensorflow.org/install/pip

uses virtualenv. Conda is more capable. Miniconda ist sufficient; the full conda is not necessary

CSS div element - how to show horizontal scroll bars only?

I also had to add white-space: nowrap; to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.

Exploitable PHP functions

Plattform-specific, but also theoretical exec vectors:

  • dotnet_load()
  • new COM("WScript.Shell")
  • new Java("java.lang.Runtime")
  • event_new() - very eventually

And there are many more disguising methods:

  • proc_open is an alias for popen
  • call_user_func_array("exE".chr(99), array("/usr/bin/damage", "--all"));
  • file_put_contents("/cgi-bin/nextinvocation.cgi") && chmod(...)
  • PharData::setDefaultStub - some more work to examine code in .phar files
  • runkit_function_rename("exec", "innocent_name") or APD rename_function

Add Insecure Registry to Docker

Anyone looking to add insecure registry on amazon linux 2: You will have to change the setting under /etc/sysconfig/docker and then restart docker daemon: here's how my /etc/sysconfig/docker looks like

# The max number of open files for the daemon itself, and all
# running containers.  The default value of 1048576 mirrors the value
# used by the systemd service unit.
DAEMON_MAXFILES=1048576

# Additional startup options for the Docker daemon, for example:
# OPTIONS="--ip-forward=true --iptables=true"
# By default we limit the number of open files per container
OPTIONS="--default-ulimit nofile=1024:4096 --insecure-registry yourinsecureregistryhostname:port"

# How many seconds the sysvinit script waits for the pidfile to appear
# when starting the daemon.
DAEMON_PIDFILE_TIMEOUT=10

PNG transparency issue in IE8

I had the same thing happen to a PNG with transparency that was set as the background-image of an <A> element with opacity applied.

The fix was to set the background-color of the <A> element.

So, the following:

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

Turns into:

/* "Overwritten" by the background-image. However this fixes the IE7 and IE8 PNG-transparency-plus-opacity bug. */
background-color: #FFFFFF; 

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Checking if a variable is defined?

You can try:

unless defined?(var)
  #ruby code goes here
end
=> true

Because it returns a boolean.

how to call url of any other website in php

Depending on what you mean, either redirect or use curl.

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Why are my PHP files showing as plain text?

Yet another reason (not for this case, but maybe it'll save some nerves for someone) is that in PHP 5.5 short open tags <? phpinfo(); ?> are disabled by default.

So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

How would you count occurrences of a string (actually a char) within a string?

These both only work for single-character search terms...

countOccurences("the", "the answer is the answer");

int countOccurences(string needle, string haystack)
{
    return (haystack.Length - haystack.Replace(needle,"").Length) / needle.Length;
}

may turn out to be better for longer needles...

But there has to be a more elegant way. :)

Apply .gitignore on an existing repository already tracking large number of files

If you added your .gitignore too late, git will continue to track already commited files regardless. To fix this, you can always remove all cached instances of the unwanted files.

First, to check what files are you actually tracking, you can run:

git ls-tree --name-only --full-tree -r HEAD

Let say that you found unwanted files in a directory like cache/ so, it's safer to target that directory instead of all of your files.

So instead of:

git rm -r --cached .

It's safer to target the unwanted file or directory:

git rm -r --cached cache/

Then proceed to add all changes,

git add .

and commit...

git commit -m ".gitignore is now working"

Reference: https://amyetheredge.com/code/13.html

OS X cp command in Terminal - No such file or directory

Summary of solution:

directory is neither an existing file nor directory. As it turns out, the real name is directory.1 as revealed by ls -la $HOME/Desktop/.

The complete working command is

cp -R $HOME/directory.1/file.bundle /library/application\ support/directory/

with the -R parameter for recursive copy (compulsory for copying directories).

How do I send an HTML email?

you have to call

msg.saveChanges();

after setting content type.

How to simulate "Press any key to continue?"

I looked into what you are trying to achieve, because I remember I wanted to do the same thing. Inspired by Vinay I wrote something that works for me and I sort of understand. But I am not an expert, so please be careful.

I don't know how Vinay knows you are using Mac OS X. But it should work kind of like this with most unix-like OS. Really helpful as resource is opengroup.org

Make sure to flush the buffer before using the function.

#include <stdio.h>
#include <termios.h>        //termios, TCSANOW, ECHO, ICANON
#include <unistd.h>     //STDIN_FILENO


void pressKey()
{
    //the struct termios stores all kinds of flags which can manipulate the I/O Interface
    //I have an old one to save the old settings and a new 
    static struct termios oldt, newt;
    printf("Press key to continue....\n");

    //tcgetattr gets the parameters of the current terminal
    //STDIN_FILENO will tell tcgetattr that it should write the settings
    // of stdin to oldt
    tcgetattr( STDIN_FILENO, &oldt);
    //now the settings will be copied 
    newt = oldt;

    //two of the c_lflag will be turned off
    //ECHO which is responsible for displaying the input of the user in the terminal
    //ICANON is the essential one! Normally this takes care that one line at a time will be processed
    //that means it will return if it sees a "\n" or an EOF or an EOL
    newt.c_lflag &= ~(ICANON | ECHO );      

    //Those new settings will be set to STDIN
    //TCSANOW tells tcsetattr to change attributes immediately. 
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    //now the char wil be requested
    getchar();

    //the old settings will be written back to STDIN
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);

}


int main(void)
{
  pressKey();
  printf("END\n");
  return 0;
}

O_NONBLOCK seems also to be an important flag, but it didn't change anything for me.

I appreciate if people with some deeper knowledge would comment on this and give some advice.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

How/when to generate Gradle wrapper files?

As gradle built-in tasks is deprecated in 4.8, try below

wrapper {
   gradleVersion = '2.0' //version required
}

and run

gradle wrapper

How to terminate a window in tmux?

For me solution looks like:

  1. ctrl+b q to show pane numbers.
  2. ctrl+b x to kill pane.

Killing last pane will kill window.

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)
{

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);

}

How can I bring my application window to the front?

While I agree with everyone, this is no-nice behavior, here is code:

[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);   


SetForegroundWindow(Handle.ToInt32());

Update

David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

CSS rule to apply only if element has BOTH classes

div.abc.xyz {
    /* rules go here */
}

... or simply:

.abc.xyz {
    /* rules go here */
}

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>

How do I get the parent directory in Python?

os.path.abspath(os.path.join(somepath, '..'))

Observe:

import posixpath
import ntpath

print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))

How does one capture a Mac's command key via JavaScript?

if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple

https://www.npmjs.com/package/vue-shortkey

v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"

Differences between .NET 4.0 and .NET 4.5 in High level in .NET


.NET Framework 4


Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).
  • Introduce Common Language Runtime (CLR) 4.0.

After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.


.NET Framework 4.5


.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.

1. .NET for Metro style apps

Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.

2. Core Features

  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
  • Ability to define the culture for an application domain.
  • Console support for Unicode (UTF-16) encoding.
  • Support for versioning of cultural string ordering and comparison data.
  • Better performance when retrieving resources.
  • Zip compression improvements to reduce the size of a compressed file.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

3. Managed Extensibility Framework (MEF)

  • Support for generic types.
  • Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
  • Multiple scopes.

4. Asynchronous operations

In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.

5. ASP.NET

  • Support for new HTML5 form types.
  • Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
  • Support for unobtrusive JavaScript in client-side validation scripts.
  • Improved handling of client script through bundling and minification for improved page performance.
  • Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
  • Support for WebSocket protocol.
  • Support for reading and writing HTTP requests and responses asynchronously.
  • Support for asynchronous modules and handlers.
  • Support for content distribution network (CDN) fallback in the ScriptManager control.

6. Networking

  • Provides a new programming interface for HTTP applications: System.Net.Http namespace and System.Net.Http.Headers namespaces are added.
  • Other improvements: Improved internationalization and IPv6 support. RFC-compliant URI support. Support for Internationalized Domain Name (IDN) parsing. Support for Email Address Internationalization (EAI).

7. Windows Presentation Foundation (WPF)

  • The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
  • The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
  • New features for the VirtualizingPanel and Dispatcher classes.
  • Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
  • Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface and retrieval of data binding information from a binding expression.
  • Repositioning of data as the values change (live shaping).
  • Better integration between WPF and Win32 user interface components.
  • Ability to check whether the data context for an item container is disconnected.
  • Ability to set the amount of time that should elapse between property changes and data source updates.
  • Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

8. Windows Communication Foundation (WCF)

In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

  • Simplification of generated configuration files.
  • Support for contract-first development.
  • Ability to configure ASP.NET compatibility mode more easily.
  • Changes in default transport property values to reduce the likelihood that you will have to set them.
  • Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
  • Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
  • New asynchronous streaming support.
  • New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
  • Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
  • Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
  • Support for configuring services in code.
  • XML Editor tooltips.
  • ChannelFactory caching support.
  • Binary encoder compression support.
  • Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. A client sends a message to a service and expects no response from the service.
  • Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.
  • Support for WCF services that use internationalized domain names (IDNs).

9. Tools

  • Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows Store apps from a .resources file embedded in a .NET Framework assembly.
  • Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. The command-line tool generates profile data for native image application assemblies.

For more information and access to reference links, please visit:

===========.Net 4.5 Poster=========

enter image description here

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

C++ Vector of pointers

By dynamically allocating a Movie object with new Movie(), you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as

std::vector<Movie *> movies

But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.

Shortest distance between a point and a line segment

Eigen C++ Version for 3D line segment and point

// Return minimum distance between line segment: head--->tail and point
double MinimumDistance(Eigen::Vector3d head, Eigen::Vector3d tail,Eigen::Vector3d point)
{
    double l2 = std::pow((head - tail).norm(),2);
    if(l2 ==0.0) return (head - point).norm();// head == tail case

    // Consider the line extending the segment, parameterized as head + t (tail - point).
    // We find projection of point onto the line.
    // It falls where t = [(point-head) . (tail-head)] / |tail-head|^2
    // We clamp t from [0,1] to handle points outside the segment head--->tail.

    double t = max(0,min(1,(point-head).dot(tail-head)/l2));
    Eigen::Vector3d projection = head + t*(tail-head);

    return (point - projection).norm();
}

how to delete a specific row in codeigniter?

a simple way:

in view(pass the id value):

<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>

in controller(receive the id):

$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);

in model(get the passed args):

function row_delete($id){}

Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.

import android packages cannot be resolved

I just had the same problem after accepting a Java update--scores of build errors and android import not recognized. On checking the build path in Project=>Properties, I found that the check box for Android 4.3 had somehow gotten cleared. Checking it resolved all the import errors without my even having to restart the IDE or run a project clean.

scp (secure copy) to ec2 instance without password

copy a file from a local server to a remote server

sudo scp -i my-pem-file.pem ./source/test.txt [email protected]:~/destination/

copy a file from a remote server to a local machine

sudo scp -i my-pem-file.pem [email protected]:~/source/of/remote/test.txt ./where/to/put

So the basically syntax is:-

scp -i my-pem-file.pem username@source:/location/to/file username@destination:/where/to/put

-i is for the identity_file

ASP.NET Custom Validator Client side & Server Side validation not firing

Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.

So you can't do this...

<script>
  function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />

But this works:

<script>
  function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />

I'm guessing it conflicts with internal .NET Javascript?

How can I roll back my last delete command in MySQL?

If you want rollback data, firstly you need to execute autocommit =0 and then execute query delete, insert, or update.

After executing the query then execute rollback...

Programmatically navigate to another view controller/scene

XCODE 8.2 AND SWIFT 3.0

Present an exist UIViewController

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(loginVC, animated: true, completion: nil)

Push an exist UIViewController

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.navigationController?.pushViewController(loginVC, animated: true)

Remember that you can put the UIViewController Identifier following the next steps:

  • Select Main.storyboard
  • Select your UIViewController
  • Search the Utilities in the right
  • Select the identity inspector
  • Search in section identity "Storyboard ID"
  • Put the Identifier for your UIViewController

enter image description here

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

How to make a Qt Widget grow with the window size?

You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example: enter image description here

To something like this:

enter image description here

Push to GitHub without a password using ssh-key

Additionally for gists, it seems you must leave out the username

git remote set-url origin [email protected]:<Project code>

How to calculate time elapsed in bash script?

With GNU units:

$ units
2411 units, 71 prefixes, 33 nonlinear units
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: s
    * 134
    / 0.0074626866
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: min
    * 2.2333333
    / 0.44776119

Splitting dataframe into multiple dataframes

I had similar problem. I had a time series of daily sales for 10 different stores and 50 different items. I needed to split the original dataframe in 500 dataframes (10stores*50stores) to apply Machine Learning models to each of them and I couldn't do it manually.

This is the head of the dataframe:

head of the dataframe: df

I have created two lists; one for the names of dataframes and one for the couple of array [item_number, store_number].

    list=[]
    for i in range(1,len(items)*len(stores)+1):
    global list
    list.append('df'+str(i))

    list_couple_s_i =[]
    for item in items:
          for store in stores:
                  global list_couple_s_i
                  list_couple_s_i.append([item,store])

And once the two lists are ready you can loop on them to create the dataframes you want:

         for name, it_st in zip(list,list_couple_s_i):
                   globals()[name] = df.where((df['item']==it_st[0]) & 
                                                (df['store']==(it_st[1])))
                   globals()[name].dropna(inplace=True)

In this way I have created 500 dataframes.

Hope this will be helpful!

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

I added the variables in the ~/.bash_profile in the following way. After you are done restart/log out and log in

export M2_HOME=/Users/robin/softwares/apache-maven-3.2.3
export ANT_HOME=/Users/robin/softwares/apache-ant-1.9.4
launchctl setenv M2_HOME $M2_HOME
launchctl setenv ANT_HOME $ANT_HOME
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/robin/softwares/apache-maven-3.2.3/bin:/Users/robin/softwares/apache-ant-1.9.4/bin
launchctl setenv PATH $PATH

NOTE: without restart/log out and log in you can apply these changes using;

source ~/.bash_profile

Adding elements to object

With that row

var element = {};

you define element to be a plain object. The native JavaScript object has no push() method. To add new items to a plain object use this syntax:

element[ yourKey ] = yourValue;

On the other hand you could define element as an array using

var element = [];

Then you can add elements using push().

How to install python developer package?

For me none of the packages mentioned above did help.

I finally managed to install lxml after running:

sudo apt-get install python3.5-dev

Android: How to handle right to left swipe gestures

In order to have Click Listener, DoubleClick Listener, OnLongPress Listener, Swipe Left, Swipe Right, Swipe Up, Swipe Down on Single View you need to setOnTouchListener. i.e,

view.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {

            @Override
            public void onClick() {
                super.onClick();
                // your on click here
            }

            @Override
            public void onDoubleClick() {
                super.onDoubleClick();
                // your on onDoubleClick here
            }

            @Override
            public void onLongClick() {
                super.onLongClick();
                // your on onLongClick here
            }

            @Override
            public void onSwipeUp() {
                super.onSwipeUp();
                // your swipe up here
            }

            @Override
            public void onSwipeDown() {
                super.onSwipeDown();
                // your swipe down here.
            }

            @Override
            public void onSwipeLeft() {
                super.onSwipeLeft();
                // your swipe left here.
            }

            @Override
            public void onSwipeRight() {
                super.onSwipeRight();
                // your swipe right here.
            }
        });

}

For this you need OnSwipeTouchListener class that implements OnTouchListener.

public class OnSwipeTouchListener implements View.OnTouchListener {

private GestureDetector gestureDetector;

public OnSwipeTouchListener(Context c) {
    gestureDetector = new GestureDetector(c, new GestureListener());
}

public boolean onTouch(final View view, final MotionEvent motionEvent) {
    return gestureDetector.onTouchEvent(motionEvent);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        onClick();
        return super.onSingleTapUp(e);
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        onDoubleClick();
        return super.onDoubleTap(e);
    }

    @Override
    public void onLongPress(MotionEvent e) {
        onLongClick();
        super.onLongPress(e);
    }

    // Determines the fling velocity and then fires the appropriate swipe event accordingly
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                }
            } else {
                if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeDown();
                    } else {
                        onSwipeUp();
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}

public void onSwipeUp() {
}

public void onSwipeDown() {
}

public void onClick() {

}

public void onDoubleClick() {

}

public void onLongClick() {

}
}

Make child visible outside an overflow:hidden parent

For others, if clearfix does not solve this for you, add margins to the non-floated sibling that is/are the same as the width(s) of the floated sibling(s).

How do I get the max and min values from a set of numbers entered?

//for excluding zero
public class SmallestInt {

    public static void main(String[] args) {

        Scanner input= new Scanner(System.in);

        System.out.println("enter number");
        int val=input.nextInt();
        int min=val;

        //String notNull;

        while(input.hasNextInt()==true)
        {
            val=input.nextInt();
            if(val<min)
                min=val;
        }
        System.out.println("min is: "+min);
    }
}

How do I mount a host directory as a volume in docker compose

In docker-compose.yml you can use this format:

volumes:
    - host directory:container directory

according to their documentation

RegEx: How can I match all numbers greater than 49?

I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:

/([5-9][0-9])|([1-9]\d{3}\d*)/

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

Forward X11 failed: Network error: Connection refused

X display location : localhost:0 Worked for me :)

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

This is what solve my problem.

If you are trying to use debugger make sure you breakpoint is not on URL or URLConnection just put your breakpoint on BufferReader or inside while loop.

If nothing works try using apache library http://hc.apache.org/index.html.

no SSL, no JDK update needed, no need to set properties even, just simple trick :)

Check if a String is in an ArrayList of Strings

The List interface already has this solved.

int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;

More can be found in the documentation about List.

Get java.nio.file.Path object from java.io.File

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

How to reverse an animation on mouse out after hover

creating a reversed animation is kinda an overkill to a simple problem, what u need is

animation-direction: reverse

however this wont work on its own because animation spec is so dump that they forgot to add a way to restart the animation so here is how you do it with the help of js

_x000D_
_x000D_
let item = document.querySelector('.item')_x000D_
_x000D_
// play normal_x000D_
item.addEventListener('mouseover', () => {_x000D_
  item.classList.add('active')_x000D_
})_x000D_
_x000D_
// play in reverse_x000D_
item.addEventListener('mouseout', () => {_x000D_
  item.style.opacity = 0 // avoid showing the init style while switching the 'active' class_x000D_
_x000D_
  item.classList.add('in-active')_x000D_
  item.classList.remove('active')_x000D_
_x000D_
  // force dom update_x000D_
  setTimeout(() => {_x000D_
    item.classList.add('active')_x000D_
    item.style.opacity = ''_x000D_
  }, 5)_x000D_
_x000D_
  item.addEventListener('animationend', onanimationend)_x000D_
})_x000D_
_x000D_
function onanimationend() {_x000D_
  item.classList.remove('active', 'in-active')_x000D_
  item.removeEventListener('animationend', onanimationend)_x000D_
}
_x000D_
@keyframes spin {_x000D_
  0% {_x000D_
    transform: rotateY(0deg);_x000D_
  }_x000D_
  100% {_x000D_
    transform: rotateY(180deg);_x000D_
  }_x000D_
}_x000D_
_x000D_
div {_x000D_
  background: black;_x000D_
  padding: 1rem;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  /* because span cant be animated */_x000D_
  display: block;_x000D_
  color: yellow;_x000D_
  font-size: 2rem;_x000D_
}_x000D_
_x000D_
.item.active {_x000D_
  animation: spin 1s forwards;_x000D_
  animation-timing-function: ease-in-out;_x000D_
}_x000D_
_x000D_
.item.in-active {_x000D_
  animation-direction: reverse;_x000D_
}
_x000D_
<div>_x000D_
  <span class="item">ABC</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to move all files including hidden files into parent directory via *

By using the find command in conjunction with the mv command, you can prevent the mv command from trying to move directories (e.g. .. and .) and subdirectories. Here's one option:

find /path/subfolder -maxdepth 1 -type f -name '*' -exec mv -n {} /path \;

There are problems with some of the other answers provided. For example, each of the following will try to move subdirectories from the source path:

1) mv /path/subfolder/* /path/ ; mv /path/subfolder/.* /path/
2) mv /path/subfolder/{.,}* /path/ 
3) mv /source/path/{.[!.],}* /destination/path

Also, 2) includes the . and .. files and 3) misses files like ..foobar, ...barfoo, etc.

You could use, mv /source/path/{.[!.],..?,}* /destination/path, which would include the files missed by 3), but it would still try to move subdirectories. Using the find command with the mv command as I describe above eliminates all these problems.

How to get htaccess to work on MAMP

If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.

How to achieve ripple animation using support library?

I formerly voted to close this question as off-topic but actually I changed my mind as this is quite nice visual effect which, unfortunately, is not yet part of support library. It will most likely show up in future update, but there's no time frame announced.

Luckily there are few custom implementations already available:

including Materlial themed widget sets compatible with older versions of Android:

so you can try one of these or google for other "material widgets" or so...

git - pulling from specific branch

Here are the steps to pull a specific or any branch,

1.clone the master(you need to provide username and password)

       git clone <url>

2. the above command will clone the repository and you will be master branch now

       git checkout <branch which is present in the remote repository(origin)>

3. The above command will checkout to the branch you want to pull and will be set to automatically track that branch

4.If for some reason it does not work like that, after checking out to that branch in your local system, just run the below command

       git pull origin <branch>

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

My problem was solved checking if the process was running on Ubuntu 12.04

ps ax | grep mysql

Then the answer was that it wasn't running, so I did

sudo service mysql start

Or try

sudo /etc/init.d/mysql start

CSS change button style after click

Each link has five different states: link, hover, active, focus and visited.

Link is the normal appearance, hover is when you mouse over, active is the state when it's clicked, focus follows active and visited is the state you end up when you unfocus the recently clicked link.

I'm guessing you want to achieve a different style on either focus or visited, then you can add the following CSS:

a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }

A recommended order in your CSS to not cause any trouble is the following:

a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }

You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools

Checking if jquery is loaded using Javascript

CAUTION: Do not use jQuery to test your jQuery

When you are using any of the code provided by other users and if you want to display the message on your window and not on the alert or console.log, Then make sure you use javascript and not jquery.

Not everyone want to use alert or console.log

alert('jquery is working');
console.log('jquery is working');

The code below will fail to display the message
Because we are using jquery inside the else (how the hell the message displays on your screen if you do not have jquery)

if ('undefined' == typeof window.jQuery) {
    $('#selector').appendTo('jquery is NOT working');
} else {
    $('#selector').appendTo('jquery is working');
}

Use JavaScript instead

if ('undefined' == typeof window.jQuery) {
    document.getElementById('selector').innerHTML = "jquery is NOT working";
} else {
    document.getElementById('selector').innerHTML = "jquery is working";
}

How to shift a block of code left/right by one space in VSCode?

There was a feature request for that in vscode repo. But it was marked as extension-candidate and closed. So, here is the extension: Indent One space

Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.

enter image description here

Count the number of occurrences of each letter in string

You can use the following code.

main()
{
    int i = 0,j=0,count[26]={0};
    char ch = 97;
    char string[100]="Hello how are you buddy ?";
    for (i = 0; i < 100; i++)
    {
        for(j=0;j<26;j++)
            {
            if (tolower(string[i]) == (ch+j))
                {
                    count[j]++;
                }
        }
    }
    for(j=0;j<26;j++)
        {

            printf("\n%c -> %d",97+j,count[j]);

    }

}

Hope this helps.

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

android - listview get item view by position

workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
        viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
    }
});

How to filter a dictionary according to an arbitrary condition function?

>>> points = {'a': (3, 4), 'c': (5, 5), 'b': (1, 2), 'd': (3, 3)}
>>> dict(filter(lambda x: (x[1][0], x[1][1]) < (5, 5), points.items()))

{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}

Android Studio don't generate R.java for my import project

Did you follow steps here? First update your Eclipse ADT plugin, then export project and the import in Android Studio.

http://developer.android.com/sdk/installing/migrate.html

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

How to sum a variable by group

library(tidyverse)

x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'), 
           Frequency = c(10, 15, 5, 2, 14, 20, 3))

count(x, Category, wt = Frequency)

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

Getting session value in javascript

I tried following with ASP.NET MVC 5, its works for me

var sessionData = "@Session["SessionName"]";

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

Why is the <center> tag deprecated in HTML?

You can still use this with XHTML 1.0 Transitional and HTML 4.01 Transitional if you like. The only other way (best way, in my opinion) is with margins:

<div style="width:200px;margin:auto;">
  <p>Hello World</p>
</div>

Your HTML should define the element, not govern its presentation.

How do I convert a TimeSpan to a formatted string?

The easiest way to format a TimeSpan is to add it to a DateTime and format that:

string formatted = (DateTime.Today + dateDifference).ToString("HH 'hrs' mm 'mins' ss 'secs'");

This works as long as the time difference is not more than 24 hours.

The Today property returns a DateTime value where the time component is zero, so the time component of the result is the TimeSpan value.

connecting to phpMyAdmin database with PHP/MySQL

Set up a user, a host the user is allowed to talk to MySQL by using (e.g. localhost), grant that user adequate permissions to do what they need with the database .. and presto.

The user will need basic CRUD privileges to start, that's sufficient to store data received from a form. The rest of the permissions are self explanatory, i.e. permission to alter tables, etc. Give the user no more, no less power than it needs to do its work.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Just finally fixed this for my single solution that was having this. Two of the projects in the solution were set as sites in IIS. I went in and enabled ASP.Net Impersonation under Authentication for both projects...and VIOLA! FINALLY, no more of this annoying error!

How can I delete using INNER JOIN with SQL Server?

You could even do a sub-query. Like this code below:

DELETE FROM users WHERE id IN(
    SELECT user_id FROM Employee WHERE Company = '1' AND Date = '2013-05-06'
)

Concatenate multiple files but include filename as section headers

This method will print filename and then file contents:

tail -f file1.txt file2.txt

Output:

==> file1.txt <==
contents of file1.txt ...
contents of file1.txt ...

==> file2.txt <==
contents of file2.txt ...
contents of file2.txt ...

TCPDF ERROR: Some data has already been output, can't send PDF file

I had this but unlike the OP I couldn't see any output before the TCPDF error message.

Turns out there was a UTF8 BOM (byte-order-mark) at the very start of my script, before the <?php tag so before I had any chance to call ob_start(). And there was also a UTF8 BOM before the TCPDF error message.

How to return 2 values from a Java method?

In my opinion the best is to create a new class which constructor is the function you need, e.g.:

public class pairReturn{
        //name your parameters:
        public int sth1;
        public double sth2;
        public pairReturn(int param){
            //place the code of your function, e.g.:
            sth1=param*5;
            sth2=param*10;
        }
    }

Then simply use the constructor as you would use the function:

pairReturn pR = new pairReturn(15);

and you can use pR.sth1, pR.sth2 as "2 results of the function"

Apple Mach-O Linker Error when compiling for device

open .xcworkspace file not .xcodeproj. I repeat open .xcworkspace file. All of your errors will go away.

Casting variables in Java

Suppose you wanted to cast a String to a File (yes it does not make any sense), you cannot cast it directly because the File class is not a child and not a parent of the String class (and the compiler complains).

But you could cast your String to Object, because a String is an Object (Object is parent). Then you could cast this object to a File, because a File is an Object.

So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !

File f = (File)(Object) "Stupid cast";

The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:

Exception in thread "main" java.lang.ClassCastException:
    java.lang.String cannot be cast to java.io.File

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

It can be resolved as follows:

  1. Go to Project properties.

  2. Then 'Java Compiler' -> Check the box ('Enable project specific settings')

  3. Change the compiler compliance level to '5.0' & click ok.

Do rebuild. It will be resolved.

Also, click the checkbox for "Use default compliance settings".

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

Convert HTML Character Back to Text Using Java Standard Library

I'm not aware of any way to do it using the standard library. But I do know and use this class that deals with html entities.

"HTMLEntities is an Open Source Java class that contains a collection of static methods (htmlentities, unhtmlentities, ...) to convert special and extended characters into HTML entitities and vice versa."

http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities

How can I remove the top and right axis in matplotlib?

Library Seaborn has this built in with function .despine().

Just add:

import seaborn as sns

Now create your graph. And add at the end:

sns.despine()

If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:

sns.despine(top=True, right=True, left=False, bottom=False)

Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html

ReferenceError: $ is not defined

i was facing the same problem in the wp-admin section of the site. I enqueued the underscore script cdn and it fixed the problem.

function kk_admin_scripts() {
    wp_enqueue_script('underscore', '//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js' );
}
add_action( 'admin_enqueue_scripts', 'kk_admin_scripts' );

How to get featured image of a product in woocommerce

I had the same problem and solved it by using the default woocommerce hook to display the product image.

while ( $loop->have_posts() ) : $loop->the_post();
   echo woocommerce_get_product_thumbnail('woocommerce_full_size');
endwhile;

Available parameters:

  • woocommerce_thumbnail
  • woocommerce_full_size

JSON Post with Customized HTTPHeader Field

Just wanted to update this thread for future developers.

JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/

Determine if Python is running inside virtualenv

A potential solution is:

os.access(sys.executable, os.W_OK)

In my case I really just wanted to detect if I could install items with pip as is. While it might not be the right solution for all cases, consider simply checking if you have write permissions for the location of the Python executable.

Note: this works in all versions of Python, but also returns True if you run the system Python with sudo. Here's a potential use case:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

How to get the focused element with jQuery?

// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

Which one should you use? quoting the jQuery docs:

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

The answer is:

document.activeElement

And if you want a jQuery object wrapping the element:

$(document.activeElement)

How to install npm peer dependencies automatically?

Cheat code helpful in this scenario and some others...

+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected]
+-- UNMET PEER DEPENDENCY @angular/[email protected] >
  1. copy & paste your error into your code editor.
  2. Highlight an unwanted part with your curser. In this case +-- UNMET PEER DEPENDENCY
  3. Press command + d a bunch of times.
  4. Press delete twice. (Press space if you accidentally highlighted +-- UNMET PEER DEPENDENCY )
  5. Press up once. Add npm install
  6. Press down once. Add --save
  7. Copy your stuff back into the cli and run
npm install @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] --save

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to check if a variable is set in Bash?

After skimming all the answers, this also works:

if [[ -z $SOME_VAR ]]; then read -p "Enter a value for SOME_VAR: " SOME_VAR; fi
echo "SOME_VAR=$SOME_VAR"

if you don't put SOME_VAR instead of what I have $SOME_VAR, it will set it to an empty value; $ is necessary for this to work.

Removing "bullets" from unordered list <ul>

ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
  content: "\2022";
  font-family: FontAwesome;
  margin-right: 10px;
  display: inline;
  vertical-align: middle;
  font-size: 1.6em;
  font-weight: normal;
}

Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.

Visual for you - http://i.imgur.com/d533SQD.png

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

What's the yield keyword in JavaScript?

It's used for iterator-generators. Basically, it allows you to make a (potentially infinite) sequence using procedural code. See Mozilla's documentation.

Switch between two frames in tkinter

Here is another simple answer, but without using classes.

from tkinter import *


def raise_frame(frame):
    frame.tkraise()

root = Tk()

f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)

for frame in (f1, f2, f3, f4):
    frame.grid(row=0, column=0, sticky='news')

Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()

Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()

Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')

Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()

raise_frame(f1)
root.mainloop()

How to find keys of a hash?

using jQuery you can get the keys like this:

var bobject =  {primary:"red",bg:"maroon",hilite:"green"};
var keys = [];
$.each(bobject, function(key,val){ keys.push(key); });
console.log(keys); // ["primary", "bg", "hilite"]

Or:

var bobject =  {primary:"red",bg:"maroon",hilite:"green"};
$.map(bobject, function(v,k){return k;});

thanks to @pimlottc

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

how to convert a string to an array in php

There is a function in PHP specifically designed for that purpose, str_word_count(). By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist parameter. Charlist parameter also accepts a range of characters as in the example.

One benefit of this function over explode() is that the punctuation marks, spaces and new lines are avoided.

$str = "1st example:
        Alte Füchse gehen schwer in die Falle.    ";

print_r( str_word_count( $str, 1, '1..9ü' ) );

/* output:
Array
(
    [0] => 1st
    [1] => example
    [2] => Alte
    [3] => Füchse
    [4] => gehen
    [5] => schwer
    [6] => in
    [7] => die
    [8] => Falle
)
*/

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

Dynamically add properties to a existing object

If you can't use the dynamic type with ExpandoObject, then you could use a 'Property Bag' mechanism, where, using a dictionary (or some other key / value collection type) you store string key's that name the properties and values of the required type.

See here for an example implementation.

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

How do I "decompile" Java class files?

Procyon includes a decompiler. It is FOSS.

Java 8: Difference between two LocalDateTime in multiple units

Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.

Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:

LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);

LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );

long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS );
tempDateTime = tempDateTime.plusYears( years );

long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS );
tempDateTime = tempDateTime.plusMonths( months );

long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS );
tempDateTime = tempDateTime.plusDays( days );


long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS );
tempDateTime = tempDateTime.plusHours( hours );

long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES );
tempDateTime = tempDateTime.plusMinutes( minutes );

long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS );

System.out.println( years + " years " + 
        months + " months " + 
        days + " days " +
        hours + " hours " +
        minutes + " minutes " +
        seconds + " seconds.");

//prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.

The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.

Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

What does the [Flags] Enum Attribute mean in C#?

To add Mode.Write:

Mode = Mode | Mode.Write;

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

How to retrieve a file from a server via SFTP?

hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)

Example code from SFTPUpload.java

package net.schmizz.sshj.examples;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.File;
import java.io.IOException;

/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final String src = System.getProperty("user.home") + File.separator + "test_file";
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.put(new FileSystemFile(src), "/tmp");
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

}

How to clear input buffer in C?

Another solution not mentioned yet is to use: rewind(stdin);

Python loop that also accesses previous and next values

Very C/C++ style solution:

    foo = 5
    objectsList = [3, 6, 5, 9, 10]
    prev = nex = 0
    
    currentIndex = 0
    indexHigher = len(objectsList)-1 #control the higher limit of list
    
    found = False
    prevFound = False
    nexFound = False
    
    #main logic:
    for currentValue in objectsList: #getting each value of list
        if currentValue == foo:
            found = True
            if currentIndex > 0: #check if target value is in the first position   
                prevFound = True
                prev = objectsList[currentIndex-1]
            if currentIndex < indexHigher: #check if target value is in the last position
                nexFound = True
                nex = objectsList[currentIndex+1]
            break #I am considering that target value only exist 1 time in the list
        currentIndex+=1
    
    if found:
        print("Value %s found" % foo)
        if prevFound:
            print("Previous Value: ", prev)
        else:
            print("Previous Value: Target value is in the first position of list.")
        if nexFound:
            print("Next Value: ", nex)
        else:
            print("Next Value: Target value is in the last position of list.")
    else:
        print("Target value does not exist in the list.")

javascript, is there an isObject function like isArray?

In jQuery there is $.isPlainObject() method for that:

Description: Check to see if an object is a plain object (created using "{}" or "new Object").

Changing font size and direction of axes text in ggplot2

Use theme():

d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))

How to display image from database using php

For example if you use this code , you can load image from db (mysql) and display it in php5 ;)

<?php
   $con =mysql_connect("localhost", "root" , "");
   $sdb= mysql_select_db("my_database",$con);
   $sql = "SELECT * FROM `news` WHERE 1";
   $mq = mysql_query($sql) or die ("not working query");
   $row = mysql_fetch_array($mq) or die("line 44 not working");
   $s=$row['photo'];
   echo $row['photo'];

   echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
   ?>

Is it possible to declare a public variable in vba and assign a default value?

This is what I do when I need Initialized Global Constants:
1. Add a module called Globals
2. Add Properties like this into the Globals module:

Property Get PSIStartRow() As Integer  
    PSIStartRow = Sheets("FOB Prices").Range("F1").Value  
End Property  
Property Get PSIStartCell() As String  
    PSIStartCell = "B" & PSIStartRow  
End Property

How to read a HttpOnly cookie using JavaScript

The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.

The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?

ASP.NET MVC Razor pass model to layout

A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.

The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.

My solution also starts of with a base view model:

public class LayoutModel
{
    public LayoutModel(string title)
    {
        Title = title;
    }

    public string Title { get;}
}

What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:

public class LayoutModel<T> : LayoutModel
{
    public LayoutModel(T pageModel, string title) : base(title)
    {
        PageModel = pageModel;
    }

    public T PageModel { get; }
}

With this solution I have disconnected the need of having inheritance between the layout model and the model.

So now I can go ahead and use the LayoutModel in Layout.cshtml like this:

@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>

And on a page you can use the generic LayoutModel like this:

@model LayoutModel<Customer>
@{
    var customer = Model.PageModel;
}

<p>Customer name: @customer.Name</p>

From your controller you simply return a model of type LayoutModel:

public ActionResult Page()
{
    return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}

iTunes Connect: How to choose a good SKU?

I put the year and the number series of my app example 2014-01

Duplicate keys in .NET dictionaries?

Very important note regarding use of Lookup:

You can create an instance of a Lookup(TKey, TElement) by calling ToLookup on an object that implements IEnumerable(T)

There is no public constructor to create a new instance of a Lookup(TKey, TElement). Additionally, Lookup(TKey, TElement) objects are immutable, that is, you cannot add or remove elements or keys from a Lookup(TKey, TElement) object after it has been created.

(from MSDN)

I'd think this would be a show stopper for most uses.

how to get last insert id after insert query in codeigniter active record

From the documentation:

$this->db->insert_id()

The insert ID number when performing database inserts.

Therefore, you could use something like this:

$lastid = $this->db->insert_id();

favicon not working in IE

Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:

Is the code like this:

<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />

Is it in the <head>?

Is the image a real ico file? (renaming a bitmap is not a real .ico! Mildly different format)

Does it work when you add the page as a bookmark?

Inserting line breaks into PDF

Another option is to use TCPDF::Ln(). It adds a line to the PDF with the option to set the height.

If the newlines are within your content already then MultiCell() is probably the way to go, as others have mentioned, but I find I like using:

$pdf->Cell(0, 0, 'Line 1', 0, 0, 'C');
$pdf->Ln();
$pdf->Cell(0, 0, 'Line 2', 0, 0, 'C');

It confuses me that Cell() and MultiCell() take in different arguments so I tend to stick to using Cell() only. Also it reads like a newline character for the PDF the same as \n reads like a newline character in text or <br> in HTML.

Html: Difference between cell spacing and cell padding

cellspacing and cell padding


Cell padding

is used for formatting purpose which is used to specify the space needed between the edges of the cells and also in the cell contents. The general format of specifying cell padding is as follows:

< table width="100" border="2" cellpadding="5">

The above adds 5 pixels of padding inside each cell .

Cell Spacing:

Cell spacing is one also used f formatting but there is a major difference between cell padding and cell spacing. It is as follows: Cell padding is used to set extra space which is used to separate cell walls from their contents. But in contrast cell spacing is used to set space between cells.

Getting attributes of Enum's value

    public enum DataFilters
    {
        [Display(Name= "Equals")]
        Equals = 1,// Display Name and Enum Name are same 
        [Display(Name= "Does Not Equal")]
        DoesNotEqual = 2, // Display Name and Enum Name are different             
    }

Now it will produce error in this case 1 "Equals"

public static string GetDisplayName(this Enum enumValue)
    {
        var enumMember = enumValue.GetType().GetMember(enumValue.ToString()).First();
        return enumMember.GetCustomAttribute<DisplayAttribute>() != null ? enumMember.GetCustomAttribute<DisplayAttribute>().Name : enumMember.Name;
    }

so if it is same return enum name rather than display name because enumMember.GetCustomAttribute() gets null if displayname and enum name are same.....

CRON job to run on the last day of the month

55 23 28-31 * * echo "[ $(date -d +1day +%d) -eq 1 ] && my.sh" | /bin/bash 

How do I find what Java version Tomcat6 is using?

After installing tomcat, you can choose "configure tomcat" by search in "search programs and files". After clicking on "configure Tomcat", you should give admin permissions and the window opens. Then click on "java" tab. There you can see the JVM and JAVA classpath.

How to download a file from a website in C#

Sure, you just use a HttpWebRequest.

Once you have the HttpWebRequest set up, you can save the response stream to a file StreamWriter(Either BinaryWriter, or a TextWriter depending on the mimetype.) and you have a file on your hard drive.

EDIT: Forgot about WebClient. That works good unless as long as you only need to use GET to retrieve your file. If the site requires you to POST information to it, you'll have to use a HttpWebRequest, so I'm leaving my answer up.

Access parent URL from iframe

The problem with the PHP $_SERVER['HTTP_REFFERER'] is that it gives the fully qualified page url of the page that brought you to the parent page. That's not the same as the parent page, itself. Worse, sometimes there is no http_referer, because the person typed in the url of the parent page. So, if I get to your parent page from yahoo.com, then yahoo.com becomes the http_referer, not your page.

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

What is the difference between 'typedef' and 'using' in C++11?

Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int); is clearer than with typedef int (*T)(int, int);. Second is that template alias form is not possible with typedef. Third is that exposing C API would require typedef in public headers.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

This looks like a problem with the svn:mergeinfo property getting out of wack between the branch and the trunk.

Which leads to the following questions (forgive my command line instructions as I done use tortoise much):

  1. Are you merging at the trunk root level or the sub folder level? In my experience it is always best to do at the root level, this way the whole trunk thinks it has been merged to rather than just part (this seems to confuse svn greatly in 1.5.0)

  2. My next question is were you using the --reintergrate parameter? I can never remember how to get to this in tortoise, but when you are going back to the trunk from a branch then you should use this parameter.

  3. Have you merged the trunk into the branch before you have reintegrated? This can help remove conflicts that you may see when you merge back?

  4. Have you got any svn:mergeinfo properties on the branch that are not at the root level? This I have found always causes problems. You can always find this out by going svn -R pg svn:mergeinfo. You can then record the locations and revisions that were below the root, if you find them relevant then move them to the root by svn merge --record-only -r start:end <location> and then delete them from the sub root locations with svn pd svn:mergeinfo <location> You then need to commit these changes

  5. Once you have all that is done try merging again.

Node.js setting up environment specific configs to be used with everyauth

This answer is not something new. It's similar to what @andy_t has mentioned. But I use the below pattern for two reasons.

  1. Clean implementation with No external npm dependencies

  2. Merge the default config settings with the environment based settings.

Javascript implementation

const settings = {
    _default: {
       timeout: 100
       baseUrl: "http://some.api/",
    },
    production: {
       baseUrl: "http://some.prod.api/",
    },
}
// If you are not using ECMAScript 2018 Standard
// https://stackoverflow.com/a/171256/1251350
module.exports = { ...settings._default, ...settings[process.env.NODE_ENV] }

I usually use typescript in my node project. Below is my actual implementation copy-pasted.

Typescript implementation

const settings: { default: ISettings, production: any } = {
    _default: {
        timeout: 100,
        baseUrl: "",
    },
    production: {
        baseUrl: "",
    },
}

export interface ISettings {
    baseUrl: string
}

export const config = ({ ...settings._default, ...settings[process.env.NODE_ENV] } as ISettings)

Given a filesystem path, is there a shorter way to extract the filename without its extension?

You can use Path API as follow:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

More info: Path.GetFileNameWithoutExtension

Convert RGBA PNG to RGB with PIL

Here's a solution in pure PIL.

def blend_value(under, over, a):
    return (over*a + under*(255-a)) / 255

def blend_rgba(under, over):
    return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])

white = (255, 255, 255, 255)

im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
    for x in range(im.size[0]):
        p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')

Is it fine to have foreign key as primary key?

Short answer: DEPENDS.... In this particular case, it might be fine. However, experts will recommend against it just about every time; including your case.

Why?

Keys are seldomly unique in tables when they are foreign (originated in another table) to the table in question. For example, an item ID might be unique in an ITEMS table, but not in an ORDERS table, since the same type of item will most likely exist in another order. Likewise, order IDs might be unique (might) in the ORDERS table, but not in some other table like ORDER_DETAILS where an order with multiple line items can exist and to query against a particular item in a particular order, you need the concatenation of two FK (order_id and item_id) as the PK for this table.

I am not DB expert, but if you can justify logically to have an auto-generated value as your PK, I would do that. If this is not practical, then a concatenation of two (or maybe more) FK could serve as your PK. BUT, I cannot think of any case where a single FK value can be justified as the PK.

Using Mockito with multiple calls to the same method with the same arguments

You can use a LinkedList and an Answer. Eg

MyService mock = mock(MyService.class);
LinkedList<String> results = new LinkedList<>(List.of("A", "B", "C"));
when(mock.doSomething(any())).thenAnswer(invocation -> results.removeFirst());

Javascript counting number of objects in object

Try Demo Here

var list ={}; var count= Object.keys(list).length;

Webpack.config how to just copy the index.html to the dist folder

To extend @hobbeshunter's answer if you want to take only index.html you can also use CopyPlugin, The main motivation to use this method over using other packages is because it's a nightmare to add many packages for every single type and config it etc. The easiest way is to use CopyPlugin for everything:

npm install copy-webpack-plugin --save-dev

Then

const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'static', to: 'static' },
      { from: 'index.html', to: 'index.html', toType: 'file'},
    ]),
  ],
};

As you can see it copy the whole static folder along with all of it's content into dist folder. No css or file or any other plugins needed.

While this method doesn't suit for everything, it would get the job done simply & quickly.

Recursively add the entire folder to a repository

In my case, there was a .git folder in the subdirectory because I had previously initialized a git repo there. When I added the subdirectory it simply added it as a subproject without adding any of the contained files.

I solved the issue by removing the git repository from the subdirectory and then re-adding the folder.

Print a list of space-separated elements in Python 3

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

how to get right offset of an element? - jQuery

There's a native DOM API that achieves this out of the box — getBoundingClientRect:

document.querySelector("#whatever").getBoundingClientRect().right

Add leading zeroes to number in Java?

How about just:

public static String intToString(int num, int digits) {
    String output = Integer.toString(num);
    while (output.length() < digits) output = "0" + output;
    return output;
}

is there a css hack for safari only NOT chrome?

At the end I use a little JavaScript to achieve it:

if (navigator.vendor.startsWith('Apple'))
    document.documentElement.classList.add('on-apple');

then in my CSS to target Apple browser engine the selector will be:

.on-apple .my-class{
    ...
}

How to access /storage/emulated/0/

Here, it is found at /mnt/shell/emulated/0

Twitter bootstrap collapse: change display of toggle button

Add some jquery code, you need jquery to do this :

<script>
        $(".btn[data-toggle='collapse']").click(function() {
            if ($(this).text() == '+') {
                $(this).text('-');
            } else {
                $(this).text('+');
            }
        });
        </script>

How to dynamically add a class to manual class names?

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

How can I determine the direction of a jQuery scroll event?

Since bind has been deprecated on v3 ("superseded by on") and wheel is now supported, forget wheelDelta:

_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
  if (e.originalEvent.deltaY > 0) {_x000D_
    console.log('down');_x000D_
  } else {_x000D_
    console.log('up');_x000D_
  }_x000D_
  if (e.originalEvent.deltaX > 0) {_x000D_
    console.log('right');_x000D_
  } else {_x000D_
    console.log('left');_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h1 style="white-space:nowrap;overflow:scroll">_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
</h1>
_x000D_
_x000D_
_x000D_

wheel event's Browser Compatibility on MDN's (2019-03-18):

Compatibility of the wheel event

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

word-break:break-all :

word to continue to border then break in newline.

word-wrap:break-word :

At first , word wrap in newline then continue to border.

Example :

_x000D_
_x000D_
div {_x000D_
   border: 1px solid red;_x000D_
   width: 200px;_x000D_
}_x000D_
_x000D_
span {_x000D_
  background-color: yellow;_x000D_
}_x000D_
_x000D_
.break-all {_x000D_
  word-break:break-all;_x000D_
 }_x000D_
.break-word {_x000D_
  word-wrap:break-word;  _x000D_
}
_x000D_
<b>word-break:break-all</b>_x000D_
_x000D_
<div class="break-all">_x000D_
  This text is styled with_x000D_
  <span>soooooooooooooooooooooooooome</span> of the text_x000D_
  formatting properties._x000D_
</div>_x000D_
_x000D_
<b> word-wrap:break-word</b>_x000D_
_x000D_
<div class="break-word">_x000D_
  This text is styled with_x000D_
  <span>soooooooooooooooooooooooooome</span> of the text_x000D_
  formatting properties._x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

How does a Linux/Unix Bash script know its own PID?

If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

sleep 1 &
mypid=$(ps -o ppid= -p "$!")

How to call javascript function from code-behind

This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg", 
    "$(document).ready(function(){EnableControls();
    alert('Overrides successfully Updated.');
    DisableControls();});", 
true);

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

How to disable the parent form when a child form is active?

Are you calling ShowDialog() or just Show() on your child form from the parent form?

ShowDialog will "block" the user from interacting with the form which is passed as a parameter to ShowDialog.

Within the parent you might call something like:

MyChildForm childForm = new MyChildForm();

childForm.ShowDialog(this);

where this is the parent form.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

LTrim function and RTrim function :

  • The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
  • It uses the Trim function to remove both types of spaces.

                  select LTRIM(RTRIM(' SQL Server '))
    

    output:

                             SQL Server
    

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO