Programs & Examples On #Teradata

Teradata is a Relational Database Management System (RDBMS), capable of supporting many concurrent users from various client platforms. Teradata is compatible with the ANSI standard and built completely on parallel architecture.

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Program to find largest and second largest number in array

Find your second largest number without using any String function:

int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
    printf("Array is too small");
    return;
}

firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
    //Largest number check
    if (array[index] > first)
    {
        secondLargest = firstLargest;
        firstLargest = array[index];
    }

    //It may not larger than first but can be larger than second number
    else if (array[index] > secondLargest && array[index] != firstLargest)
{
        secondLargest = array[index];
}

//Finally you got your answer
if (secondLargest == minNumber)
{
    printf("No Second largest number");
}
else
{
    printf("Second Largest Number is %d", secondLargest);
}

HTML embed autoplay="false", but still plays automatically

Just change the mime type to: type="audio/mpeg", this way chrome will honor the autostart="false" parameter.

Case insensitive string as HashMap key

Instead of creating your own class to validate and store case insensitive string as a HashMap key, you can use:

  1. LinkedCaseInsensitiveMap wraps a LinkedHashMap, which is a Map based on a hash table and a linked list. Unlike LinkedHashMap, it doesn't allow null key inserting. LinkedCaseInsensitiveMap preserves the original order as well as the original casing of keys while allowing calling functions like get and remove with any case.

Eg:

Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("AbC", 2);

System.out.println(linkedHashMap);

Output: {AbC=2}

Mvn Dependency:

Spring Core is a Spring Framework module that also provides utility classes, including LinkedCaseInsensitiveMap.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>
  1. CaseInsensitiveMap is a hash-based Map, which converts keys to lower case before they are being added or retrieved. Unlike TreeMap, CaseInsensitiveMap allows null key inserting.

Eg:

Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("ABC", 1);
commonsHashMap.put("abc", 2);
commonsHashMap.put("aBc", 3);

System.out.println(commonsHashMap);

Output: {abc=3}

Dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>
  1. TreeMap is an implementation of NavigableMap, which means that it always sorts the entries after inserting, based on a given Comparator. Also, TreeMap uses a Comparator to find if an inserted key is a duplicate or a new one.

Therefore, if we provide a case-insensitive String Comparator, we'll get a case-insensitive TreeMap.

Eg:

Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("ABC", 1);
treeMap.put("ABc", 2);
treeMap.put("cde", 1);
        
System.out.println(treeMap);

Output: {ABC=2, cde=1}

how to get the value of a textarea in jquery?

you should use val() instead of html()

var message = $('#message').val();

Test or check if sheet exists

You don't need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:

For i = 1 To Worksheets.Count
    If Worksheets(i).Name = "MySheet" Then
        exists = True
    End If
Next i

If Not exists Then
    Worksheets.Add.Name = "MySheet"
End If

SQL Server: Filter output of sp_who2

You could try something like

DECLARE @Table TABLE(
        SPID INT,
        Status VARCHAR(MAX),
        LOGIN VARCHAR(MAX),
        HostName VARCHAR(MAX),
        BlkBy VARCHAR(MAX),
        DBName VARCHAR(MAX),
        Command VARCHAR(MAX),
        CPUTime INT,
        DiskIO INT,
        LastBatch VARCHAR(MAX),
        ProgramName VARCHAR(MAX),
        SPID_1 INT,
        REQUESTID INT
)

INSERT INTO @Table EXEC sp_who2

SELECT  *
FROM    @Table
WHERE ....

And filter on what you require.

How do I syntax check a Bash script without running it?

bash -n scriptname

Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello.

Disable keyboard on EditText

Here is a website that will give you what you need

As a summary, it provides links to InputMethodManager and View from Android Developers. It will reference to the getWindowToken inside of View and hideSoftInputFromWindow() for InputMethodManager

A better answer is given in the link, hope this helps.

here is an example to consume the onTouch event:

editText_input_field.setOnTouchListener(otl);

private OnTouchListener otl = new OnTouchListener() {
  public boolean onTouch (View v, MotionEvent event) {
        return true; // the listener has consumed the event
  }
};

Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:

MyEditor.setOnTouchListener(new OnTouchListener(){

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    int inType = MyEditor.getInputType(); // backup the input type
    MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
    MyEditor.onTouchEvent(event); // call native handler
    MyEditor.setInputType(inType); // restore input type
    return true; // consume touch even
  }
});

Hope this points you in the right direction

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

How to remove all non-alpha numeric characters from a string in MySQL?

The fastest way I was able to find (and using ) is with convert().

from Doc. CONVERT() with USING is used to convert data between different character sets.

Example:

convert(string USING ascii)

In your case the right character set will be self defined

NOTE from Doc. The USING form of CONVERT() is available as of 4.1.0.

Standard concise way to copy a file in Java?

In Java 7 it is easy...

File src = new File("original.txt");
File target = new File("copy.txt");

Files.copy(src.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);

ImageView rounded corners

Based on Nihal's answer ( https://stackoverflow.com/a/42234152/2832027 ), here is a pure XML version that gives a rectangle with rounded corners on API 24 and above. On below API 24, it will show no rounded corners.

Usage:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="150dp"
    android:layout_height="200dp"
    android:foreground="@drawable/rounded_corner_mask"/>

rounded_corner_mask.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:gravity="bottom|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,10 A10,10 0 0,0 10,0 L10,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="bottom|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,0 A10,10 0 0,0 10,10 L0,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,0 A10,10 0 0,0 0,10 L0,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,10 A10,10 0 0,0 0,0 L10,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

</layer-list>

Is there an equivalent method to C's scanf in Java?

If one really wanted to they could make there own version of scanf() like so:

    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}


}

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input: apples 8 9 pears oranges 5 Ints gathered: 8 9 5 Strings gathered: apples pears oranges Data: 8 apples 9 pears 5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

If you can discount transient outages on the remote server you are trying to connect to, then that just leaves the local network config as a problem.

Using the IP address instead of the hostname is only going to work for the default domain on the remote host.

What happens when you try using www.google.com (or its IP address)? If you stil can't connect, then its something to do with the network between your server and the outside world.

How to prevent going back to the previous activity?

Put

finish();

immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add

onCreate(){
    getActionBar().setDisplayHomeAsUpEnabled(false);
    ...
}

to the activity you are starting.

Do I really need to encode '&' as '&amp;'?

If the user passes it to you, or it will wind up in a URL, you need to escape it.

If it appears in static text on a page? All browsers will get this one right either way, you don't worry much about it, since it will work.

Can I set up HTML/Email Templates with ASP.NET?

If you want to pass parameters like user names, product names, ... etc. you can use open source template engine NVelocity to produce your final email / HTML's.

An example of NVelocity template (MailTemplate.vm) :

A sample email template by <b>$name</b>.
<br />

Foreach example :
<br />    
#foreach ($item in $itemList)

[Date: $item.Date] Name: $item.Name, Value: $itemValue.Value
<br /><br />

#end

Generating mail body by MailTemplate.vm in your application :

VelocityContext context = new VelocityContext();
context.Put("name", "ScarletGarden");
context.Put("itemList", itemList);

StringWriter writer = new StringWriter();

Velocity.MergeTemplate("MailTemplate.vm", context, writer);

string mailBody = writer.GetStringBuilder().ToString();

The result mail body is :

A sample email template by ScarletGarden.

Foreach example :

[Date: 12.02.2009] Name: Item 1, Value: 09

[Date: 21.02.2009] Name: Item 4, Value: 52

[Date: 01.03.2009] Name: Item 2, Value: 21

[Date: 23.03.2009] Name: Item 6, Value: 24

For editing the templates, maybe you can use FCKEditor and save your templates to files.

Zoom in on a point (using scale and translate)

Here's an alternate way to do it that uses setTransform() instead of scale() and translate(). Everything is stored in the same object. The canvas is assumed to be at 0,0 on the page, otherwise you'll need to subtract its position from the page coords.

this.zoomIn = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale * zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) * zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) * zoomFactor
    };
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    this.lastTranslation.x,
                                    this.lastTranslation.y);
};
this.zoomOut = function (pageX, pageY) {
    var zoomFactor = 1.1;
    this.scale = this.scale / zoomFactor;
    this.lastTranslation = {
        x: pageX - (pageX - this.lastTranslation.x) / zoomFactor,
        y: pageY - (pageY - this.lastTranslation.y) / zoomFactor
    };
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    this.lastTranslation.x,
                                    this.lastTranslation.y);
};

Accompanying code to handle panning:

this.startPan = function (pageX, pageY) {
    this.startTranslation = {
        x: pageX - this.lastTranslation.x,
        y: pageY - this.lastTranslation.y
    };
};
this.continuePan = function (pageX, pageY) {
    var newTranslation = {x: pageX - this.startTranslation.x,
                          y: pageY - this.startTranslation.y};
    this.canvasContext.setTransform(this.scale, 0, 0, this.scale,
                                    newTranslation.x, newTranslation.y);
};
this.endPan = function (pageX, pageY) {
    this.lastTranslation = {
        x: pageX - this.startTranslation.x,
        y: pageY - this.startTranslation.y
    };
};

To derive the answer yourself, consider that the same page coordinates need to match the same canvas coordinates before and after the zoom. Then you can do some algebra starting from this equation:

(pageCoords - translation) / scale = canvasCoords

405 method not allowed Web API

[HttpPost] is unnecessary!

[Route("")]
public void Post(ProductModel data)
{
    ...
}

Scala vs. Groovy vs. Clojure

They can be differentiated with where they are coming from or which developers they're targeting mainly.

Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.

Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.

Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

How to Delete node_modules - Deep Nested Folder in Windows

What worked for me was:

  1. closed the node manager console
  2. closed the Atom (visual studio code ) dev environment you are in.
  3. then delete the node_modules

    npm install rimraf -g 
    rimraf node_modules
    

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

What is the default text size on Android?

Looks like someone else found it: What are the default font characteristics in Android ?

There someone discovered the default text size, for TextViews (which use TextAppearance.Small) it's 14sp.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Check if argparse optional argument is set or not

Here is my solution to see if I am using an argparse variable

import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False) 
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something

This might give more insight to the above answer which I used and adapted to work for my program.

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I had the same issue when getting my software running on another machine. On my developer pc (Windows 7), I had Visual Studio 2015 installed, the target pc was a clean installation of Windows 10 (.Net installed). I also tested it on another clean Windows 7 pc including .Net Framework. However, on both target pc's I needed to install the Visual C++ Redistributable for Visual Studio 2015 package for x86 or x64 (depends on what your application is build for). That was already installed on my developer pc.

My application was using a C library, which has been compiled to a C++ application using /clr and /TP options in visual studio. Also the application was providing functions to C# by using dllexport method signatures. Not sure if the C# integration leaded to give me that error or if a C++ application would have given me the same.

Hope it helps anybody.

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

how to get the value of css style using jquery

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

How can I change the app display name build with Flutter?

You can change it in iOS without opening Xcode by editing file *project/ios/Runner/info.plist. Set <key>CFBundleDisplayName</key> to the string that you want as your name.

For Android, change the app name from the Android folder, in the AndroidManifest.xml file, android/app/src/main. Let the android label refer to the name you prefer, for example,

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    <application
        android:label="test"
        // The rest of the code
    </application>
</manifest>

Unresolved external symbol in object files

Just spent a couple of hours to find that the issue was my main file had extension .c instead of .cpp

:/

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


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

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I have just found this pretty solution:

import sys; sys.path.insert(0, '..') # add parent folder path where lib folder is
import lib.store_load # store_load is a file on my library folder

You just want some functions of that file

from lib.store_load import your_function_name

If python version >= 3.3 you do not need init.py file in the folder

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How to check if a "lateinit" variable has been initialized?

Using .isInitialized property one can check initialization state of a lateinit variable.

if (::file.isInitialized) {
    // File is initialized
} else {
    // File is not initialized
}

How to set an iframe src attribute from a variable in AngularJS

this way i follow and its work for me fine, may it will works for you,

<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
                height: iframeHeight * 0.75 + 'px'
            }" style="width:100%"></iframe>

here trustThisUrl is just filter,

angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
        return function (val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);

How to find a string inside a entire database?

Here are couple more free tools that can be used for this. Both work as SSMS addins.

ApexSQL Search – 100% free - searches both schema and data in tables. Has couple more useful options such as dependency tracking…

SSMS Tools pack – free for all versions except SQL 2012 – doesn’t look as advanced as previous one but has a lot of other cool features.

How do I horizontally center an absolute positioned element inside a 100% width div?

You will have to assign both left and right property 0 value for margin: auto to center the logo.

So in this case:

#logo {
  background:red;
  height:50px;
  position:absolute;
  width:50px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

You might also want to set position: relative for #header.

This works because, setting left and right to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin is set to auto. margin takes up all the extra space(equally on each side) leaving the content to its specified width. This results in content becoming center aligned.

grant remote access of MySQL database from any IP address

Enable Remote Access (Grant) Home / Tutorials / Mysql / Enable Remote Access (Grant) If you try to connect to your mysql server from remote machine, and run into error like below, this article is for you.

ERROR 1130 (HY000): Host ‘1.2.3.4’ is not allowed to connect to this MySQL server

Change mysql config

Start with editing mysql config file

vim /etc/mysql/my.cnf

Comment out following lines.

#bind-address           = 127.0.0.1
#skip-networking

If you do not find skip-networking line, add it and comment out it.

Restart mysql server.

~ /etc/init.d/mysql restart

Change GRANT privilege

You may be surprised to see even after above change you are not getting remote access or getting access but not able to all databases.

By default, mysql username and password you are using is allowed to access mysql-server locally. So need to update privilege.

Run a command like below to access from all machines. (Replace USERNAME and PASSWORD by your credentials.)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'%' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;

Run a command like below to give access from specific IP. (Replace USERNAME and PASSWORD by your credentials.)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'1.2.3.4' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;

You can replace 1.2.3.4 with your IP. You can run above command many times to GRANT access from multiple IPs.

You can also specify a separate USERNAME & PASSWORD for remote access.

You can check final outcome by:

SELECT * from information_schema.user_privileges where grantee like "'USERNAME'%";

Finally, you may also need to run:

mysql> FLUSH PRIVILEGES;

Test Connection

From terminal/command-line:

mysql -h HOST -u USERNAME -pPASSWORD

If you get a mysql shell, don’t forget to run show databases; to check if you have right privileges from remote machines.

Bonus-Tip: Revoke Access

If you accidentally grant access to a user, then better have revoking option handy.

Following will revoke all options for USERNAME from all machines:

mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'USERNAME'@'%';
Following will revoke all options for USERNAME from particular IP:

mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'USERNAME'@'1.2.3.4';
Its better to check information_schema.user_privileges table after running REVOKE command.

If you see USAGE privilege after running REVOKE command, its fine. It is as good as no privilege at all. I am not sure if it can be revoked.

best way to preserve numpy arrays on disk

savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:

f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()

f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()

To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.

Locking a file in Python

Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:

import os

def my_lock(f):
    if os.name == "posix":
        # Unix or OS X specific locking here
    elif os.name == "nt":
        # Windows specific locking here
    else:
        print "Unknown operating system, lock unavailable"

How to delete a localStorage item when the browser window/tab is closed?

This is an old question, but it seems none of the answer above are perfect.

In the case you want to store authentication or any sensitive information that are destructed only when the browser is closed, you can rely on sessionStorage and localStorage for cross-tab message passing.

Basically, the idea is:

  1. You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage.
  2. The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain).
  3. You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information.
  4. If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.

Please notice that this scheme does not depend on window.onbeforeunload event which is fragile (since the browser can be closed/crashed without these events being fired). Also, the time the sensitive information is stored on the localStorage is very small (since you rely on transcients change detection for cross tab message event) so it's unlikely that such sensitive information leaks on the user's hard drive.

Here's a demo of this concept: http://jsfiddle.net/oypdwxz7/2/

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to make a <div> or <a href="#"> to align center

You can do this:

<div style="text-align: center">
    <a href="contact.html" class="button large hpbottom">Get Started</a>
</div>

UIScrollView not scrolling

Set contentSize property of UIScrollview in ViewDidLayoutSubviews method. Something like this

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    scrollView.contentSize = CGSizeMake(view.frame.size.width, view.frame.size.height)
}

How do I remove the first characters of a specific column in a table?

Try this:

update table YourTable
set YourField = substring(YourField, 5, len(YourField)-3);

How to click or tap on a TextView text

Although you can resolve the problem by setting the listener to textview, it's recommended not to. You should use flat button as it is a subclass of Button and it provides many attributes which TextView doesn't.


To use flat button, add style="?android:attr/borderlessButtonStyle" attribute -

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="DONE"
    style="?android:attr/borderlessButtonStyle"/>

Constraint Layout Vertical Align Center

If you have a ConstraintLayout with some size, and a child View with some smaller size, you can achieve centering by constraining the child's two edges to the same two edges of the parent. That is, you can write:

app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"

or

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"

Because the view is smaller, these constraints are impossible. But ConstraintLayout will do the best it can, and each constraint will "pull" at the child view equally, thereby centering it.

This concept works with any target view, not just the parent.

Update

Below is XML that achieves your desired UI with no nesting of views and no Guidelines (though guidelines are not inherently evil).

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eee">

    <TextView
        android:id="@+id/title1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="10"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/divider1"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Streak"
        app:layout_constraintTop_toBottomOf="@+id/title1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/divider1"/>

    <View
        android:id="@+id/divider1"
        android:layout_width="1dp"
        android:layout_height="55dp"
        android:layout_marginTop="12dp"
        android:layout_marginBottom="12dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/title1"
        app:layout_constraintRight_toLeftOf="@+id/title2"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/title2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="243"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/divider1"
        app:layout_constraintRight_toLeftOf="@+id/divider2"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Calories Burned"
        app:layout_constraintTop_toBottomOf="@+id/title2"
        app:layout_constraintLeft_toRightOf="@+id/divider1"
        app:layout_constraintRight_toLeftOf="@+id/divider2"/>

    <View
        android:id="@+id/divider2"
        android:layout_width="1dp"
        android:layout_height="55dp"
        android:layout_marginTop="12dp"
        android:layout_marginBottom="12dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/title2"
        app:layout_constraintRight_toLeftOf="@+id/title3"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/title3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="3200"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/divider2"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Steps"
        app:layout_constraintTop_toBottomOf="@+id/title3"
        app:layout_constraintLeft_toRightOf="@+id/divider2"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

enter image description here

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

intelliJ IDEA 13 error: please select Android SDK

My Problem: "please select Android SDK", But everything is okey :( -> I think one of IntelliJ file was crashed (after blue screen of death)

My resolution:

File -> Settings -> Android SDK -> Android SDK Location Edit -> Next, Next (Android SDK is up to date.), Finished

... and crashed file was repaired!

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

AngularJS sorting by property

You should really improve your JSON structure to fix your problem:

$scope.testData = [
   {name:"CData", order: 1},
   {name:"BData", order: 2},
   {name:"AData", order: 3},
]

Then you could do

<li ng-repeat="test in testData | orderBy:order">...</li>

The problem, I think, is that the (key, value) variables are not available to the orderBy filter, and you should not be storing data in your keys anyways

How to use log4net in Asp.net core 2.0

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

Change Git repository directory location.

I'm not sure of the question, so here are two answers :

If you want to move your repository :

Simply copy the whole repository (with its .git directory).

There is no absolute path in the .git structure and nothing preventing it to be moved so you have nothing to do after the move. All the links to github (see in .git/config) will work as before.

If you want to move files inside the repository :

Simply move the files. Then add the changes listed in git status. The next commit will do the necessary. You'll be happy to learn that no file will be duplicated : moving a file in git is almost costless.

Private vs Protected - Visibility Good-Practice Concern

Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.

How do I remove the non-numeric character from a string in java?

you could use a recursive method like below:

public static String getAllNumbersFromString(String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        char c = input.charAt(input.length() - 1);
        String newinput = input.substring(0, input.length() - 1);

            if (c >= '0' && c<= '9') {
            return getAllNumbersFromString(newinput) + c;

        } else {
            return getAllNumbersFromString(newinput);
        }
    } 

Add values to app.config and retrieve them

This works:

public static void AddValue(string key, string value)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add(key, value);
    config.Save(ConfigurationSaveMode.Minimal);
}

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Use jquery click to handle anchor onClick()

The HTML should look like:

<div class="solTitle"> <a href="#"  id="solution0">Solution0 </a></div>
<div class="solTitle"> <a href="#"  id="solution1">Solution1 </a></div>

<div id="summary_solution0" style="display:none" class="summary">Summary solution0</div>
<div id="summary_solution1" style="display:none" class="summary">Summary solution1</div>

And the javascript:

$(document).ready(function(){
    $(".solTitle a").live('click',function(e){
        var contentId = "summary_" + $(this).attr('id');
        $(".summary").hide();
        $("#" + contentId).show();
    });
});

See the Example: http://jsfiddle.net/kmendes/4G9UF/

How do I make a Docker container start automatically on system boot?

You can run a container that restart always by:

$ docker run -dit --restart unless-stopped <image name OR image hash>

If you want to change a running container's configs, you should update it by:

$ docker update --restart=<options> <container ID OR name>

And if you want to see current policy of the container, run the following command before above at the first place:

docker inspect gateway | grep RestartPolicy -A 3

After all, Not to forget to make installed docker daemon enable at system boot by:

$ systemctl enable docker

To see a full list of restart policies, see: Restart Policies

How to create a responsive image that also scales up in Bootstrap 3

I guess image is than corrupted. Example: image size is 195px X 146px.

It will work inside lower resolutions like tablets. When you have 1280 X 800 resolution it will force larger as there is also width 100 %. Maybe CSS inside media query like icons fonts is the best solution.

Spring Boot - How to log all requests and responses with exceptions in single place?

Currently Spring Boot has the Actuator feature to get the logs of requests and responses.

But you can also get the logs using Aspect(AOP).

Aspect provides you with annotations like: @Before, @AfterReturning, @AfterThrowing etc.

@Before logs the request, @AfterReturning logs the response and @AfterThrowing logs the error message, You may not need all endpoints' log, so you can apply some filters on the packages.

Here are some examples:

For Request:

@Before("within(your.package.where.endpoints.are..*)")
    public void endpointBefore(JoinPoint p) {
        if (log.isTraceEnabled()) {
            log.trace(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " START");
            Object[] signatureArgs = p.getArgs();


            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            try {

                if (signatureArgs[0] != null) {
                    log.trace("\nRequest object: \n" + mapper.writeValueAsString(signatureArgs[0]));
                }
            } catch (JsonProcessingException e) {
            }
        }
    }

Here @Before("within(your.package.where.endpoints.are..*)") has the package path. All endpoints within this package will generate the log.

For Response:

@AfterReturning(value = ("within(your.package.where.endpoints.are..*)"),
            returning = "returnValue")
    public void endpointAfterReturning(JoinPoint p, Object returnValue) {
        if (log.isTraceEnabled()) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            try {
                log.trace("\nResponse object: \n" + mapper.writeValueAsString(returnValue));
            } catch (JsonProcessingException e) {
                System.out.println(e.getMessage());
            }
            log.trace(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " END");
        }
    }

Here @AfterReturning("within(your.package.where.endpoints.are..*)") has the package path. All endpoints within this package will generate the log. Also Object returnValue contains the response.

For Exception:

@AfterThrowing(pointcut = ("within(your.package.where.endpoints.are..*)"), throwing = "e")
public void endpointAfterThrowing(JoinPoint p, Exception e) throws DmoneyException {
    if (log.isTraceEnabled()) {
        System.out.println(e.getMessage());

        e.printStackTrace();


        log.error(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " " + e.getMessage());
    }
}

Here @AfterThrowing(pointcut = ("within(your.package.where.endpoints.are..*)"), throwing = "e") has the package path. All endpoints within this package will generate the log. Also Exception e contains the error response.

Here is the full code:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(1)
@Component
@ConditionalOnExpression("${endpoint.aspect.enabled:true}")
public class EndpointAspect {
    static Logger log = Logger.getLogger(EndpointAspect.class);

    @Before("within(your.package.where.is.endpoint..*)")
    public void endpointBefore(JoinPoint p) {
        if (log.isTraceEnabled()) {
            log.trace(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " START");
            Object[] signatureArgs = p.getArgs();


            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            try {

                if (signatureArgs[0] != null) {
                    log.trace("\nRequest object: \n" + mapper.writeValueAsString(signatureArgs[0]));
                }
            } catch (JsonProcessingException e) {
            }
        }
    }

    @AfterReturning(value = ("within(your.package.where.is.endpoint..*)"),
            returning = "returnValue")
    public void endpointAfterReturning(JoinPoint p, Object returnValue) {
        if (log.isTraceEnabled()) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            try {
                log.trace("\nResponse object: \n" + mapper.writeValueAsString(returnValue));
            } catch (JsonProcessingException e) {
                System.out.println(e.getMessage());
            }
            log.trace(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " END");
        }
    }


    @AfterThrowing(pointcut = ("within(your.package.where.is.endpoint..*)"), throwing = "e")
    public void endpointAfterThrowing(JoinPoint p, Exception e) throws Exception {
        if (log.isTraceEnabled()) {
            System.out.println(e.getMessage());

            e.printStackTrace();


            log.error(p.getTarget().getClass().getSimpleName() + " " + p.getSignature().getName() + " " + e.getMessage());
        }
    }
}

Here, using @ConditionalOnExpression("${endpoint.aspect.enabled:true}") you can enable/disable the log. just add endpoint.aspect.enabled:true into the application.property and control the log

More info about AOP visit here:

Spring docs about AOP

Sample article about AOP

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

Plot two histograms on single chart with matplotlib

Inspired by Solomon's answer, but to stick with the question, which is related to histogram, a clean solution is:

sns.distplot(bar)
sns.distplot(foo)
plt.show()

Make sure to plot the taller one first, otherwise you would need to set plt.ylim(0,0.45) so that the taller histogram is not chopped off.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

It is possible when the page itself is opened via a file:/// path.

<button onclick="window.open('file:///C:/Windows/notepad.exe')">
    Launch notepad
</button>

However, the moment you put it on a webserver (even if you access it via http://localhost/), you will get an error:

Error: Access to 'file:///C:/Windows/notepad.exe' from script denied

jQuery - Add ID instead of Class

$('selector').attr( 'id', 'yourId' );

How can I split a JavaScript string by white space or comma?

String.split() can also accept a regular expression:

input.split(/[ ,]+/);

This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Had the same issue recently, solved by adding traditional: true,

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Below are some of the way by which you can create a link button in MVC.

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)  
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })  
@Html.Action("Action", "Controller", new { area = "AreaName" })  
@Url.Action("Action", "Controller", new { area = "AreaName" })  
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a> 

Hope this will help you.

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

How to check if an app is installed from a web-page on an iPhone?

I need to do something like this I ended up going with the following solution.

I have a specific website URL that will open a page with two buttons

1) Button One go to website

2) Button Two go to application (iphone / android phone / tablet) you can fall back to a default location from here if the app is not installed (like another url or an app store)

3) cookie to remember users choice

<head>
<title>Mobile Router Example </title>


<script type="text/javascript">
    function set_cookie(name,value)
    {
       // js code to write cookie
    }
    function read_cookie(name) {
       // jsCode to read cookie
    }

    function goToApp(appLocation) {
        setTimeout(function() {
            window.location = appLocation;
              //this is a fallback if the app is not installed. Could direct to an app store or a website telling user how to get app


        }, 25);
        window.location = "custom-uri://AppShouldListenForThis";
    }

    function goToWeb(webLocation) {
        window.location = webLocation;
    }

    if (readCookie('appLinkIgnoreWeb') == 'true' ) {
        goToWeb('http://somewebsite');

    }
    else if (readCookie('appLinkIgnoreApp') == 'true') {
        goToApp('http://fallbackLocation');
    }



</script>
</head>
<body>


<div class="iphone_table_padding">
<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <!-- INTRO -->
            <span class="iphone_copy_intro">Check out our new app or go to website</span>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <!-- GET IPHONE APP BTN -->
                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreApp',document.getElementById('chkDontShow').checked);goToApp('http://getappfallback')">
                    <tr>
                        <td class="iphone_btn_on_left">&nbsp;</td>
                        <td class="iphone_btn_on_mid">
                            <span class="iphone_copy_btn">
                                Get The Mobile Applications
                            </span>
                        </td>
                        <td class="iphone_btn_on_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_btn_padding">

                <table border="0" cellspacing="0" cellpadding="0" class="iphone_btn"  onclick="set_cookie('appLinkIgnoreWeb',document.getElementById('chkDontShow').checked);goToWeb('http://www.website.com')">
                    <tr>
                        <td class="iphone_btn_left">&nbsp;</td>
                        <td class="iphone_btn_mid">
                            <span class="iphone_copy_btn">
                                Visit Website.com
                            </span>
                        </td>
                        <td class="iphone_btn_right">&nbsp;</td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
    <tr>
        <td class="iphone_table_leftRight">&nbsp;</td>
        <td>
            <div class="iphone_chk_padding">

                <!-- CHECK BOX -->
                <table border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td><input type="checkbox" id="chkDontShow" /></td>
                        <td>
                            <span class="iphone_copy_chk">
                                <label for="chkDontShow">&nbsp;Don&rsquo;t show this screen again.</label>
                            </span>
                        </td>
                    </tr>
                </table>

            </div>
        </td>
        <td class="iphone_table_leftRight">&nbsp;</td>
    </tr>
</table>

</div>

</body>
</html>

Mipmap drawables for icons

The understanding I have about mipmap is more or less like this:

When an image needs to be drawn, given we have different screen sizes are resolutions, some scaling will have to take part.

If you have an image that is ok for a low end cell phone, when you scale it to the size of a 10" tablet you have to "invent" pixels that don't actually exist. This is done with some interpolation algorithm. The more amount of pixels that have to be invented, the longer the process takes and quality starts to fail. Best quality is obtained with more complex algorithms that take longer (average of surrounding pixles vs copy the nearest pixel for example).

To reduce the number of pixels that have to be invented, with mipmap you provide different sizes/rsolutions of the same image, and the system will choose the nearest image to the resolution that has to be rendered and do the scaling from there. This should reduce the number of invented pixels saving resources to be used in calculating these pixels to provide a good quality image.

I read about this in an article explaining a performance problem in libgdx when scaling images:

http://www.badlogicgames.com/wordpress/?p=1403

What does collation mean?

Collation means assigning some order to the characters in an Alphabet, say, ASCII or Unicode etc.

Suppose you have 3 characters in your alphabet - {A,B,C}. You can define some example collations for it by assigning integral values to the characters

  1. Example 1 = {A=1,B=2,C=3}
  2. Example 2 = {C=1,B=2,A=3}
  3. Example 3 = {B=1,C=2,A=3}

As a matter of fact, you can define n! collations on an Alphabet of size n. Given such an order, different sorting routines likes LSD/MSD string sorts make use of it for sorting strings.

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Arrays vs Vectors: Introductory Similarities and Differences

arrays:

  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;

std::vector:

  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

What is the difference between baud rate and bit rate?

Bit rate:- Bit rate is nothing but number of bits transmitted per second.For example if Bit rate is 1000bps then 1000 bits are i.e. 0s or 1s transmitted per second.

Baud rate:- It means number of time signal changes its state.When the signal is binary then baud rate and bit rate are same.

Querying a linked sql server

I use open query to perform this task like so:

select top 1 *
INTO [DATABASE_TO_INSERT_INTO].[dbo].[TABLE_TO_SELECT_INTO]
from openquery(
    [LINKED_SERVER_NAME],
    'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)

The example above uses open query to select data from a database on a linked server into a database of your choosing.

Note: For completeness of reference, you may perform a simple select like so:

select top 1 * from openquery(
    [LINKED_SERVER_NAME],
    'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)

How to play a local video with Swift?

Here a solution for Swift 5.2

PlayerView.swift:

import AVFoundation
import UIKit

class PlayerView: UIView {

    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

    // Override UIView property
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}

VideoPlayer.swift

import AVFoundation
import Foundation

protocol VideoPlayerDelegate {
    func downloadedProgress(progress:Double)
    func readyToPlay()
    func didUpdateProgress(progress:Double)
    func didFinishPlayItem()
    func didFailPlayToEnd()
}

let videoContext: UnsafeMutableRawPointer? = nil

class VideoPlayer : NSObject {

    private var assetPlayer:AVPlayer?
    private var playerItem:AVPlayerItem?
    private var urlAsset:AVURLAsset?
    private var videoOutput:AVPlayerItemVideoOutput?

    private var assetDuration:Double = 0
    private var playerView:PlayerView?

    private var autoRepeatPlay:Bool = true
    private var autoPlay:Bool = true

    var delegate:VideoPlayerDelegate?

    var playerRate:Float = 1 {
        didSet {
            if let player = assetPlayer {
                player.rate = playerRate > 0 ? playerRate : 0.0
            }
        }
    }

    var volume:Float = 1.0 {
        didSet {
            if let player = assetPlayer {
                player.volume = volume > 0 ? volume : 0.0
            }
        }
    }

    // MARK: - Init

    convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
        self.init()

        playerView = view
        autoPlay = startAutoPlay
        autoRepeatPlay = repeatAfterEnd

        if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
            playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        }
        initialSetupWithURL(url: urlAsset)
        prepareToPlay()
    }

    override init() {
        super.init()
    }

    // MARK: - Public

    func isPlaying() -> Bool {
        if let player = assetPlayer {
            return player.rate > 0
        } else {
            return false
        }
    }

    func seekToPosition(seconds:Float64) {
        if let player = assetPlayer {
            pause()
            if let timeScale = player.currentItem?.asset.duration.timescale {
                player.seek(to: CMTimeMakeWithSeconds(seconds, preferredTimescale: timeScale), completionHandler: { (complete) in
                    self.play()
                })
            }
        }
    }

    func pause() {
        if let player = assetPlayer {
            player.pause()
        }
    }

    func play() {
        if let player = assetPlayer {
            if (player.currentItem?.status == .readyToPlay) {
                player.play()
                player.rate = playerRate
            }
        }
    }

    func cleanUp() {
        if let item = playerItem {
            item.removeObserver(self, forKeyPath: "status")
            item.removeObserver(self, forKeyPath: "loadedTimeRanges")
        }
        NotificationCenter.default.removeObserver(self)
        assetPlayer = nil
        playerItem = nil
        urlAsset = nil
    }

    // MARK: - Private

    private func prepareToPlay() {
        let keys = ["tracks"]
        if let asset = urlAsset {
            asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
                DispatchQueue.main.async {
                    self.startLoading()
                }
            })
        }
    }

    private func startLoading(){
        var error:NSError?
        guard let asset = urlAsset else {return}
        let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)

        if status == AVKeyValueStatus.loaded {
            assetDuration = CMTimeGetSeconds(asset.duration)

            let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
            videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
            playerItem = AVPlayerItem(asset: asset)

            if let item = playerItem {
                item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
                item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)

                NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
                NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)

                if let output = videoOutput {
                    item.add(output)

                    item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
                    assetPlayer = AVPlayer(playerItem: item)

                    if let player = assetPlayer {
                        player.rate = playerRate
                    }

                    addPeriodicalObserver()
                    if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                        layer.player = assetPlayer
                        print("player created")
                    }
                }
            }
        }
    }

    private func addPeriodicalObserver() {
        let timeInterval = CMTimeMake(value: 1, timescale: 1)

        if let player = assetPlayer {
            player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
                self.playerDidChangeTime(time: time)
            })
        }
    }

    private func playerDidChangeTime(time:CMTime) {
        if let player = assetPlayer {
            let timeNow = CMTimeGetSeconds(player.currentTime())
            let progress = timeNow / assetDuration

            delegate?.didUpdateProgress(progress: progress)
        }
    }

    @objc private func playerItemDidReachEnd() {
        delegate?.didFinishPlayItem()

        if let player = assetPlayer {
            player.seek(to: CMTime.zero)
            if autoRepeatPlay == true {
                play()
            }
        }
    }

    @objc private func didFailedToPlayToEnd() {
        delegate?.didFailPlayToEnd()
    }

    private func playerDidChangeStatus(status:AVPlayer.Status) {
        if status == .failed {
            print("Failed to load video")
        } else if status == .readyToPlay, let player = assetPlayer {
            volume = player.volume
            delegate?.readyToPlay()

            if autoPlay == true && player.rate == 0.0 {
                play()
            }
        }
    }

    private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
        var maximum:TimeInterval = 0
        for value in ranges {
            let range:CMTimeRange = value.timeRangeValue
            let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
            if currentLoadedTimeRange > maximum {
                maximum = currentLoadedTimeRange
            }
        }
        let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration

        delegate?.downloadedProgress(progress: progress)
    }

    deinit {
        cleanUp()
    }

    private func initialSetupWithURL(url:NSURL) {
        let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
        urlAsset = AVURLAsset(url: url as URL, options: options)
    }

    // MARK: - Observations
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if context == videoContext {
            if let key = keyPath {
                if key == "status", let player = assetPlayer {
                    playerDidChangeStatus(status: player.status)
                } else if key == "loadedTimeRanges", let item = playerItem {
                    moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
                }
            }
        }
    }
}

Usage:

private var playerView: PlayerView = PlayerView()
private var videoPlayer:VideoPlayer?

and inside viewDidLoad():

view.addSubview(playerView)
preparePlayer()

// set Constraints (if you do it purely in code)
playerView.translatesAutoresizingMaskIntoConstraints = false
playerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10.0).isActive = true
playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10.0).isActive = true
playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10.0).isActive = true
playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10.0).isActive = true
private func preparePlayer() {
    if let filePath = Bundle.main.path(forResource: "my video", ofType: "mp4") {
        let fileURL = NSURL(fileURLWithPath: filePath)
        videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
        if let player = videoPlayer {
            player.playerRate = 0.67
        }
    }
}

What's the correct way to convert bytes to a hex string in Python 3?

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3.

I'm also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

Given that, the best approach I know is:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

The following assertion will be true for either Python 2 or Python 3, assuming you haven't activated the unicode_literals future in Python 2:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(Or you can use ''.join() to omit the space between the bytes, etc.)

Split string into array of character strings

To sum up the other answers...

This works on all Java versions:

"cat".split("(?!^)")

This only works on Java 8 and up:

"cat".split("")

C++ Redefinition Header Files (winsock2.h)

I wouldn't use just FILENAME_H but

#ifndef FILENAME_H_AF06570D_B36E_4B82_8F97_C456AF4A38FD
#define FILENAME_H_AF06570D_B36E_4B82_8F97_C456AF4A38FD

//code stuff
#endif // FILENAME_H_AF06570D_B36E_4B82_8F97_C456AF4A38FD

I have always used a postfix guid. I came across a very poor code base some years ago that had different header files with the same file name and include guard. The files in question had defined a class with the same name. If only namespaces were used. Some projects compiled some didn't. Using unique guards was a part of the solution in differentiating headers and their contents.

On Windows with Visual Studio use guidgen.exe, on Linux uuidgen -t.

mysqld: Can't change dir to data. Server doesn't start

mariofertc completely solved this for me here are his steps:

  1. Verify mysql's data directory is empty (before you delete it though, save the err file for your records).

  2. Under the mysql bin path run: mysqld.exe --initialize-insecure

  3. add to my.ini (mysql's configuration file) the following: [mysqld] default_authentication_plugin=mysql_native_password

Then check services (via task manager) to make sure MySql is running, if not - right click MySql and start it.

I'll also note, if you don't have your mysql configuration file in the mysql bin and can't find it via the windows search, you will want to look for it in C:\Program Data\Mysql\ Note that it might be a different name other than my.ini, like a template, as Heesu mentions here: Can't find my.ini (mysql 5.7) Just find the template that matches the version of your mysql via the command mysql --version

How to embed YouTube videos in PHP?

You can do this simple with Joomla. Let me assume a sample YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

<?php 
$youtubeUrl =  JUri::getInstance('https://www.youtube.com/watch?v=ndmXkyohT1M');
$videoId = $youtubeUrl->getVar('v'); ?>

<iframe id="ytplayer" type="text/html" width="640" height="390"  src="http://www.youtube.com/embed/<?php echo $videoId; ?>"  frameborder="0"/>

Excel 2010: how to use autocomplete in validation list

Building on the answer of JMax, use this formula for the dynamic named range to make the solution work for multiple rows:

=OFFSET(Sheet2!$A$1,MATCH(INDIRECT("Sheet1!"&ADDRESS(ROW(),COLUMN(),4))&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))

Create a custom event in Java

The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:

 public class MyClass
 {
        //... class code goes here

        public interface DataLoadFinishedListener {
            public void onDataLoadFinishedListener(int data_type);
        }

        private DataLoadFinishedListener m_lDataLoadFinished;

        public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
            this.m_lDataLoadFinished = dlf;
        }



        private void someOtherMethodOfMyClass()
        {
            m_lDataLoadFinished.onDataLoadFinishedListener(1);
        }    
    }

Usage is as follows:

myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
            @Override
            public void onDataLoadFinishedListener(int data_type) {
                }
            });

Arduino Tools > Serial Port greyed out

open $arduinoHome/arduino in text editor and modify last string:

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base "$@"

to

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel -Dgnu.io.rxtx.SerialPorts="/dev/ttyACMN" processing.app.Base "$@"

(set property gnu.io.rxtx.SerialPorts to /dev/ttyACMN,where ttyACMN is name of serial port which you use)

it may temporary fix bug in rxtx library. helped me to upload sketch with arduino1.0.5 IDE.

Maybe would helpful for someone.

ImportError: No module named apiclient.discovery

apiclient was the original name of the library.
At some point, it was switched over to be googleapiclient.

If your code is running on Google App Engine, both should work.

If you are running the application yourself, with the google-api-python-client installed, both should work as well.

Although, if we take a look at the source code of the apiclient package's __init__.py module, we can see that the apiclient module was simply kept around for backwards-compatibility.

Retain apiclient as an alias for googleapiclient.

So, you really should be using googleapiclient in your code, since the apiclient alias was just maintained as to not break legacy code.

# bad
from apiclient.discovery import build

# good
from googleapiclient.discovery import build

Counting Line Numbers in Eclipse

Search > File Search

Check the Regular expression box.

Use this expression:

\n[\s]*

Select whatever file types (*.java, *.xml, etc..) and working sets are appropriate for you.

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

How to clear a textbox once a button is clicked in WPF?

You can use Any of the statement given below to clear the text of the text box on button click:

  1. textBoxName.Text = string.Empty;
  2. textBoxName.Clear();
  3. textBoxName.Text = "";

String split on new line, tab and some number of spaces

If you look at the documentation for str.split:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

In other words, if you're trying to figure out what to pass to split to get '\n\tName: Jane Smith' to ['Name:', 'Jane', 'Smith'], just pass nothing (or None).

This almost solves your whole problem. There are two parts left.

First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:

s.split(None, 1)

Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:

key, value = s.split(None, 1)
key = key[:-1]

There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.

How do I hide an element when printing a web page?

The best thing to do is to create a "print-only" version of the page.

Oh, wait... this isn't 1999 anymore. Use a print CSS with "display: none".

JSON to string variable dump

something along this?

function dump(x, indent) {
    var indent = indent || '';
    var s = '';
    if (Array.isArray(x)) {
        s += '[';
        for (var i=0; i<x.length; i++) {
            s += dump(x[i], indent)
            if (i < x.length-1) s += ', ';
        }
        s +=']';
    } else if (x === null) {
      s = 'NULL';
    } else switch(typeof x) {
        case 'undefined':
            s += 'UNDEFINED';
            break;
        case 'object':
            s += "{ ";
            var first = true;
            for (var p in x) {
                if (!first) s += indent + '  ';
                s += p + ': ';
                s += dump(x[p], indent + '  ');
                s += "\n"
                first = false;
            }
            s += '}';
            break;
        case 'boolean':
            s += (x) ? 'TRUE' : 'FALSE';
            break;
        case 'number':
            s += x;
            break;
        case 'string':
            s += '"' + x + '"';
            break;
        case 'function':
            s += '<FUNCTION>';
            break;
        default:
            s += x;
            break;
    }
    return s;
}

How to input automatically when running a shell over SSH?

ssh-key with passphrase, with keychain

keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.

To enable keychain, install it and add something like the following to ~/.bash_profile:

eval keychain --agents ssh --eval id_rsa From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.

Got this info from;

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Hope this helps

I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)

  1. edit the bashrc file to add this script;

    Check if the SSH agent is awake

    if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi

    Above line will start the expect script upon terminal launch.

    ./ssh.exp

here's the content of this expect script

#!/usr/bin/expect

set timeout 20

set passphrase "test"

spawn "./keyadding.sh"

expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"

send "$passphrase\r";

interact

Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)

#!/bin/bash

ssh-add /the/path/of/yourkey_id_rsa

exit 0

I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp) and also a chmod +x script.sh to make it executable. A chmod +r term_boot.exp would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.

Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

Will certainly change my method for this one when I'll have the time.

Combine a list of data frames into one data frame by row

How it should be done in the tidyverse:

df.dplyr.purrr <- listOfDataFrames %>% map_df(bind_rows)

How to add hyperlink in JLabel?

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

So just try it :

I think that's exactly what you're searching for.

Here's the complete code example :

/**
 * Example of a jLabel Hyperlink and a jLabel Mailto
 */

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author ibrabelware
 */
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
    /**
     * Creates new form JLabelLink
     */
    public JLabelLink() {
        this.setTitle("jLabelLinkExample");
        this.setSize(300, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));

    pan.add(contact);
    pan.add(website);
        this.setContentPane(pan);
        this.setVisible(true);
        sendMail(contact);
        goWebsite(website);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JLabelLink().setVisible(true);
            }
        });
    }

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }
}

How can I get a Dialog style activity window to fill the screen?

Matthias' answer is mostly right but it's still not filling the entire screen as it has a small padding on each side (pointed out by @Holmes). In addition to his code, we could fix this by extending Theme.Dialog style and add some attributes like this.

<style name="MyDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then we simply declare Activity with theme set to MyDialog:

<activity
    android:name=".FooActivity"
    android:theme="@style/MyDialog" />

Initializing a struct to 0

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:
C and C++ : Partial initialization of automatic structure

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

  • JDK - Java Development Kit
  • JRE - Java Runtime Environment
  • Java SE - Java Standard Edition

SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).

The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.

Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).


Edited 2011-04-06: The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)


Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.

Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.

Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).

What's the best way to loop through a set of elements in JavaScript?

At the risk of getting yelled at, i would get a javascript helper library like jquery or prototype they encapsulate the logic in nice methods - both have an .each method/iterator to do it - and they both strive to make it cross-browser compatible

EDIT: This answer was posted in 2008. Today much better constructs exist. This particular case could be solved with a .forEach.

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = test_array.map(fields => fields.map(escape))

Then simply do:

csv = escaped_array.map(fields => fields.join(","))
                .join("\n")

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv
window.open(encodeURI(dl))

Business logic in MVC

Business rules go in the model.

Say you were displaying emails for a mailing list. The user clicks the "delete" button next to one of the emails, the controller notifies the model to delete entry N, then notifies the view the model has changed.

Perhaps the admin's email should never be removed from the list. That's a business rule, that knowledge belongs in the model. The view may ultimately represent this rule somehow -- perhaps the model exposes an "IsDeletable" property which is a function of the business rule, so that the delete button in the view is disabled for certain entries - but the rule itself isn't contained in the view.

The model is ultimately gatekeeper for your data. You should be able to test your business logic without touching the UI at all.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

first you have to give echo to display base url. Then change below value in your autoload.php which will be inside your application/config/ folder. $autoload['helper'] = array('url'); then your issue will be resolved.

insert datetime value in sql database with c#

you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"

Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.

DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";

sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b or --bind flag.

python -m http.server 8000 --bind 127.0.0.1

The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.

Convert XML String to Object

public string Serialize<T>(T settings)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringWriter outStream = new StringWriter();
    serializer.Serialize(outStream, settings);
    return outStream.ToString();
}

Compare dates in MySQL

This works for me:

select date_format(date(starttime),'%Y-%m-%d') from data
where date(starttime) >= date '2012-11-02';

Note the format string '%Y-%m-%d' and the format of the input date.

How to get current moment in ISO 8601 format with date, hour, and minute?

I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.

private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";

public static Calendar isoToCalendar(final String inputDate) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
        Date date = dateFormat.parse(inputDate);
        calendar.setTime(date);
    } catch (ParseException e) {
        Log.e("TAG",e.getMessage());
    }
    return calendar;
}

REMEMBER: The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

How do I center list items inside a UL element?

A more modern way is to use flexbox:

_x000D_
_x000D_
ul{_x000D_
  list-style-type:none;_x000D_
  display:flex;_x000D_
  justify-content: center;_x000D_
_x000D_
}_x000D_
ul li{_x000D_
  display: list-item;_x000D_
  background: black;_x000D_
  padding: 5px 10px;_x000D_
  color:white;_x000D_
  margin: 0 3px;_x000D_
}_x000D_
div{_x000D_
  background: wheat;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
  <li>One</li>_x000D_
  <li>Two</li>_x000D_
  <li>Three</li>_x000D_
</ul>  _x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sorting object property by values

Here is one more example:

_x000D_
_x000D_
function sortObject(obj) {_x000D_
  var arr = [];_x000D_
  var prop;_x000D_
  for (prop in obj) {_x000D_
    if (obj.hasOwnProperty(prop)) {_x000D_
      arr.push({_x000D_
        'key': prop,_x000D_
        'value': obj[prop]_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
  arr.sort(function(a, b) {_x000D_
    return a.value - b.value;_x000D_
  });_x000D_
  return arr; // returns array_x000D_
}_x000D_
var list = {_x000D_
  car: 300,_x000D_
  bike: 60,_x000D_
  motorbike: 200,_x000D_
  airplane: 1000,_x000D_
  helicopter: 400,_x000D_
  rocket: 8 * 60 * 60_x000D_
};_x000D_
var arr = sortObject(list);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Is there a way to specify which pytest tests to run from a file?

Method 1: Randomly selected tests. Long and ugly.

python -m pytest test/stress/test_performance.py::TestPerformance::test_continuous_trigger test/integration/test_config.py::TestConfig::test_valid_config

Method 2: Use Keyword Expressions.

Note: I am searching by testcase names. Same is applicable to TestClass names.

Case 1: The below will run whichever is found. Since we have used 'OR' .

python -m pytest -k 'test_password_valid or test_no_configuration'

Lets say the two above are actually correct, 2 tests will be run.

Case 2: Now an incorrect name and another correct name.

python -m pytest -k 'test_password_validzzzzzz or test_no_configuration' 

Only one is found and run.

Case 3: If you want all tests to run or no one, then use AND

python -m pytest -k 'test_password_valid and test_no_configuration'

Both will be run if correct or none.

Case 4: Run test only in one folder:

python -m pytest test/project1/integration -k 'test_password_valid or test_no_configuration'

Case 5: Run test from only one file.

python -m pytest test/integration/test_authentication.py -k 'test_password_expiry or test_incorrect_password'

Case 6: Run all tests except the match.

python -m pytest test/integration/test_authentication.py -k 'not  test_incorrect_password'

How can I list ALL DNS records?

  1. A zone transfer is the only way to be sure you have all the subdomain records. If the DNS is correctly configured you should not normally be able to perform an external zone transfer.

  2. The scans.io project has a database of DNS records that can be downloaded and searched for subdomains. This requires downloading the 87GB of DNS data, alternatively you can try the online search of the data at https://hackertarget.com/find-dns-host-records/

Read specific columns from a csv file with csv module?

import pandas as pd 
csv_file = pd.read_csv("file.csv") 
column_val_list = csv_file.column_name._ndarray_values

Combine Date and Time columns using python pandas

Use the combine function:

datetime.datetime.combine(date, time)

What does it mean when an HTTP request returns status code 0?

Many of the answers here are wrong. It seems people figure out what was causing status==0 in their particular case and then generalize that as the answer.

Practically speaking, status==0 for a failed XmlHttpRequest should be considered an undefined error.

The actual W3C spec defines the conditions for which zero is returned here: https://fetch.spec.whatwg.org/#concept-network-error

As you can see from the spec (fetch or XmlHttpRequest) this code could be the result of an error that happened even before the server is contacted.

Some of the common situations that produce this status code are reflected in the other answers but it could be any or none of these problems:

  1. Illegal cross origin request (see CORS)
  2. Firewall block or filtering
  3. The request itself was cancelled in code
  4. An installed browser extension is mucking things up

What would be helpful would be for browsers to provide detailed error reporting for more of these status==0 scenarios. Indeed, sometimes status==0 will accompany a helpful console message, but in others there is no other information.

Custom domain for GitHub project pages

Short answer

These detailed explanations are great, but the OP's (and my) confusion could be resolved with one sentence: "Direct DNS to your GitHub username or organization, ignoring the specific project, and add the appropriate CNAME files in your project repositories: GitHub will send the right DNS to the right project based on files in the respository."

How to have Android Service communicate with Activity

My method:

Class to manage send and receive message from/to service/activity:

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class MessageManager {

    public interface IOnHandleMessage{
        // Messages
        int MSG_HANDSHAKE = 0x1;

        void onHandleMessage(Message msg);
    }

    private static final String LOGCAT = MessageManager.class.getSimpleName();

    private Messenger mMsgSender;
    private Messenger mMsgReceiver;
    private List<Message> mMessages;

    public MessageManager(IOnHandleMessage callback, IBinder target){
        mMsgReceiver = new Messenger(new MessageHandler(callback, MessageHandler.TYPE_ACTIVITY));
        mMsgSender = new Messenger(target);
        mMessages = new ArrayList<>();
    }

    public MessageManager(IOnHandleMessage callback){
        mMsgReceiver = new Messenger(new MessageHandler(callback, MessageHandler.TYPE_SERVICE));
        mMsgSender = null;
        mMessages = new ArrayList<>();
    }

    /* START Getter & Setter Methods */
    public Messenger getMsgSender() {
        return mMsgSender;
    }

    public void setMsgSender(Messenger sender) {
        this.mMsgSender = sender;
    }

    public Messenger getMsgReceiver() {
        return mMsgReceiver;
    }

    public void setMsgReceiver(Messenger receiver) {
        this.mMsgReceiver = receiver;
    }

    public List<Message> getLastMessages() {
        return mMessages;
    }

    public void addMessage(Message message) {
        this.mMessages.add(message);
    }
    /* END Getter & Setter Methods */

    /* START Public Methods */
    public void sendMessage(int what, int arg1, int arg2, Bundle msgData){
        if(mMsgSender != null && mMsgReceiver != null) {
            try {
                Message msg = Message.obtain(null, what, arg1, arg2);
                msg.replyTo = mMsgReceiver;
                if(msgData != null){
                    msg.setData(msgData);
                }
                mMsgSender.send(msg);
            } catch (RemoteException rE) {
                onException(rE);
            }
        }
    }

    public void sendHandshake(){
        if(mMsgSender != null && mMsgReceiver != null){
            sendMessage(IOnHandleMessage.MSG_HANDSHAKE, 0, 0, null);
        }
    }
    /* END Public Methods */

    /* START Private Methods */
    private void onException(Exception e){
        Log.e(LOGCAT, e.getMessage());
        e.printStackTrace();
    }
    /* END Private Methods */

    /** START Private Classes **/
    private class MessageHandler extends Handler {

        // Types
        final static int TYPE_SERVICE = 0x1;
        final static int TYPE_ACTIVITY = 0x2;

        private IOnHandleMessage mCallback;
        private int mType;

        public MessageHandler(IOnHandleMessage callback, int type){
            mCallback = callback;
            mType = type;
        }

        @Override
        public void handleMessage(Message msg){
            addMessage(msg);
            switch(msg.what){
                case IOnHandleMessage.MSG_HANDSHAKE:
                    switch(mType){
                        case TYPE_SERVICE:
                            setMsgSender(msg.replyTo);
                            sendHandshake();
                            break;
                        case TYPE_ACTIVITY:
                            Log.v(LOGCAT, "HERE");
                            break;
                    }
                    break;
                default:
                    if(mCallback != null){
                        mCallback.onHandleMessage(msg);
                    }
                    break;
            }
        }

    }
    /** END Private Classes **/

}

In Activity Example:

public class activity extends AppCompatActivity
      implements     ServiceConnection,
                     MessageManager.IOnHandleMessage { 

    [....]

    private MessageManager mMessenger;

    private void initMyMessenger(IBinder iBinder){
        mMessenger = new MessageManager(this, iBinder);
        mMessenger.sendHandshake();
    }

    private void bindToService(){
        Intent intent = new Intent(this, TagScanService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        /* START THE SERVICE IF NEEDED */
    }

    private void unbindToService(){
    /* UNBIND when you want (onDestroy, after operation...)
        if(mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    /* START Override MessageManager.IOnHandleMessage Methods */
    @Override
    public void onHandleMessage(Message msg) {
        switch(msg.what){
            case Constants.MSG_SYNC_PROGRESS:
                Bundle data = msg.getData();
                String text = data.getString(Constants.KEY_MSG_TEXT);
                setMessageProgress(text);
                break;
            case Constants.MSG_START_SYNC:
                onStartSync();
                break;
            case Constants.MSG_END_SYNC:
                onEndSync(msg.arg1 == Constants.ARG1_SUCCESS);
                mBound = false;
                break;
        }
    }
    /* END Override MessageManager.IOnHandleMessage Methods */

    /** START Override ServiceConnection Methods **/
    private class BLEScanServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            initMyMessenger(iBinder);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mMessenger = null;
            mBound = false;
        }
    }
    /** END Override ServiceConnection Methods **/

In Service Example:

public class Blablabla extends Service
    implements     MessageManager.IOnHandleMessage {

    [...]

    private MessageManager mMessenger;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        super.onBind(intent);
        initMessageManager();
        return mMessenger.getMsgReceiver().getBinder();
    }

    private void initMessageManager(){
        mMessenger = new MessageManager(this);
    }

    /* START Override IOnHandleMessage Methods */
    @Override
    public void onHandleMessage(Message msg) {
    /* Do what you want when u get a message looking the "what" attribute */
    }
    /* END Override IOnHandleMessage Methods */

Send a message from Activity / Service:

mMessenger.sendMessage(what, arg1, arg2, dataBundle);

How this works:

on the activity you start or bind the service. The service "OnBind" methods return the Binder to his MessageManager, the in the Activity through the "Service Connection" interface methods implementation "OnServiceConnected" you get this IBinder and init you MessageManager using it. After the Activity has init his MessageManager the MessageHandler send and Handshake to the service so it can set his "MessageHandler" sender ( the "private Messenger mMsgSender;" in MessageManager ). Doing this the service know to who send his messages.

You can also implement this using a List/Queue of Messenger "sender" in the MessageManager so you can send multiple messages to different Activities/Services or you can use a List/Queue of Messenger "receiver" in the MessageManager so you can receive multiple message from different Activities/Services.

In the "MessageManager" instance you have a list of all messages received.

As you can see the connection between "Activity's Messenger" and "Service Messenger" using this "MessageManager" instance is automatic, it is done through the "OnServiceConnected" method and through the use of the "Handshake".

Hope this is helpful for you :) Thank you very much! Bye :D

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

How to select specified node within Xpath node sets by index with Selenium?

//img[@title='Modify'][i]

is short for

/descendant-or-self::node()/img[@title='Modify'][i]

hence is returning the i'th node under the same parent node.

You want

/descendant-or-self::img[@title='Modify'][i]

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013

Reading data from a website using C#

If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:

        WebClient web = new WebClient();
        System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            String text = reader.ReadToEnd();
        }

If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.

Why can't I do <img src="C:/localfile.jpg">?

what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

What is the best way to left align and right align two div tags?

<div style="float: left;">Left Div</div>
<div style="float: right;">Right Div</div>

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Why is MySQL InnoDB insert so slow?

InnoDB has transaction support, you're not using explicit transactions so innoDB has to do a commit after each statement ("performs a log flush to disk for every insert").

Execute this command before your loop:

START TRANSACTION

and this after you loop

COMMIT

UIButton action in table view cell

in Swift 4

in cellForRowAt indexPath:

 cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)

function that run after user pressed button:

@objc func onClicked(sender: UIButton){
        let tag = sender.tag


    }

html text input onchange event

Well unless I misunderstand you can just use the onChange attribute:

<input type="text" onChange="return bar()">

Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

I think you want to return a REFCURSOR:

create function test_cursor 
            return sys_refcursor
            is
                    c_result sys_refcursor;
            begin
                    open c_result for
                    select * from dual;
                    return c_result;
            end;

Update: If you need to call this from SQL, use a table function like @Tony Andrews suggested.

how to save DOMPDF generated content to file?

I have just used dompdf and the code was a little different but it worked.

Here it is:

require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

Only difference here is that all of the files in the include directory are included.

Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.

What is causing "Unable to allocate memory for pool" in PHP?

solution for me:

  • apc.ttl=0
  • apc.shm_size=anything you want

edit start

warning!

@bokan indicated me that i should add a warning here.

if you have a ttl of 0 this means the every cached item can be purged immediately. so if you have a small cache size like 2mb and a ttl of 0 this would render the apc useless, because the data in the cache gets always overwritten.

lowering the ttl means only that the cache cannot become full, only with items which can't be replaced.

so you have to choose a good balance between ttl and cache size.

in my case i had a cache size of 1gb, so it was more than enough for me.

edit end

had the same issue on centos 5 with php 5.2.17 and noticed that if the cache size is small and the ttl parameter is "high" (like 7200) while having a lot of php files to cache, then the cache fills up quite fast and apc doesn't find anything which it can remove because all files in the cache still fit in the ttl.

increasing the memory size is only a part solution, you still run in this error if you cache fills up and all files are within the ttl.

so my solution was to set the ttl to 0, so apc fills up the cache an there is allways the possibility for apc to clear some memory for new data.

hope that helps

edit: see also: http://pecl.php.net/bugs/bug.php?id=16966

download http://pecl.php.net/get/APC extract and run the apc.php, there you have a nice diagram how your cache usage look like

Refused to load the script because it violates the following Content Security Policy directive

We used this:

<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">

Angular 2: Get Values of Multiple Checked Checkboxes

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

1. To initiate optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. to update the optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

Get column index from column name in python pandas

For returning multiple column indices, I recommend using the pandas.Index method get_indexer, if you have unique labels:

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)

If you have non-unique labels in the index (columns only support unique labels) get_indexer_for. It takes the same args as get_indeder:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]}, 
    index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)

Both methods also support non-exact indexing with, f.i. for float values taking the nearest value with a tolerance. If two indices have the same distance to the specified label or are duplicates, the index with the larger index value is selected:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
    index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)

ng if with angular for string contains

Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.

Controller:

angular.module("myApp")
.controller("myController",function(){
    var self = this;

    self.select = { /* ... */ };

    self.showFoo = function() {
        //Checks if self.select.name contains the character '?'
        return self.select.name.indexOf('?') != -1;
    }
});

Page example:

<div ng-app="myApp" ng-controller="myController as vm">
    <p ng-show="vm.showFoo()">Bar</p>
</div>

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I know this MIGHT not be the cause of your issue, but I've spent a few hours hitting my head against the wall to solve this issue and this is my solution.

(running Windows 10 x32)

So I had installed XAMPP in a deeply nested directory and all the conf files make reference to root\xampp\apache, whereas my files were some_dir\another_dir\whatthehelliswrongwithme\finally\xampp\apache

so my options were to either go through and edit all \xampp\apache references and point them at the right place, OR, the much simpler option... reinstall XAMPP at the root, so the references all point to the right place.

A little annoying, but I guess that's what we get when Mac and Windows try to be friends..

Hope it helps a few of you.

How to deploy a Java Web Application (.war) on tomcat?

  • copy the .war file in the webapps folder
  • upload the file using the manager application - http://host:port/manager. You will have to setup some users beforehand.
  • (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in webapps/webappname

Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:

After you have it deployed (check the /logs dir for any problems), it should be accessible via: http://host:port/yourwebappname/. So in your case, one of those:

http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/

If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)

How can I validate a string to only allow alphanumeric characters in it?

You could do it easily with an extension function rather than a regex ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

Per comment :) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}

Automatically running a batch file as an administrator

Put each line in cmd or all of theme in the batch file:

@echo off

if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)

"Put your command here"

it works fine for me.

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Copy a file in a sane, safe and efficient way

Qt has a method for copying files:

#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".

Clearing <input type='file' /> using jQuery

$("#control").val('') is all you need! Tested on Chrome using JQuery 1.11

Other users have tested in Firefox as well.

Installing Node.js (and npm) on Windows 10

Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.

Original answer:

Follow these steps, closely:

  • http://nodejs.org/download/ download the 64 bits version, 32 is for hipsters
  • Install it anywhere you want, by default: C:\Program Files\nodejs
  • Control Panel -> System -> Advanced system settings -> Environment Variables
  • Select PATH and choose to edit it.

If the PATH variable is empty, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm, append the following right after: ;C:\Program Files\nodejs

If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.

Re-start the command prompt and npm will now work.

Display html text in uitextview

You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

https://github.com/AliSoftware/OHAttributedLabel

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Windows service on Local Computer started and then stopped error

Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:

"Service on local computer started and then stopped. some services stop automatically..."

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Simple timeout in java

Use this line of code:

Thread.sleep(1000);

It will sleep for 1 second.

Byte Array and Int conversion in Java

You're swapping endianness between your two methods. You have intToByteArray(int a) assigning the low-order bits into ret[0], but then byteArrayToInt(byte[] b) assigns b[0] to the high-order bits of the result. You need to invert one or the other, like:

public static byte[] intToByteArray(int a)
{
    byte[] ret = new byte[4];
    ret[3] = (byte) (a & 0xFF);   
    ret[2] = (byte) ((a >> 8) & 0xFF);   
    ret[1] = (byte) ((a >> 16) & 0xFF);   
    ret[0] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

How to convert View Model into JSON object in ASP.NET MVC?

Well done, you've only just started using MVC and you've found its first major flaw.

You don't really want to be converting it to JSON in the view, and you don't really want to convert it in the controller, as neither of these locations make sense. Unfortunately, you're stuck with this situation.

The best thing I've found to do is send the JSON to the view in a ViewModel, like this:

var data = somedata;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);

return View("viewname", viewModel);

then use

<%= Model.JsonData %>

in your view. Be aware that the standard .NET JavaScriptSerializer is pretty crap.

doing it in the controller at least makes it testable (although not exactly like the above - you probably want to take an ISerializer as a dependency so you can mock it)

Update also, regarding your JavaScript, it would be good practice to wrap ALL the widget JS you have above like so:

(
    // all js here
)();

this way if you put multiple widgets on a page, you won't get conflicts (unless you need to access the methods from elsewhere in the page, but in that case you should be registering the widget with some widget framework anyway). It may not be a problem now, but it would be good practice to add the brackets now to save yourself muchos effort in the future when it becomes a requirement, it's also good OO practice to encapsulate the functionality.

How to define a two-dimensional array?

Using NumPy you can initialize empty matrix like this:

import numpy as np
mm = np.matrix([])

And later append data like this:

mm = np.append(mm, [[1,2]], axis=1)

TSQL Pivot without aggregate function

The OP didn't actually need to pivot without agregation but for those of you coming here to know how see:

sql parameterised cte query

The answer to that question involves a situation where pivot without aggregation is needed so an example of doing it is part of the solution.

Convert string to hex-string in C#

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

How to install Android SDK on Ubuntu?

Android SDK Manager

Get it from the Snap Store

sudo snap install androidsdk

Usage

You can use the sdkmanager to perform the following tasks.

List installed and available packages

androidsdk --list [options]

Install packages

androidsdk packages [options]

The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.

For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:

androidsdk "platform-tools" "platforms;android-28"

Alternatively, you can pass a text file that specifies all packages:

androidsdk --package_file=package_file [options]

The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).

To uninstall, simply add the --uninstall flag:

androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]

Update all installed packages

androidsdk --update [options]

Note

androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk

Location of installed android sdk files : /home/user/AndroidSDK

See all sdkmanager options in google documentation

How to get xdebug var_dump to show full object/array

These are configurable variables in php.ini:

; with sane limits
xdebug.var_display_max_depth = 10
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024 


; with no limits
; (maximum nesting is 1023)
xdebug.var_display_max_depth = -1 
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1 

Of course, these may also be set at runtime via ini_set(), useful if you don't want to modify php.ini and restart your web server but need to quickly inspect something more deeply.

ini_set('xdebug.var_display_max_depth', '10');
ini_set('xdebug.var_display_max_children', '256');
ini_set('xdebug.var_display_max_data', '1024');

Xdebug settings are explained in the official documentation.

Table overflowing outside of div

You can prevent tables from expanding beyond their parent div by using table-layout:fixed.

The CSS below will make your tables expand to the width of the div surrounding it.

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

I found this trick here.

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

jQuery textbox change event doesn't fire until textbox loses focus?

$(this).bind('input propertychange', function() {
        //your code here
    });

This is works for typing, paste, right click mouse paste etc.

Execute PHP function with onclick

It can be done and with rather simple php if this is your button

<input type="submit" name="submit>

and this is your php code

if(isset($_POST["submit"])) { php code here }

the code get's called when submit get's posted which happens when the button is clicked.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I have solved this issue by:

  1. go to sdk folder/platform-tools by cmd ,type adb shell
  2. delete all the .apk files of your project from ../output-folder
  3. restart your emulator
  4. run your project.

How to get a context in a recycler view adapter

If you are using Databinding on layout you can get the context from holder. An exemple below.

@Override
public void onBindViewHolder(@NonNull GenericViewHolder holder, int position) {
    View currentView = holder.binding.getRoot().findViewById(R.id.cycle_count_manage_location_line_layout);// id of your root layout
    currentView.setBackgroundColor(ContextCompat.getColor(holder.binding.getRoot().getContext(), R.color.light_green));
}

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

Why I got " cannot be resolved to a type" error?

In my case the missing type was referencing an import for java class in a dependent jar. For some reason my project file was missing the javabuilder and therefore couldnt resolve the path to the import.

Why it was missing in the first place I don't know, but adding these lines in fixed the error.

<buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
</buildCommand>

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

Get Application Name/ Label via ADB Shell or Terminal

If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,

$  adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox

Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk

After that aapt tool comes in handy :

$  adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...

Again some grep magic to get the Label.

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

How to get thread id from a thread pool?

The accepted answer answers the question about getting a thread id, but it doesn't let you do "Thread X of Y" messages. Thread ids are unique across threads but don't necessarily start from 0 or 1.

Here is an example matching the question:

import java.util.concurrent.*;
class ThreadIdTest {

  public static void main(String[] args) {

    final int numThreads = 5;
    ExecutorService exec = Executors.newFixedThreadPool(numThreads);

    for (int i=0; i<10; i++) {
      exec.execute(new Runnable() {
        public void run() {
          long threadId = Thread.currentThread().getId();
          System.out.println("I am thread " + threadId + " of " + numThreads);
        }
      });
    }

    exec.shutdown();
  }
}

and the output:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 11 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 12 of 5

A slight tweak using modulo arithmetic will allow you to do "thread X of Y" correctly:

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;

New results:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest  
I am thread 2 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 5 of 5 
I am thread 1 of 5 
I am thread 4 of 5 
I am thread 1 of 5 
I am thread 2 of 5 
I am thread 3 of 5 

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

How to return a struct from a function in C++?

You have a scope problem. Define the struct before the function, not inside it.

How can I find all of the distinct file extensions in a folder hierarchy?

Adding my own variation to the mix. I think it's the simplest of the lot and can be useful when efficiency is not a big concern.

find . -type f | grep -o -E '\.[^\.]+$' | sort -u

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

Route.get() requires callback functions but got a "object Undefined"

In my case I was trying to 'get' from express app. Instead I had to do SET.

app.set('view engine','pug');

Oracle SQL, concatenate multiple columns + add text

You have two options for concatenating strings in Oracle:

CONCAT example:

CONCAT(
  CONCAT(
    CONCAT(
      CONCAT(
        CONCAT('I like ', t.type_desc_column), 
        ' cake with '), 
      t.icing_desc_column),
    ' and a '),
  t.fruit_desc_column)

Using || example:

'I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a ' || t.fruit_desc_column

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

popup form using html/javascript/css

Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/

Add a Button or link to your page like this

<p><a href="#inline">click to open</a></p>

“#inline” here should be the “id” of the that will contain the form.

<div id="inline">
 <h2>Send us a Message</h2>
 <form id="contact" name="contact" action="#" method="post">
 <label for="email">Your E-mail</label>
 <input type="email" id="email" name="email" class="txt">
 <br>
 <label for="msg">Enter a Message</label>
 <textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
 </form>
</div>

Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method

<script type="text/javascript">
 $(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
 $("#email").removeClass("error");
 }

 if(msglen < 4) {
 $("#msg").addClass("error");
 }
 else if(msglen >= 4){
 $("#msg").removeClass("error");
 }

 if(mailvalid == true && msglen >= 4) {
 // if both validate we attempt to send the e-mail
 // first we hide the submit btn so the user doesnt click twice
 $("#send").replaceWith("<em>sending...</em>");
 //This will post it to the php page
 $.ajax({
 type: 'POST',
 url: 'sendmessage.php',
 data: $("#contact").serialize(),
 success: function(data) {
 if(data == "true") {
 $("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
 $(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
 setTimeout("$.fancybox.close()", 1000);
 });
 }
 }
 });
 }
 });
 });
</script>

You can add anything you want to do in your PHP file.

rebase in progress. Cannot commit. How to proceed or stop (abort)?

Mine was an error that popped up from BitBucket. Ran git am --skip fixed it.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

When you decorate a model property with [DataType(DataType.Date)] the default template in ASP.NET MVC 4 generates an input field of type="date":

<input class="text-box single-line" 
       data-val="true" 
       data-val-date="The field EstPurchaseDate must be a date."
       id="EstPurchaseDate" 
       name="EstPurchaseDate" 
       type="date" value="9/28/2012" />

Browsers that support HTML5 such Google Chrome render this input field with a date picker.

In order to correctly display the date, the value must be formatted as 2012-09-28. Quote from the specification:

value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.

You could enforce this format using the DisplayFormat attribute:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }

Encrypting & Decrypting a String in C#

using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}

Ajax LARAVEL 419 POST error

In your action you need first to load companies like so :

$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();

This will make the companies variable available in the view, and it should render the HTML correctly.

Try to use postman chrome extension to debug your view.

JavaScript dictionary with names

The main problem I see with what you have is that it's difficult to loop through, for populating a table.

Simply use an array of arrays:

var myMappings = [
    ["Name", "10%"], // Note the quotes around "10%"
    ["Phone", "10%"],
    // etc..
];

... which simplifies access:

myMappings[0][0]; // column name
myMappings[0][1]; // column width

Alternatively:

var myMappings = {
    names: ["Name", "Phone", etc...],
    widths: ["10%", "10%", etc...]
};

And access with:

myMappings.names[0];
myMappings.widths[0];