Programs & Examples On #Truthtable

A truth table is a mathematical table used in logic—specifically in connection with Boolean algebra, boolean functions, and propositional calculus—to compute the functional values of logical expressions on each of their functional arguments, that is, on each combination of values taken by their logical variables.

True and False for && logic and || Logic table

You probably mean a truth table for the boolean operators, which displays the result of the usual boolean operations (&&, ||). This table is not language-specific, but can be found e.g. here.

How to implement a ViewPager with different Fragments / Layouts

Create new instances in your fragments and do like so in your Activity

 private class SlidePagerAdapter extends FragmentStatePagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
            case 3:
                return Fragment4.newInstance();


            default: break;

        }
        return null;
    }

ListAGG in SQLSERVER

Starting in SQL Server 2017 the STRING_AGG function is available which simplifies the logic considerably:

select FieldA, string_agg(FieldB, '') as data
from yourtable
group by FieldA

See SQL Fiddle with Demo

In SQL Server you can use FOR XML PATH to get the result:

select distinct t1.FieldA,
  STUFF((SELECT distinct '' + t2.FieldB
         from yourtable t2
         where t1.FieldA = t2.FieldA
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') data
from yourtable t1;

See SQL Fiddle with Demo

.autocomplete is not a function Error

when you see this problem always put your autocomplete function in keyup function and ensure you have added the libraries

$( "#searcharea" ).keyup(function(){
   $( "#searcharea" ).autocomplete({
      source: "suggestions.php"
   });
});

Graph implementation C++

Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.

#include <iostream>
using namespace std;


// 1 ->2 
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;

// Structure of a vertex
struct vertex {
   int i;
   struct node *list;
   struct vertex *next;
};
typedef struct vertex * VPTR;

// Struct of adjacency list
struct node {
    struct vertex * n;
    struct node *next;
};

typedef struct node * NODEPTR;

class Graph {
    public:
        // list of nodes chained together
        VPTR V;
        Graph() {
            V = NULL;
        }
        void addEdge(int, int);
        VPTR  addVertex(int);
        VPTR existVertex(int i);
        void listVertex();
};

// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
    VPTR temp  = V;
    while(temp != NULL) {
        if(temp->i == i) {
            return temp;
        }
        temp = temp->next;
    }
   return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
    VPTR temp = new(struct vertex);
    temp->list = NULL;
    temp->i = i;
    temp->next = NULL;

    VPTR *curr = &V;
    while(*curr) {
        curr = &(*curr)->next;
    }
    *curr = temp;
    return temp;
}

// Add a node from vertex i to j. 
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {

    VPTR v_i = existVertex(i);   
    VPTR v_j = existVertex(j);   
    if(v_i == NULL) {
        v_i = addVertex(i);
    }
    if(v_j == NULL) {
        v_j = addVertex(j);
    }

    NODEPTR *temp = &(v_i->list);
    while(*temp) {
        temp = &(*temp)->next;
    }
    *temp = new(struct node);
    (*temp)->n = v_j;
    (*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
    VPTR temp = V;
    while(temp) {
        cout <<temp->i <<" ";
        temp = temp->next;
    }
    cout <<"\n";

}

// Client program
int main() {
    Graph G;
    G.addEdge(1, 2);
    G.listVertex();

}

With the above code, you can expand to do DFS/BFS etc.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

In AndroidManifest.xml:

<application
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:name="com..."
    android:theme="@style/Theme">...</Application>

In styles.xml: (See android:icon)

<style name="Theme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<style name="ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:icon">@drawable/icon</item>
</style>

How do I make case-insensitive queries on Mongodb?

To find case Insensitive string use this,

var thename = "Andrew";
db.collection.find({"name":/^thename$/i})

Do Java arrays have a maximum size?

I tried to create a byte array like this

byte[] bytes = new byte[Integer.MAX_VALUE-x];
System.out.println(bytes.length);

With this run configuration:

-Xms4G -Xmx4G

And java version:

Openjdk version "1.8.0_141"

OpenJDK Runtime Environment (build 1.8.0_141-b16)

OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)

It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2

Values above that give

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

How to force a list to be vertical using html css

CSS

li {
   display: inline-block;
}

Works for me also.

Normalize columns of pandas data frame

one easy way by using Pandas: (here I want to use mean normalization)

normalized_df=(df-df.mean())/df.std()

to use min-max normalization:

normalized_df=(df-df.min())/(df.max()-df.min())

Edit: To address some concerns, need to say that Pandas automatically applies colomn-wise function in the code above.

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

Steps to debug:-

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

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

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

if getting NotReady state error, verify network pod logs.

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

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

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

  3. ssh to that node

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

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

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

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

  1. systemctl daemon-reload
  2. systemctl restart kubelet

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

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

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

How to implement swipe gestures for mobile devices?

NOTE: Greatly inspired by EscapeNetscape's answer, I've made an edit of his script using modern javascript in a comment. I made an answer of this due to user interest and a massive 4h jsfiddle.net downtime. I chose not to edit the original answer since it would change everything...


Here is a detectSwipe function, working pretty well (used on one of my websites). I'd suggest you read it before you use it. Feel free to review it/edit the answer.

_x000D_
_x000D_
// usage example_x000D_
detectSwipe('swipeme', (el, dir) => alert(`you swiped on element with id ${el.id} to ${dir} direction`))_x000D_
_x000D_
// source code_x000D_
_x000D_
// Tune deltaMin according to your needs. Near 0 it will almost_x000D_
// always trigger, with a big value it can never trigger._x000D_
function detectSwipe(id, func, deltaMin = 90) {_x000D_
  const swipe_det = {_x000D_
    sX: 0,_x000D_
    sY: 0,_x000D_
    eX: 0,_x000D_
    eY: 0_x000D_
  }_x000D_
  // Directions enumeration_x000D_
  const directions = Object.freeze({_x000D_
    UP: 'up',_x000D_
    DOWN: 'down',_x000D_
    RIGHT: 'right',_x000D_
    LEFT: 'left'_x000D_
  })_x000D_
  let direction = null_x000D_
  const el = document.getElementById(id)_x000D_
  el.addEventListener('touchstart', function(e) {_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.sX = t.screenX_x000D_
    swipe_det.sY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchmove', function(e) {_x000D_
    // Prevent default will stop user from scrolling, use with care_x000D_
    // e.preventDefault();_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.eX = t.screenX_x000D_
    swipe_det.eY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchend', function(e) {_x000D_
    const deltaX = swipe_det.eX - swipe_det.sX_x000D_
    const deltaY = swipe_det.eY - swipe_det.sY_x000D_
    // Min swipe distance, you could use absolute value rather_x000D_
    // than square. It just felt better for personnal use_x000D_
    if (deltaX ** 2 + deltaY ** 2 < deltaMin ** 2) return_x000D_
    // horizontal_x000D_
    if (deltaY === 0 || Math.abs(deltaX / deltaY) > 1)_x000D_
      direction = deltaX > 0 ? directions.RIGHT : directions.LEFT_x000D_
    else // vertical_x000D_
      direction = deltaY > 0 ? directions.UP : directions.DOWN_x000D_
_x000D_
    if (direction && typeof func === 'function') func(el, direction)_x000D_
_x000D_
    direction = null_x000D_
  }, false)_x000D_
}
_x000D_
#swipeme {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: orange;_x000D_
  color: black;_x000D_
  text-align: center;_x000D_
  padding-top: 20%;_x000D_
  padding-bottom: 20%;_x000D_
}
_x000D_
<div id='swipeme'>_x000D_
  swipe me_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android: How to bind spinner to custom object list?

Just a small tweak to Joaquin Alberto's answer can solve the style issue.Just replace the getDropDownView function in the custom adapter as below,

@Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        View v = super.getDropDownView(position, convertView, parent);
        TextView tv = ((TextView) v);
        tv.setText(values[position].getName());
        tv.setTextColor(Color.BLACK);
        return v;
    }

Test if numpy array contains only zeros

This will work.

def check(arr):
    if np.all(arr == 0):
        return True
    return False

USB Debugging option greyed out

Unplug your phone from the PC and go to develop options and now here you can enable USB debugging. if you connect USB and try to enable debugging it will not enable and follow TMacGyver is right it works for me using choose PC connection.

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Retrieve version from maven pom.xml in code

Assuming you're using Java, you can:

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

  2. Set the value of some property in your .properties file using the standard Maven property for project version:

    foo.bar=${project.version}
    
  3. In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters).

  4. In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>   
    </build>
    

You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.

How to scroll to an element in jQuery?

You can extend jQuery functionalities like this:

jQuery.fn.extend({
scrollToMe: function () {
    var x = jQuery(this).offset().top - 100;
    jQuery('html,body').animate({scrollTop: x}, 500);
}});

and then:

$('...').scrollToMe();

easy ;-)

Bash Script : what does #!/bin/bash mean?

That is called a shebang, it tells the shell what program to interpret the script with, when executed.

In your example, the script is to be interpreted and run by the bash shell.

Some other example shebangs are:

(From Wikipedia)

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby

and a few additional ones I can think off the top of my head, such as:

#!/bin/ksh
#!/bin/awk
#!/bin/expect

In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.

Response to updated portion:

It depends on what /bin/sh actually points to on your system. Often it is just a symlink to /bin/bash. Sometimes portable scripts are written with #!/bin/sh just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh on that particular system (maybe it points to /bin/bash, /bin/ksh or /bin/zsh)

Remove title in Toolbar in appcompat-v7

getSupportActionBar().setDisplayShowTitleEnabled(false);

Adding 30 minutes to time formatted as H:i in PHP

$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));

Make an image width 100% of parent div, but not bigger than its own width

Just specify max-width: 100% alone, that should do it.

Presenting modal in iOS 13 fullscreen

Latest for iOS 13 and Swift 5.x

let vc = ViewController(nibName: "ViewController", bundle: nil)

vc.modalPresentationStyle = .fullScreen

self.present(vc, animated: true, completion: nil)

How to redirect 'print' output to a file using python?

Don't use print, use logging

You can change sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using print, use the logging module.

With logging, you can print just like you would to stdout, or you can also write the output to a file. You can even use the different message levels (critical, error, warning, info, debug) to, for example, only print major issues to the console, but still log minor code actions to a file.

A simple example

Import logging, get the logger, and set the processing level:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed

If you want to print to stdout:

ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # or any other level
logger.addHandler(ch)

If you want to also write to a file (if you only want to write to a file skip the last section):

fh = logging.FileHandler('myLog.log')
fh.setLevel(logging.DEBUG) # or any level you want
logger.addHandler(fh)

Then, wherever you would use print use one of the logger methods:

# print(foo)
logger.debug(foo)

# print('finishing processing')
logger.info('finishing processing')

# print('Something may be wrong')
logger.warning('Something may be wrong')

# print('Something is going really bad')
logger.error('Something is going really bad')

To learn more about using more advanced logging features, read the excellent logging tutorial in the Python docs.

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

Most efficient way to concatenate strings in JavaScript?

You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.

for (var res = '', i = 0; i < data.length; i++) {
  res = `${res}${data[i]}`;
}

Make the current commit the only (initial) commit in a Git repository?

git filter-branch is the major-surgery tool.

git filter-branch --parent-filter true -- @^!

--parent-filter gets the parents on stdin and should print the rewritten parents on stdout; unix true exits successfully and prints nothing, so: no parents. @^! is Git shorthand for "the head commit but not any of its parents". Then delete all the other refs and push at leisure.

Autocompletion in Vim

Try YouCompleteMe. It uses Clang through the libclang interface, offering semantic C/C++/Objective-C completion. It's much like clang_complete, but substantially faster and with fuzzy-matching.

In addition to the above, YCM also provides semantic completion for C#, Python, Go, TypeScript etc. It also provides non-semantic, identifier-based completion for languages for which it doesn't have semantic support.

Parsing HTTP Response in Python

You can also use python's requests library instead.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

Now you can manipulate the "dict" like a python dictionary.

Regex to extract substring, returning 2 results for some reason

Just get rid of the parenthesis and that will give you an array with one element and:

  • Change this line

var test = tesst.match(/a(.*)j/);

  • To this

var test = tesst.match(/a.*j/);

If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis

  • Also according to developer.mozilla.org docs :

If you only want the first match found, you might want to use RegExp.exec() instead.

You can use the below code:

RegExp(/a.*j/).exec("afskfsd33j")

C# - Multiple generic types in one list

public abstract class Metadata
{
}

// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
    private DataType mDataType;
}

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

Codeigniter displays a blank page instead of error messages

Just for anyone who is still looking for answers:

$db['default']['dbdriver'] = 'mysqli'; (make sure you use mysqli, not mysql). (database.php)

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I know this is a very old question, but this worked for me:

UPDATE TABLE SET FIELD1 =
CASE 
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;

Regards

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

mvn command is not recognized as an internal or external command

I had the same problem. But just restarting my computer after setting up the Maven path resolved the issue.

Variable Name: M2_Home Variable Value:C:\Apache\apache-maven-3.3.9

Variable Name: Path Variable Value:C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%JAVA_HOME%\bin\;%M2_HOME%\bin\

Declare global variables in Visual Studio 2010 and VB.NET

Make it static (shared in VB).

Public Class Form1

   Public Shared SomeValue As Integer = 5

End Class

How can I make git show a list of the files that are being tracked?

The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use

git ls-tree --full-tree --name-only -r HEAD
  • --full-tree makes the command run as if you were in the repo's root directory.
  • -r recurses into subdirectories. Combined with --full-tree, this gives you all committed, tracked files.
  • --name-only removes SHA / permission info for when you just want the file paths.
  • HEAD specifies which branch you want the list of tracked, committed files for. You could change this to master or any other branch name, but HEAD is the commit you have checked out right now.

This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.

Using Excel as front end to Access database (with VBA)

It's quite easy and efficient to use Excel as a reporting tool for Access data. A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:

strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection  
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst

That's it !

How to set TextView textStyle such as bold, italic

One way you can do is :

myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);

Another option if you want to keep the previous typeface and don't want to lose previously applied then:

myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);        
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); 

How do I sort arrays using vbscript?

You either have to write your own sort by hand, or maybe try this technique:

http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83

You can freely intermix server side javascript with VBScript, so wherever VBScript falls short, switch to javascript.

Copy a git repo without history

Deleting the .git folder is probably the easiest path since you don't want/need the history (as Stephan said).

So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)

git clone <git_url>

then delete .git, and afterwards run

git init

Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?

Follow the above steps then:

git add .
git commit -m "Initial commit"

Push to your repo.

git remote add origin <github-uri>
git push -u --force origin master

The total number of locks exceeds the lock table size

It is worth saying that the figure used for this setting is in BYTES - found that out the hard way!

Python function overloading

Overloading methods is tricky in Python. However, there could be usage of passing the dict, list or primitive variables.

I have tried something for my use cases, and this could help here to understand people to overload the methods.

Let's take your example:

A class overload method with call the methods from different class.

def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):

Pass the arguments from the remote class:

add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}

Or

add_bullet(sprite = 'test', start=Yes, headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}

So, handling is being achieved for list, Dictionary or primitive variables from method overloading.

Try it out for your code.

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

Detect element content changes with jQuery

Try to bind to the DOMSubtreeModified event seeign as test is also just part of the DOM.

see this post here on SO:

how-do-i-monitor-the-dom-for-changes

How to find the installed pandas version

Check pandas.__version__:

In [76]: import pandas as pd

In [77]: pd.__version__
Out[77]: '0.12.0-933-g281dc4e'

Pandas also provides a utility function, pd.show_versions(), which reports the version of its dependencies as well:

In [53]: pd.show_versions(as_json=False)

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.6.final.0
python-bits: 64
OS: Linux
OS-release: 3.13.0-45-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

pandas: 0.15.2-113-g5531341
nose: 1.3.1
Cython: 0.21.1
numpy: 1.8.2
scipy: 0.14.0.dev-371b4ff
statsmodels: 0.6.0.dev-a738b4f
IPython: 2.0.0-dev
sphinx: 1.2.2
patsy: 0.3.0
dateutil: 1.5
pytz: 2012c
bottleneck: None
tables: 3.1.1
numexpr: 2.2.2
matplotlib: 1.4.2
openpyxl: None
xlrd: 0.9.3
xlwt: 0.7.5
xlsxwriter: None
lxml: 3.3.3
bs4: 4.3.2
html5lib: 0.999
httplib2: 0.8
apiclient: None
rpy2: 2.5.5
sqlalchemy: 0.9.8
pymysql: None
psycopg2: 2.4.5 (dt dec mx pq3 ext)

Creating a div element in jQuery

Create an in-memory DIV

$("<div/>");

Add click handlers, styles etc - and finally insert into DOM into a target element selector:

_x000D_
_x000D_
$("<div/>", {_x000D_
_x000D_
  // PROPERTIES HERE_x000D_
  _x000D_
  text: "Click me",_x000D_
  id: "example",_x000D_
  "class": "myDiv",      // ('class' is still better in quotes)_x000D_
  css: {           _x000D_
    color: "red",_x000D_
    fontSize: "3em",_x000D_
    cursor: "pointer"_x000D_
  },_x000D_
  on: {_x000D_
    mouseenter: function() {_x000D_
      console.log("PLEASE... "+ $(this).text());_x000D_
    },_x000D_
    click: function() {_x000D_
      console.log("Hy! My ID is: "+ this.id);_x000D_
    }_x000D_
  },_x000D_
  append: "<i>!!</i>",_x000D_
  appendTo: "body"      // Finally, append to any selector_x000D_
  _x000D_
}); // << no need to do anything here as we defined the properties internally.
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

The problem is that you are calling ToString in a LINQ to Entities query. That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).

All you have to do is move the ToString call to a separate line:

var keyString = item.Key.ToString();

var pages = from p in context.entities
            where p.Serial == keyString
            select p;

How can I disable a button on a jQuery UI dialog?

If you're including the .button() plugin/widget that jQuery UI contains (if you have the full library and are on 1.8+, you have it), you can use it to disable the button and update the state visually, like this:

$(".ui-dialog-buttonpane button:contains('Confirm')").button("disable");

You can give it a try here...or if you're on an older version or not using the button widget, you can disable it like this:

$(".ui-dialog-buttonpane button:contains('Confirm')").attr("disabled", true)
                                              .addClass("ui-state-disabled");

If you want it inside a specific dialog, say by ID, then do this:

$("#dialogID").next(".ui-dialog-buttonpane button:contains('Confirm')")
              .attr("disabled", true);

In other cases where :contains() might give false positives then you can use .filter() like this, but it's overkill here since you know your two buttons. If that is the case in other situations, it'd look like this:

$("#dialogID").next(".ui-dialog-buttonpane button").filter(function() {
  return $(this).text() == "Confirm";
}).attr("disabled", true);

This would prevent :contains() from matching a substring of something else.

Git diff says subproject is dirty

A submodule may be marked as dirty if filemode settings is enabled and you changed file permissions in submodule subtree.

To disable filemode in a submodule, you can edit /.git/modules/path/to/your/submodule/config and add

[core]
  filemode = false

If you want to ignore all dirty states, you can either set ignore = dirty property in /.gitmodules file, but I think it's better to only disable filemode.

Getting the IP address of the current machine using Java

import java.net.DatagramSocket;
import java.net.InetAddress;

try(final DatagramSocket socket = new DatagramSocket()){
  socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
  ip = socket.getLocalAddress().getHostAddress();
}

This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8 is not needed to be reachable.

Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.

So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.

Edit:

As @macomgil says, for MacOS you can do this:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());

Interview question: Check if one string is a rotation of other string

Surely a better answer would be, "Well, I'd ask the stackoverflow community and would probably have at least 4 really good answers within 5 minutes". Brains are good and all, but I'd place a higher value on someone who knows how to work with others to get a solution.

Wait until boolean value changes it state

You need a mechanism which avoids busy-waiting. The old wait/notify mechanism is fraught with pitfalls so prefer something from the java.util.concurrent library, for example the CountDownLatch:

public final CountDownLatch latch = new CountDownLatch(1);

public void run () {
  latch.await();
  ...
}

And at the other side call

yourRunnableObj.latch.countDown();

However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService to which you submit as a task the work which must be done when the condition is met.

What does ||= (or-equals) mean in Ruby?

It means or-equals to. It checks to see if the value on the left is defined, then use that. If it's not, use the value on the right. You can use it in Rails to cache instance variables in models.

A quick Rails-based example, where we create a function to fetch the currently logged in user:

class User > ActiveRecord::Base

  def current_user
    @current_user ||= User.find_by_id(session[:user_id])
  end

end

It checks to see if the @current_user instance variable is set. If it is, it will return it, thereby saving a database call. If it's not set however, we make the call and then set the @current_user variable to that. It's a really simple caching technique but is great for when you're fetching the same instance variable across the application multiple times.

How do I convert a calendar week into a date in Excel?

If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:

=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5

the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.

ASP.NET email validator regex

For regex, I first look at this web site: RegExLib.com

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Get first element from a dictionary

EDIT: Use an OrderedDictionary.

It's better to use FirstOrDefault() to retrieve the first value.

Ex:

var firstElement = like.FirstOrDefault();
string firstElementKey = firstElement.Key;
Dictinary<string,string> firstElementValue = firstElement.Value;

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

OR, AND Operator

There is a distinction between the conditional operators && and || and the boolean operators & and |. Mainly it is a difference of precendence (which operators get evaluated first) and also the && and || are 'escaping'. This means that is a sequence such as...

cond1 && cond2 && cond3

If cond1 is false, neither cond2 or cond3 are evaluated as the code rightly assumes that no matter what their value, the expression cannot be true. Likewise...

cond1 || cond2 || cond3

If cond1 is true, neither cond2 or cond3 are evaluated as the expression must be true no matter what their value is.

The bitwise counterparts, & and | are not escaping.

Hope that helps.

How to read a string one letter at a time in python

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

Lombok is not generating getter and setter

Download Lombok Jar, let’s maven do the download on our behalf :

 <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
    </dependency>

Now... mvn clean install command on the newly created project to get this jar downloaded in local repository. Goto the jar location, execute the command prompt, run the command : java -jar lombok-1.16.18.jar

enter image description here

click on the “Specify Location” button and locate the eclipse.exe path LIKE : enter image description here

finally install this by clicking the “Install/Update”

Add colorbar to existing axis

This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)

im = ax.imshow(data, cmap='bone')

fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Image with proper colorbar in size

How to get the size of a JavaScript object?

I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:

Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

no suitable HttpMessageConverter found for response type

This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

In Spring 4.0.9, we were able to send this

    JSONObject jsonCredential = new JSONObject();
    jsonCredential.put(APPLICATION_CREDENTIALS, data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);

In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

The way Convertors work is that if you have it in your classpath, they get registered.

Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

Once we added I could see the converter being registered.

enter image description here

How to get the selected date value while using Bootstrap Datepicker?

Generally speaking,

$('#startdate').data('date') 

is best because

$('#startdate').val()

not work if you have a datepicker "inline"

Setting onClickListener for the Drawable right of an EditText

This has been already answered but I tried a different way to make it simpler.

The idea is using putting an ImageButton on the right of EditText and having negative margin to it so that the EditText flows into the ImageButton making it look like the Button is in the EditText.

enter image description here

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Pin"
            android:singleLine="true"
            android:textSize="25sp"
            android:paddingRight="60dp"
            />
        <ImageButton
            android:id="@+id/pastePin"
            android:layout_marginLeft="-60dp"
            style="?android:buttonBarButtonStyle"
            android:paddingBottom="5dp"
            android:src="@drawable/ic_action_paste"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

Also, as shown above, you can use a paddingRight of similar width in the EditText if you don't want the text in it to be flown over the ImageButton.

I guessed margin size with the help of android-studio's layout designer and it looks similar across all screen sizes. Or else you can calculate the width of the ImageButton and set the margin programatically.

T-SQL Format integer to 2-digit string

DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

Best Practice: Software Versioning

Yet another example for the A.B.C approach is the Eclipse Bundle Versioning. Eclipse bundles rather have a fourth segment:

In Eclipse, version numbers are composed of four (4) segments: 3 integers and a string respectively named major.minor.service.qualifier. Each segment captures a different intent:

  • the major segment indicates breakage in the API
  • the minor segment indicates "externally visible" changes
  • the service segment indicates bug fixes and the change of development stream
  • the qualifier segment indicates a particular build

What is the optimal algorithm for the game 2048?

I developed a 2048 AI using expectimax optimization, instead of the minimax search used by @ovolve's algorithm. The AI simply performs maximization over all possible moves, followed by expectation over all possible tile spawns (weighted by the probability of the tiles, i.e. 10% for a 4 and 90% for a 2). As far as I'm aware, it is not possible to prune expectimax optimization (except to remove branches that are exceedingly unlikely), and so the algorithm used is a carefully optimized brute force search.

Performance

The AI in its default configuration (max search depth of 8) takes anywhere from 10ms to 200ms to execute a move, depending on the complexity of the board position. In testing, the AI achieves an average move rate of 5-10 moves per second over the course of an entire game. If the search depth is limited to 6 moves, the AI can easily execute 20+ moves per second, which makes for some interesting watching.

To assess the score performance of the AI, I ran the AI 100 times (connected to the browser game via remote control). For each tile, here are the proportions of games in which that tile was achieved at least once:

2048: 100%
4096: 100%
8192: 100%
16384: 94%
32768: 36%

The minimum score over all runs was 124024; the maximum score achieved was 794076. The median score is 387222. The AI never failed to obtain the 2048 tile (so it never lost the game even once in 100 games); in fact, it achieved the 8192 tile at least once in every run!

Here's the screenshot of the best run:

32768 tile, score 794076

This game took 27830 moves over 96 minutes, or an average of 4.8 moves per second.

Implementation

My approach encodes the entire board (16 entries) as a single 64-bit integer (where tiles are the nybbles, i.e. 4-bit chunks). On a 64-bit machine, this enables the entire board to be passed around in a single machine register.

Bit shift operations are used to extract individual rows and columns. A single row or column is a 16-bit quantity, so a table of size 65536 can encode transformations which operate on a single row or column. For example, moves are implemented as 4 lookups into a precomputed "move effect table" which describes how each move affects a single row or column (for example, the "move right" table contains the entry "1122 -> 0023" describing how the row [2,2,4,4] becomes the row [0,0,4,8] when moved to the right).

Scoring is also done using table lookup. The tables contain heuristic scores computed on all possible rows/columns, and the resultant score for a board is simply the sum of the table values across each row and column.

This board representation, along with the table lookup approach for movement and scoring, allows the AI to search a huge number of game states in a short period of time (over 10,000,000 game states per second on one core of my mid-2011 laptop).

The expectimax search itself is coded as a recursive search which alternates between "expectation" steps (testing all possible tile spawn locations and values, and weighting their optimized scores by the probability of each possibility), and "maximization" steps (testing all possible moves and selecting the one with the best score). The tree search terminates when it sees a previously-seen position (using a transposition table), when it reaches a predefined depth limit, or when it reaches a board state that is highly unlikely (e.g. it was reached by getting 6 "4" tiles in a row from the starting position). The typical search depth is 4-8 moves.

Heuristics

Several heuristics are used to direct the optimization algorithm towards favorable positions. The precise choice of heuristic has a huge effect on the performance of the algorithm. The various heuristics are weighted and combined into a positional score, which determines how "good" a given board position is. The optimization search will then aim to maximize the average score of all possible board positions. The actual score, as shown by the game, is not used to calculate the board score, since it is too heavily weighted in favor of merging tiles (when delayed merging could produce a large benefit).

Initially, I used two very simple heuristics, granting "bonuses" for open squares and for having large values on the edge. These heuristics performed pretty well, frequently achieving 16384 but never getting to 32768.

Petr Morávek (@xificurk) took my AI and added two new heuristics. The first heuristic was a penalty for having non-monotonic rows and columns which increased as the ranks increased, ensuring that non-monotonic rows of small numbers would not strongly affect the score, but non-monotonic rows of large numbers hurt the score substantially. The second heuristic counted the number of potential merges (adjacent equal values) in addition to open spaces. These two heuristics served to push the algorithm towards monotonic boards (which are easier to merge), and towards board positions with lots of merges (encouraging it to align merges where possible for greater effect).

Furthermore, Petr also optimized the heuristic weights using a "meta-optimization" strategy (using an algorithm called CMA-ES), where the weights themselves were adjusted to obtain the highest possible average score.

The effect of these changes are extremely significant. The algorithm went from achieving the 16384 tile around 13% of the time to achieving it over 90% of the time, and the algorithm began to achieve 32768 over 1/3 of the time (whereas the old heuristics never once produced a 32768 tile).

I believe there's still room for improvement on the heuristics. This algorithm definitely isn't yet "optimal", but I feel like it's getting pretty close.


That the AI achieves the 32768 tile in over a third of its games is a huge milestone; I will be surprised to hear if any human players have achieved 32768 on the official game (i.e. without using tools like savestates or undo). I think the 65536 tile is within reach!

You can try the AI for yourself. The code is available at https://github.com/nneonneo/2048-ai.

Application Installation Failed in Android Studio

Go to USB Debugging and disable MIUI Inspection and allow the phone to reboot. Things should be fine from here

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio Code is an editor while Visual Studio is an IDE.

Visual Studio Code is cross-platform and fast, while Visual Studio is not fast.

Note that Visual Studio for Mac is available now but is a different product compared to Visual Studio (Windows). It's based on Xamarin Studio and lacks support for some older .NET project types. It does successfully build solutions created in Visual Studio 2017. Visual Studio for Mac has a more limited UI (for example, no customizable toolbar). So for cross-platform work, Visual Studio Code may still be preferable.

How can I zoom an HTML element in Firefox and Opera?

Use scale instead! After many researches and tests I have made this plugin to achieve it cross browser:

$.fn.scale = function(x) {
    if(!$(this).filter(':visible').length && x!=1)return $(this);
    if(!$(this).parent().hasClass('scaleContainer')){
        $(this).wrap($('<div class="scaleContainer">').css('position','relative'));
        $(this).data({
            'originalWidth':$(this).width(),
            'originalHeight':$(this).height()});
    }
    $(this).css({
        'transform': 'scale('+x+')',
        '-ms-transform': 'scale('+x+')',
        '-moz-transform': 'scale('+x+')',
        '-webkit-transform': 'scale('+x+')',
        'transform-origin': 'right bottom',
        '-ms-transform-origin': 'right bottom',
        '-moz-transform-origin': 'right bottom',
        '-webkit-transform-origin': 'right bottom',
        'position': 'absolute',
        'bottom': '0',
        'right': '0',
    });
    if(x==1)
        $(this).unwrap().css('position','static');else
            $(this).parent()
                .width($(this).data('originalWidth')*x)
                .height($(this).data('originalHeight')*x);
    return $(this);
};

usege:

$(selector).scale(0.5);

note:

It will create a wrapper with a class scaleContainer. Take care of that while styling content.

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

for more extendability for large scale apps use oop style with encapsulated fields.

Simple way :-

  class Fruit implements JsonSerializable {

        private $type = 'Apple', $lastEaten = null;

        public function __construct() {
            $this->lastEaten = new DateTime();
        }

        public function jsonSerialize() {
            return [
                'category' => $this->type,
                'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
            ];
        }
    }

echo json_encode(new Fruit()); //which outputs:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}

Real Gson on PHP :-

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serialize only

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

From the Tools menu, click on Options, select Designers from the side menu and untick prevent changes that can lead to recreation of a table. Then save the changes

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

Eclipse C++: Symbol 'std' could not be resolved

For MinGW this worked for me:

  • Right click project, select Properties
  • Go to C/C++ General - Paths and Symbols - Includes - GNU C++ - Include directories
  • Select Add...
  • Select Variables...
  • Select MINGW_HOME and click OK
  • Click Apply and OK

You should now see several MinGW paths in Includes in your project explorer.
The errors may not disappear instantly, you may need to refresh/build your project.


If you are using Cygwin, there could be an equivalent variable present.

Default parameters with C++ constructors

Matter of style, but as Matt said, definitely consider marking constructors with default arguments which would allow implicit conversion as 'explicit' to avoid unintended automatic conversion. It's not a requirement (and may not be preferable if you're making a wrapper class which you want to implicitly convert to), but it can prevent errors.

I personally like defaults when appropriate, because I dislike repeated code. YMMV.

How to scp in Python?

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

SOAP or REST for Web Services?

I'd recommend you go with REST first - if you're using Java look at JAX-RS and the Jersey implementation. REST is much simpler and easy to interop in many languages.

As others have said in this thread, the problem with SOAP is its complexity when the other WS-* specifications come in and there are countless interop issues if you stray into the wrong parts of WSDL, XSDs, SOAP, WS-Addressing etc.

The best way to judge the REST v SOAP debate is look on the internet - pretty much all the big players in the web space, google, amazon, ebay, twitter et al - tend to use and prefer RESTful APIs over the SOAP ones.

The other nice approach to going with REST is that you can reuse lots of code and infratructure between a web application and a REST front end. e.g. rendering HTML versus XML versus JSON of your resources is normally pretty easy with frameworks like JAX-RS and implicit views - plus its easy to work with RESTful resources using a web browser

Proper way to exit iPhone application?

Hm, you may 'have to' quit the application if, say, your application requires an internet connection. You could display an alert and then do something like this:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {
    [[UIApplication sharedApplication] performSelector:@selector(terminate)];
} else {
    kill(getpid(), SIGINT); 
}

How to add files/folders to .gitignore in IntelliJ IDEA?

You can create file .gitignore and then Idea will suggest you install plugin

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

What does status=canceled for a resource mean in Chrome Developer Tools?

For me 'canceled' status was because the file did not exist. Strange why chrome does not show 404.

How to make HTML element resizable using pure Javascript?

_x000D_
_x000D_
// import
function get_difference(pre, mou) {
  return {
    x: mou.x - pre.x,
    y: mou.y - pre.y
  };
}

/*
if your panel is in a nested environment, which the parent container's width and height does not equa to document width 
and height, for example, in an element `canvas`, then edit it to

function oMousePos(e) {
  var rc = canvas.getBoundingClientRect();
  return {
    x: e.clientX - rc.left,
    y: e.clientY - rc.top,
  };
}
*/

function oMousePos(e) {
  return {
    x: e.clientX,
    y: e.clientY,
  };
}

function render_element(styles, el) {
  for (const [kk, vv] of Object.entries(styles)) {
    el.style[kk] = vv;
  }
}

class MoveablePanel {

  /*
  prevent an element from moving out of window
  */
  constructor(container, draggable, left, top) {
    this.container = container;
    this.draggable = draggable;
    this.left = left;
    this.top = top;
    let rect = container.getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.status = false;

    // initial position of the panel, should not be changed
    this.original = {
      left: left,
      top: top
    };

    // current left and top postion
    // {this.left, this.top}

    // assign the panel to initial position
    // initalize in registration
    this.default();

    if (!MoveablePanel._instance) {
      MoveablePanel._instance = [];
    }
    MoveablePanel._instance.push(this);
  }

  mousedown(e) {
    this.status = true;
    this.previous = oMousePos(e)
  }

  mousemove(e) {
    if (!this.status) {
      return;
    }
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;
    let kleft, ktop;

    if (vleft < 0) {
      kleft = 0;
    } else if (vleft > window.innerWidth - this.width) {
      kleft = window.innerWidth - this.width;
    } else {
      kleft = vleft;
    }

    if (vtop < 0) {
      ktop = 0;
    } else if (vtop > window.innerHeight - this.height) {
      ktop = window.innerHeight - this.height;
    } else {
      ktop = vtop;
    }
    this.container.style.left = `${kleft}px`;
    this.container.style.top = `${ktop}px`;
  }

  /*
  sometimes user move the cursor too fast which mouseleave is previous than mouseup
  to prevent moving too fast and break the control, mouseleave is handled the same as mouseup
  */

  mouseupleave(e) {
    if (!this.status) {
      return null;
    }
    this.status = false;
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;

    if (vleft < 0) {
      this.left = 0;
    } else if (vleft > window.innerWidth - this.width) {
      this.left = window.innerWidth - this.width;
    } else {
      this.left = vleft;
    }

    if (vtop < 0) {
      this.top = 0;
    } else if (vtop > window.innerHeight - this.height) {
      this.top = window.innerHeight - this.height;
    } else {
      this.top = vtop;
    }

    this.show();
    return true;
  }

  default () {
    this.container.style.left = `${this.original.left}px`;
    this.container.style.top = `${this.original.top}px`;
  }

  /*
  panel with a higher z index will interupt drawing
  therefore if panel is not displaying, set it with a lower z index that canvas

  change index doesn't work, if panel is hiding, then we move it out
  hide: record current position, move panel out
  show: assign to recorded position

  notice this position has nothing to do panel drag movement
  they cannot share the same variable
  */

  hide() {
    // move to the right bottom conner
    this.container.style.left = `${window.screen.width}px`;
    this.container.style.top = `${window.screen.height}px`;
  }

  show() {
    this.container.style.left = `${this.left}px`;
    this.container.style.top = `${this.top}px`;
  }
}
// end of import

class DotButton{
    constructor(
        width_px, 
        styles, // mainly pos, padding and margin, e.g. {top: 0, left: 0, margin: 0},
        color, 
        color_hover,
        border, // boolean
        border_dismiss, // boolean: dismiss border when hover
    ){
        this.width = width_px;
        this.styles = styles;
        this.color = color;
        this.color_hover = color_hover;
        this.border = border;
        this.border_dismiss = border_dismiss;
    }

    create(_styles=null){
        var el = document.createElement('div');
        Object.keys(this.styles).forEach(kk=>{
            el.style[kk] = `${this.styles[kk]}px`;
        });
        if(_styles){
            Object.keys(_styles).forEach(kk=>{
                el.style[kk] = `${this.styles[kk]}px`;
            });
        }
        el.style.width = `${this.width}px`
        el.style.height = `${this.width}px`
        el.style.position = 'absolute';
        el.style.left = `${this.left_px}px`;
        el.style.top = `${this.top_px}px`;
        el.style.background = this.color;
        if(this.border){
            el.style.border = '1px solid'; 
        }
        el.style.borderRadius = `${this.width}px`;

        el.addEventListener('mouseenter', ()=>{
            el.style.background = this.color_hover;
            if(this.border_dismiss){
                el.style.border = `1px solid ${this.color_hover}`; 
            }
        });
        el.addEventListener('mouseleave', ()=>{
            el.style.background = this.color;
            if(this.border_dismiss){
                el.style.border = '1px solid'; 
            }
        });
        return el;
    }
}

function cursor_hover(el, default_cursor, to_cursor){
    el.addEventListener('mouseenter', function(){
        this.style.cursor = to_cursor;
    }.bind(el));


    el.addEventListener('mouseleave', function(){
        this.style.cursor = default_cursor;
    }.bind(el));
}

class FlexPanel extends MoveablePanel{
    constructor(
        parent_el,
        top_px,
        left_px,
        width_px, 
        height_px, 
        background,
        handle_width_px, 
        coner_vmin_ratio, 
        button_width_px, 
        button_margin_px, 
    ){
        super(
            (()=>{
                var el = document.createElement('div');
                render_element(
                    {
                        position: 'fixed', 
                        top: `${top_px}px`,
                        left: `${left_px}px`,
                        width: `${width_px}px`,
                        height: `${height_px}px`,
                        background: background, 
                    }, 
                    el,
                );
                return el;
            })(), // iife returns a container (panel el)
            new DotButton(button_width_px, {top: 0, right: 0, margin: button_margin_px}, 'green', 'lightgreen', false, false).create(), // draggable
            left_px, // left
            top_px, // top
        );

        this.draggable.addEventListener('mousedown', e => {
            e.preventDefault();
            this.mousedown(e);
        });

        this.draggable.addEventListener('mousemove', e => {
            e.preventDefault();
            this.mousemove(e);
        });

        this.draggable.addEventListener('mouseup', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.draggable.addEventListener('mouseleave', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.parent_el = parent_el;
        this.background = background;

        // parent
        this.width = width_px;
        this.height = height_px;

        this.handle_width_px = handle_width_px;
        this.coner_vmin_ratio = coner_vmin_ratio;

        this.panel_el = document.createElement('div');

        // styles that won't change 
        this.panel_el.style.position = 'absolute';
        this.panel_el.style.top = `${this.handle_width_px}px`;
        this.panel_el.style.left = `${this.handle_width_px}px`; 
        this.panel_el.style.background = this.background;
    
        this.handles = [
            this.handle_top,
            this.handle_left,
            this.handle_bottom,
            this.handle_right, 

            this.handle_lefttop,
            this.handle_topleft,
            this.handle_topright,
            this.handle_righttop, 
            this.handle_rightbottom, 
            this.handle_bottomright,
            this.handle_bottomleft,
            this.handle_leftbottom, 
        ] = Array.from({length: 12}, i => document.createElement('div'));

        this.handles.forEach(el=>{
            el.style.position = 'absolute';
        });

        this.handle_topleft.style.top = '0';
        this.handle_topleft.style.left = `${this.handle_width_px}px`;

        this.handle_righttop.style.right = '0';
        this.handle_righttop.style.top = `${this.handle_width_px}px`;

        this.handle_bottomright.style.bottom = '0';
        this.handle_bottomright.style.right = `${this.handle_width_px}px`;

        this.handle_leftbottom.style.left = '0';
        this.handle_leftbottom.style.bottom = `${this.handle_width_px}px`;


        this.handle_lefttop.style.left = '0';
        this.handle_lefttop.style.top = '0';

        this.handle_topright.style.top = '0';
        this.handle_topright.style.right = '0';

        this.handle_rightbottom.style.right = '0';
        this.handle_rightbottom.style.bottom = '0';

        this.handle_bottomleft.style.bottom = '0';
        this.handle_bottomleft.style.left = '0';

        this.update_ratio();

        [
            'ns-resize', // |
            'ew-resize', // -
            'ns-resize', // |
            'ew-resize', // -

            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
        ].map((dd, ii)=>{
            cursor_hover(this.handles[ii], 'default', dd);
        });

        this.vtop = this.top;
        this.vleft = this.left;
        this.vwidth = this.width;
        this.vheight = this.height;

        this.update_ratio();

        this.handles.forEach(el=>{
            this.container.appendChild(el);
        });

        cursor_hover(this.draggable, 'default', 'move');

        this.panel_el.appendChild(this.draggable);
        this.container.appendChild(this.panel_el);
        this.parent_el.appendChild(this.container);

        [
            this.edgemousedown, 
            this.verticalmousemove,
            this.horizontalmousemove,
            this.nwsemousemove,
            this.neswmousemove,
            this.edgemouseupleave,
        ] = [
            this.edgemousedown.bind(this),
            this.verticalmousemove.bind(this),
            this.horizontalmousemove.bind(this),
            this.nwsemousemove.bind(this),
            this.neswmousemove.bind(this),
            this.edgemouseupleave.bind(this),
        ];

        this.handle_top.addEventListener('mousedown', e=>{this.edgemousedown(e, 'top')});
        this.handle_left.addEventListener('mousedown', e=>{this.edgemousedown(e, 'left')});
        this.handle_bottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottom')});
        this.handle_right.addEventListener('mousedown', e=>{this.edgemousedown(e, 'right')}); 
        this.handle_lefttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'lefttop')});
        this.handle_topleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topleft')});
        this.handle_topright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topright')});
        this.handle_righttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'righttop')}); 
        this.handle_rightbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'rightbottom')}); 
        this.handle_bottomright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomright')});
        this.handle_bottomleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomleft')});
        this.handle_leftbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'leftbottom')});

        this.handle_top.addEventListener('mousemove', this.verticalmousemove);
        this.handle_left.addEventListener('mousemove', this.horizontalmousemove);
        this.handle_bottom.addEventListener('mousemove', this.verticalmousemove);
        this.handle_right.addEventListener('mousemove', this.horizontalmousemove); 
        this.handle_lefttop.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topleft.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topright.addEventListener('mousemove', this.neswmousemove);
        this.handle_righttop.addEventListener('mousemove', this.neswmousemove); 
        this.handle_rightbottom.addEventListener('mousemove', this.nwsemousemove); 
        this.handle_bottomright.addEventListener('mousemove', this.nwsemousemove);
        this.handle_bottomleft.addEventListener('mousemove', this.neswmousemove);
        this.handle_leftbottom.addEventListener('mousemove', this.neswmousemove);

        this.handle_top.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_left.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()});
        this.handle_bottom.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_right.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()}); 
        this.handle_lefttop.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topleft.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topright.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_righttop.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()}); 
        this.handle_rightbottom.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()}); 
        this.handle_bottomright.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_bottomleft.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_leftbottom.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
    
        this.handle_top.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_left.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_right.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_lefttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_righttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_rightbottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_leftbottom.addEventListener('mouseleave', this.edgemouseupleave);
    }

    // box size change triggers corner handler size change
    update_ratio(){
        this.container.style.top = `${this.vtop}px`;
        this.container.style.left = `${this.vleft}px`;
        this.container.style.width = `${this.vwidth}px`;
        this.container.style.height = `${this.vheight}px`;

        this.panel_el.style.width = `${this.vwidth - 2 * this.handle_width_px}px`;
        this.panel_el.style.height = `${this.vheight - 2 * this.handle_width_px}px`;

        this.ratio = this.vwidth < this.vheight ? this.coner_vmin_ratio * this.vwidth : this.coner_vmin_ratio * this.vheight;
        [
            this.handle_top,
            this.handle_bottom, 
        ].forEach(el=>{
            el.style.width = `${this.vwidth - 2 * this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_left,
            this.handle_right, 
        ].forEach(el=>{
            el.style.height = `${this.vheight - 2 * this.ratio}px`;
            el.style.width = `${this.handle_width_px}px`;
        });

        this.handle_top.style.top = `0`;
        this.handle_top.style.left = `${this.ratio}px`;

        this.handle_left.style.top = `${this.ratio}px`;
        this.handle_left.style.left = `0`;

        this.handle_bottom.style.bottom = `0`;
        this.handle_bottom.style.right = `${this.ratio}px`;

        this.handle_right.style.bottom = `${this.ratio}px`;
        this.handle_right.style.right = `0`;

        [
            this.handle_topright,
            this.handle_bottomleft,
        ].forEach(el=>{
            el.style.width = `${this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_lefttop,
            this.handle_rightbottom,
        ].forEach(el=>{
            el.style.width = `${this.handle_width_px}px`;
            el.style.height = `${this.ratio}px`;
        });

        [
            this.handle_topleft,
            this.handle_bottomright,
        ].forEach(el=>{
            el.style.width = `${this.ratio - this.handle_width_px}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_righttop,
            this.handle_leftbottom,
        ].forEach(el=>{
            el.style.height = `${this.handle_width_px}px`;
            el.style.width = `${this.ratio - this.handle_width_px}px`;
        });
    }

    edgemousedown(e, flag){
        this.previous = oMousePos(e);
        this.flag = flag;
        this.drag = true;
    }

    verticalmousemove(e){
        if(this.drag){
            // -
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            switch(this.flag){
                case 'top':
                    this.vtop = this.top + ydif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;

                case 'bottom':
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;
            }
            this.update_ratio();
        }
    }

    horizontalmousemove(e){
        if(this.drag){
            // |
            this.mouse = oMousePos(e);
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'left':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;

                    this.vtop = this.top;
                    this.vheight = this.height;
                break;

                case 'right':
                    this.vwidth = this.width + xdif;
                
                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vheight = this.height;
                break;
            }
            this.update_ratio();
        }
    }

    nwsemousemove(e){
        if(this.drag){
            // \
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topleft':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'lefttop':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'bottomright':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;

                case 'rightbottom':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;
            }
            this.update_ratio();
        }
    }

    neswmousemove(e){
        if(this.drag){
            // /
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topright':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'righttop':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'bottomleft':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;

                case 'leftbottom':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;
            }
            this.update_ratio();
        }
    }

    edgemouseupleave(){
        this.drag = false;
        this.top = this.vtop;
        this.left = this.vleft;
        this.width = this.vwidth;
        this.height = this.vheight;
    }

    mouseupleave(e){
        if(super.mouseupleave(e)){
            this.vtop = this.top;
            this.vleft = this.left;         
        }
    }
}


var fp = new FlexPanel(
    document.body, // parent div container
    20, // top margin
    20, // left margin
    200, // width 
    150, // height
    'lightgrey', // background
    20, // handle height when horizontal; handle width when vertical
    0.2, // edge up and left resize bar width : top resize bar width = 1 : 5
    35, // green move button width and height
    2, // button margin
);

/*
this method creates an element for you
which you don't need to pass in a selected element

to manipuate dom element
fp.container -> entire panel
fp.panel_el -> inside panel
*/
_x000D_
_x000D_
_x000D_

Achieving functionalities fully requires a lot of hard coding. Please refer to the documentation, it will show you how to use each class as element.

PHP to search within txt file and echo the whole line

$searchfor = $_GET['keyword'];
$file = 'users.txt';

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if (preg_match_all($pattern, $contents, $matches)) {
    echo "Found matches:<br />";
    echo implode("<br />", $matches[0]);
} else {
    echo "No matches found";
    fclose ($file); 
}

Centering image and text in R Markdown for a PDF report

There is now a much better solution, a lot more elegant, based on fenced div, which have been implemented in pandoc, as explained here:

::: {.center data-latex=""}
Some text here...
:::

All you need to do is to change your css file accordingly. The following chunk for instance does the job:

```{cat, engine.opts = list(file = "style.css")}
.center {
  text-align: center;
}
``` 

(Obviously, you can also directly type the content of the chunk into your .css file...).
The tex file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!") does not bold for the word "text", but it would if inside a fenced div.

For images, etc... the lua filter is available here

List of macOS text editors and code editors

I thought TextMate was everyone's favourite. I haven't met a programmer using a Mac who is not using TextMate.

When can I use a forward declaration?

The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

How to start Spyder IDE on Windows

I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.

I installed PyQt5 (pip install pyqt5) and Spyder (pip install spyder) which both installed w/out error and included all of the necessary dependencies.

To launch Spyder, I created a simple Python script (Spyder.py):

# Spyder Start Script
from spyder.app import start
start.main()

Then I created a Windows batch file (Spyder.bat):

@echo off
python c:\<path_to_Spyder_py>\Spyder.py

Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.

Works like a charm for me.

onclick="location.href='link.html'" does not load page in Safari

Give this a go:

<option onclick="parent.location='#5.2'">Bookmark 2</option>

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

How to loop through a plain JavaScript object with the objects as members?

This answer is an aggregate of the solutions that were provided in this post with some performance feedbacks. I think there is 2 use-cases and the OP didn't mention if he needs to access the keys in order use them during the loop process.

I. the keys need to be accessed,

? the of and Object.keys approach

let k;
for (k of Object.keys(obj)) {

    /*        k : key
     *   obj[k] : value
     */
}

? the in approach

let k;
for (k in obj) {

    /*        k : key
     *   obj[k] : value
     */
}

Use this one with cautious, as it could print prototype'd properties of obj

? the ES7 approach

for (const [key, value] of Object.entries(obj)) {

}

However, at the time of the edit I wouldn't recommend the ES7 method, because JavaScript initializes a lot of variables internally to build this procedure (see the feedbacks for proof). Unless you are not developing a huge app which deserves optimization, then it is ok but if optimization is your priority you should think about it.

II. we just need to access each values,

? the of and Object.values approach

let v;
for (v of Object.values(obj)) {

}

More feedbacks about the tests :

  • Caching Object.keys or Object.values performance is negligible

For instance,

const keys = Object.keys(obj);
let i;
for (i of keys) {
  //
}
// same as
for (i of Object.keys(obj)) {
  //
}
  • For Object.values case, using a native for loop with cached variables in Firefox seems to be a little faster than using a for...of loop. However the difference is not that important and Chrome is running for...of faster than native for loop, so I would recommend to use for...of when dealing with Object.values in any cases (4th and 6th tests).

  • In Firefox, the for...in loop is really slow, so when we want to cache the key during the iteration it is better to use Object.keys. Plus Chrome is running both structure at equal speed (1st and last tests).

You can check the tests here : https://jsperf.com/es7-and-misc-loops

How can I break up this long line in Python?

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator (+):

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

What is "Advanced" SQL?

SELECT ... HAVING ... is a good start. Not many developers seem to understand how to use it.

Display PDF file inside my android application

You can download the source from here(Display PDF file inside my android application)

Add this dependency in your gradle file:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


    </RelativeLayout>

MainActivity.java

package pdfviewer.pdfviewer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }


    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}

Path.Combine for URLs?

I have to point out that Path.Combine appears to work for this also directly, at least on .NET 4.

How to allocate aligned memory only using the standard library?

The first thing that popped into my head when reading this question was to define an aligned struct, instantiate it, and then point to it.

Is there a fundamental reason I'm missing since no one else suggested this?

As a sidenote, since I used an array of char (assuming the system's char is 8 bits (i.e. 1 byte)), I don't see the need for the __attribute__((packed)) necessarily (correct me if I'm wrong), but I put it in anyway.

This works on two systems I tried it on, but it's possible that there is a compiler optimization that I'm unaware of giving me false positives vis-a-vis the efficacy of the code. I used gcc 4.9.2 on OSX and gcc 5.2.1 on Ubuntu.

#include <stdio.h>
#include <stdlib.h>

int main ()
{

   void *mem;

   void *ptr;

   // answer a) here
   struct __attribute__((packed)) s_CozyMem {
       char acSpace[16];
   };

   mem = malloc(sizeof(struct s_CozyMem));
   ptr = mem;

   // memset_16aligned(ptr, 0, 1024);

   // Check if it's aligned
   if(((unsigned long)ptr & 15) == 0) printf("Aligned to 16 bytes.\n");
   else printf("Rubbish.\n");

   // answer b) here
   free(mem);

   return 1;
}

Table overflowing outside of div

A crude work around is to set display: table on the containing div.

javascript getting my textbox to display a variable

You're on the right track with using document.getElementById() as you have done for your first two text boxes. Use something like document.getElementById("textbox3") to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;

For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/> (e.g. <span id="answerDisplay">--</span>). Then use document.getElementById("answerDisplay").textContent = answer; to display it.

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

In MySQL, "Group By" uses an extra step: filesort. I realize DISTINCT is faster than GROUP BY, and that was a surprise.

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

How to make System.out.println() shorter

package some.useful.methods;

public class B {

    public static void p(Object s){
        System.out.println(s);
    }
}
package first.java.lesson;

import static some.useful.methods.B.*;

public class A {

    public static void main(String[] args) {

        p("Hello!");

    }
}

Null or empty check for a string variable

Yes, you could also use COALESCE(@value,'')='' which is based on the ANSI SQL standard:

SELECT CASE WHEN COALESCE(@value,'')='' 
    THEN 'Yes, it is null or empty' ELSE 'No, not null or empty' 
    END AS IsNullOrEmpty

DEMO

MySQL: How to copy rows, but change a few fields?

Hey how about to copy all fields, change one of them to the same value + something else.

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, Event_ID+"155"
  FROM Table
 WHERE Event_ID = "120"

??????????

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

jQuery if Element has an ID?

I seemed to have been able to solve it with:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}

Android Canvas: drawing too large bitmap

If you don't want your image to be pre-scaled you can move it to the res/drawable-nodpi/ folder.

More info: https://developer.android.com/training/multiscreen/screendensities#DensityConsiderations

SQL Query - how do filter by null or not null

set ansi_nulls off go select * from table t inner join otherTable o on t.statusid = o.statusid go set ansi_nulls on go

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {
        it.next();
    }
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {
        it.next();
    }
}

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        @Override
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
        }
    };
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.
}

regular expression for DOT

You should use contains not matches

if(nom.contains("."))
    System.out.println("OK");
else
    System.out.println("Bad");

GitHub: How to make a fork of public repository private?

GitHub now has an import option that lets you choose whatever you want your new imported repository public or private

Github Repository import

Check date with todays date

Android already has a dedicated class for this. Check DateUtils.isToday(long when)

Range with step of type float

When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1) return [0.0, 1.1] or [0.0, 1.1, 2.199999999]? There's no way to be certain without rigorous analysis.

The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

In Short -> You must enable VT-x Technology in your BIOS.

Here are the detailed steps:

1- Restore Optimized Defaults (Not Necessary)//Steps to start BIOS

Its better to restore Optimized Defaults before, But following steps are not necessary:

  1. Reboot the computer and open the system's BIOS menu. This can usually be done by pressing the delete key, the F1 key or Alt and F4 keys depending on the system.

  2. Select Restore Defaults or Restore Optimized Defaults, and then select Save & Exit.

2- Enable VT-x Technology in BIOS (Necessary)

  1. Power on/Reboot the machine and open the BIOS (as per Step 1).

  2. Open the Processor submenu The processor settings menu may be hidden in the Chipset, Advanced CPU Configuration or Northbridge.

  3. Enable Intel Virtualization Technology (also known as Intel VT-x) or AMD-V depending on the brand of the processor. The virtualization extensions may be labelled Virtualization Extensions, Vanderpool or various other names depending on the OEM and system BIOS.

  4. Select Save & Exit.

Note: Many of the steps above may vary depending on your motherboard, processor type, chipset and OEM. Refer to your system's accompanying documentation for the correct information on configuring your system.

Test:

Run cat /proc/cpuinfo | grep vmx svm. If the command outputs, the virtualization extensions are now enabled. If there is no output your system may not have the virtualization extensions or the correct BIOS setting enabled.

Detailed instructions can be found Here

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

Visual Studio Copy Project

I have a project where the source files are in in a folder below the project folder. When I copied the project folder without the source folder and opened the copied project, the source files are not missing but found at the old location. I closed the project, copied also the source folder, and re-opened the project. Now, the project magically references the copied source files (both the new path showed up on "save as" and a change in a file has been saved in the copied version).

There is a caveat: If not both old and new project folders are below a used library folder, the above-mentioned magic discards also the absolute reference to the library and expects it under the same relative path.

I tried this with VS Express 2012.

How do I debug "Error: spawn ENOENT" on node.js?

Are you changing the env option?

Then look at this answer.


I was trying to spawn a node process and TIL that you should spread the existing environment variables when you spawn else you'll loose the PATH environment variable and possibly other important ones.

This was the fix for me:

const nodeProcess = spawn('node', ['--help'], {
  env: {
    // by default, spawn uses `process.env` for the value of `env`
    // you can _add_ to this behavior, by spreading `process.env`
    ...process.env,
    OTHER_ENV_VARIABLE: 'test',
  }
});

How to extract elements from a list using indices in Python?

Try

numbers = range(10, 16)
indices = (1, 1, 2, 1, 5)

result = [numbers[i] for i in indices]

How do I pass multiple ints into a vector at once?

These days (c++17) it's easy:

auto const pusher([](auto& v) noexcept
  {
    return [&](auto&& ...e)
      {
        (
          (
            v.push_back(std::forward<decltype(e)>(e))
          ),
          ...
        );
      };
  }
);

pusher(TestVector)(2, 5, 8, 11, 14);

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

Set content of iframe

I needed to reuse the same iframe and replace the content each time. I've tried a few ways and this worked for me:

// Set the iframe's src to about:blank so that it conforms to the same-origin policy 
iframeElement.src = "about:blank";

// Set the iframe's new HTML
iframeElement.contentWindow.document.open();
iframeElement.contentWindow.document.write(newHTML);
iframeElementcontentWindow.document.close();

Here it is as a function:

function replaceIframeContent(iframeElement, newHTML)
{
    iframeElement.src = "about:blank";
    iframeElement.contentWindow.document.open();
    iframeElement.contentWindow.document.write(newHTML);
    iframeElement.contentWindow.document.close();
}

casting Object array to Integer array error

Or do the following:

...

  Integer[] integerArray = new Integer[integerList.size()];
  integerList.toArray(integerArray);

  return integerArray;

}

Use the auto keyword in C++ STL

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

This is supposedly because you trying to make cross-domain request, or something that is clarified as it. You could try adding header('Access-Control-Allow-Origin: *'); to the requested file.

Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source or XHR polling in IE 8-10 (which confused me first time).

How to check if a query string value is present via JavaScript?

Try this

//field "search";
var pattern = /[?&]search=/;
var URL = location.search;

if(pattern.test(URL))
{
    alert("Found :)");
}else{
    alert("Not found!");
}

JSFiddle: https://jsfiddle.net/codemirror/zj4qyao2/

Is there any way to install Composer globally on Windows?

An alternative variant (see Lusitanian answer) is to register .phar files as executable on your system, exemplary phar.reg file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.phar]
@="phar_auto_file"

[HKEY_CLASSES_ROOT\phar_auto_file\shell\open\command]
@="\"c:\\PROGRA~1\\php\\php.exe\" \"%1\" %*"

Just replace the path to php.exe to your PHP executable. You can then also extend the %PATHEXT% commandline variable with .PHAR which will allow you to type composer instead of composer.phar as long as composer.phar is inside the %Path%.

Sending the bearer token with axios

This works and I need to set the token only once in my app.js:

axios.defaults.headers.common = {
    'Authorization': 'Bearer ' + token
};

Then I can make requests in my components without setting the header again.

"axios": "^0.19.0",

Remove Project from Android Studio

  1. Go to your Android project directory

    C:\Users\HP\AndroidStudioProjects
    

    Screenshot

  2. Delete which one you need to delete

  3. Restart Android Studio

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

How do I suspend painting for a control and its children?

Or just use Control.SuspendLayout() and Control.ResumeLayout().

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

IIS 7, HttpHandler and HTTP Error 500.21

It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.

You can learn more about modules, handlers and IIS modes in the following blog post:

IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions

For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.

Passing data between view controllers

I have seen a lot of people over complicating this using the didSelectRowAtPath method. I am using Core Data in my example.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // This solution is for using Core Data
    YourCDEntityName * value = (YourCDEntityName *)[[self fetchedResultsController] objectAtIndexPath: indexPath];

    YourSecondViewController * details = [self.storyboard instantiateViewControllerWithIdentifier:@"nameOfYourSecondVC"]; // Make sure in storyboards you give your second VC an identifier

    // Make sure you declare your value in the second view controller
    details.selectedValue = value;

    // Now that you have said to pass value all you need to do is change views
    [self.navigationController pushViewController: details animated:YES];

}

Four lines of code inside the method and you are done.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

This too took me sometime to figure out.

Solution:

To create a new Maven Project under the existing workspace, just have the "Use default Workspace location" ticked (Ignore what is in the grayed out location text input).

The name of the project will be determined by you Artifact Id in step 2 of the creation wizard.

Reasoning:

It was so confusing because in my case, because when I selected to create a new Maven Project: the default workspace loaction is ticked and directly proceeding it is the grayed out "Location" text input had the workspace location + the existing project I was looking at before choose to create a new Maven Project. (ie: Location = '[workspace path]/last looked at project')

So I unticked the default workspace location box and entered in '[workspace path]/new project', which didn't work because eclipse expects the [workspace path] to be different compared to the default path. (Otherwise we would of selected the default workspace check box).

What does "collect2: error: ld returned 1 exit status" mean?

In your situation you got a reference to the missing symbols. But in some situations, ld will not provide error information.

If you want to expand the information provided by ld, just add the following parameters to your $(LDFLAGS)

-Wl,-V

How can I position my jQuery dialog to center?

Try this for older versions and somebody who don't want to use position:

$("#dialog-div-id").dialog({position: ['center', 'top'],....

WHERE Clause to find all records in a specific month

I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

Let's assume you have a table named things that looks something like this:

id happend_at
-- ----------------
1  2009-01-01 12:08
2  2009-02-01 12:00
3  2009-01-12 09:40
4  2009-01-29 17:55

And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

SELECT id FROM things 
   WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009

Which would return:

id
---
1
3
4

How to abort makefile if variable not set?

Use the shell error handling for unset variables (note the double $):

$ cat Makefile
foo:
        echo "something is set to $${something:?}"

$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127


$ make foo something=x
echo "something is set to ${something:?}"
something is set to x

If you need a custom error message, add it after the ?:

$ cat Makefile
hello:
        echo "hello $${name:?please tell me who you are via \$$name}"

$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127

$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Remove characters except digits from string using Python?

A fast version for Python 3:

# xx3.py
from collections import defaultdict
import string
_NoneType = type(None)

def keeper(keep):
    table = defaultdict(_NoneType)
    table.update({ord(c): c for c in keep})
    return table

digit_keeper = keeper(string.digits)

Here's a performance comparison vs. regex:

$ python3.3 -mtimeit -s'import xx3; x="aaa12333bb445bb54b5b52"' 'x.translate(xx3.digit_keeper)'
1000000 loops, best of 3: 1.02 usec per loop
$ python3.3 -mtimeit -s'import re; r = re.compile(r"\D"); x="aaa12333bb445bb54b5b52"' 'r.sub("", x)'
100000 loops, best of 3: 3.43 usec per loop

So it's a little bit more than 3 times faster than regex, for me. It's also faster than class Del above, because defaultdict does all its lookups in C, rather than (slow) Python. Here's that version on my same system, for comparison.

$ python3.3 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)'
100000 loops, best of 3: 13.6 usec per loop

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Assign one struct to another in C

Yes if the structure is of the same type. Think it as a memory copy.

How can I quantify difference between two images?

I apologize if this is too late to reply, but since I've been doing something similar I thought I could contribute somehow.

Maybe with OpenCV you could use template matching. Assuming you're using a webcam as you said:

  1. Simplify the images (thresholding maybe?)
  2. Apply template matching and check the max_val with minMaxLoc

Tip: max_val (or min_val depending on the method used) will give you numbers, large numbers. To get the difference in percentage, use template matching with the same image -- the result will be your 100%.

Pseudo code to exemplify:

previous_screenshot = ...
current_screenshot = ...

# simplify both images somehow

# get the 100% corresponding value
res = matchTemplate(previous_screenshot, previous_screenshot, TM_CCOEFF)
_, hundred_p_val, _, _ = minMaxLoc(res)

# hundred_p_val is now the 100%

res = matchTemplate(previous_screenshot, current_screenshot, TM_CCOEFF)
_, max_val, _, _ = minMaxLoc(res)

difference_percentage = max_val / hundred_p_val

# the tolerance is now up to you

Hope it helps.

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

PHP 5 disable strict standards error

All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess at root folder. Just to hide the errors. [Put one of the followling lines in the file]

php_flag display_errors off

Or

php_value display_errors 0

Next, to set the error reporting

php_value error_reporting 30719

If you are wondering how the value 30719 came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719)

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

What is the correct way to read a serial port using .NET framework?

Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

 using System;
 using System.IO.Ports;

 class SerialPortProgram 
 { 
  // Create the serial port with basic settings 
    private SerialPort port = new   SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One); 
    [STAThread] 
    static void Main(string[] args) 
    { 
      // Instatiate this 
      SerialPortProgram(); 
    } 

    private static void SerialPortProgram() 
    { 
        Console.WriteLine("Incoming Data:");
         // Attach a method to be called when there
         // is data waiting in the port's buffer 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        // Begin communications 
        port.Open(); 
        // Enter an application loop to keep this thread alive 
        Console.ReadLine();
     } 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
       // Show all the incoming data in the port's buffer
       Console.WriteLine(port.ReadExisting()); 
    } 
}

Or is you want to do it based on what you were trying to do , you can try this

public class MySerialReader : IDisposable
{
  private SerialPort serialPort;
  private Queue<byte> recievedData = new Queue<byte>();

  public MySerialReader()
  {
    serialPort = new SerialPort();
    serialPort.Open();
    serialPort.DataReceived += serialPort_DataReceived;
  }

  void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
  {
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    data.ToList().ForEach(b => recievedData.Enqueue(b));
    processData();
  }

  void processData()
  {
    // Determine if we have a "packet" in the queue
    if (recievedData.Count > 50)
    {
        var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
    }
  }

  public void Dispose()
  {
        if (serialPort != null)
        {
            serialPort.Dispose();
        }
  }

How do I force Kubernetes to re-pull an image?

Now, the command kubectl rollout restart deploy YOUR-DEPLOYMENT combined with a imagePullPolicy: Always policy will allow you to restart all your pods with a latest version of your image.

How to decorate a class?

I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)

What you're thinking of is a metaclass. The __new__ function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.

Example:

def substitute_init(self, id, *args, **kwargs):
    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = substitute_init
        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I had the same problem. The solution was to update IntelliJ to the newest version.

How to round up with excel VBA round()?

If you want to round up, use half adjusting. Add 0.5 to the number to be rounded up and use the INT() function.

answer = INT(x + 0.5)

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

Datatables: Cannot read property 'mData' of undefined

in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.

_x000D_
_x000D_
<table id="tabel_data">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>heading 1</th>_x000D_
            <th>heading 2</th>_x000D_
            <th>heading 3</th>_x000D_
            <th>heading 4</th>_x000D_
            <th>heading 5</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>data-1</td>_x000D_
            <td>data-2</td>_x000D_
            <td>data-3</td>_x000D_
            <td>data-4</td>_x000D_
            <td>data-5</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>_x000D_
_x000D_
<table id="tabel_data">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>heading 1</th>_x000D_
            <th>heading 2</th>_x000D_
            <th>heading 3</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>data-1</td>_x000D_
            <td>data-2</td>_x000D_
            <td>data-3</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

getting the screen density programmatically in android?

To get dpi:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

// will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH
int dpiClassification = dm.densityDpi;

// these will return the actual dpi horizontally and vertically
float xDpi = dm.xdpi;
float yDpi = dm.ydpi;

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

Best way to Bulk Insert from a C# DataTable

This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.

If you're using SQL Server, use the SqlBulkCopy class.

For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.

What can I use for good quality code coverage for C#/.NET?

C# Test Coverage Tool has very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class, and package levels.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Just to complete the example with a full implementation of ClientHttpRequestInterceptor to trace request and response:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        log.info("===========================request begin================================================");
        log.debug("URI         : {}", request.getURI());
        log.debug("Method      : {}", request.getMethod());
        log.debug("Headers     : {}", request.getHeaders() );
        log.debug("Request body: {}", new String(body, "UTF-8"));
        log.info("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        log.info("============================response begin==========================================");
        log.debug("Status code  : {}", response.getStatusCode());
        log.debug("Status text  : {}", response.getStatusText());
        log.debug("Headers      : {}", response.getHeaders());
        log.debug("Response body: {}", inputStringBuilder.toString());
        log.info("=======================response end=================================================");
    }

}

Then instantiate RestTemplate using a BufferingClientHttpRequestFactory and the LoggingRequestInterceptor:

RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);

The BufferingClientHttpRequestFactory is required as we want to use the response body both in the interceptor and for the initial calling code. The default implementation allows to read the response body only once.

How to find a user's home directory on linux or unix?

To find the home directory for user FOO on a UNIX-ish system, use ~FOO. For the current user, use ~.

How to Apply Gradient to background view of iOS Swift App

It's easy

    // MARK: - Gradient
extension CAGradientLayer {
    enum Point {
        case topLeft
        case centerLeft
        case bottomLeft
        case topCenter
        case center
        case bottomCenter
        case topRight
        case centerRight
        case bottomRight
        var point: CGPoint {
            switch self {
            case .topLeft:
                return CGPoint(x: 0, y: 0)
            case .centerLeft:
                return CGPoint(x: 0, y: 0.5)
            case .bottomLeft:
                return CGPoint(x: 0, y: 1.0)
            case .topCenter:
                return CGPoint(x: 0.5, y: 0)
            case .center:
                return CGPoint(x: 0.5, y: 0.5)
            case .bottomCenter:
                return CGPoint(x: 0.5, y: 1.0)
            case .topRight:
                return CGPoint(x: 1.0, y: 0.0)
            case .centerRight:
                return CGPoint(x: 1.0, y: 0.5)
            case .bottomRight:
                return CGPoint(x: 1.0, y: 1.0)
            }
        }
    }
    convenience init(start: Point, end: Point, colors: [CGColor], type: CAGradientLayerType) {
        self.init()
        self.startPoint = start.point
        self.endPoint = end.point
        self.colors = colors
        self.locations = (0..<colors.count).map(NSNumber.init)
        self.type = type
    }
}

Use like this:-

let fistColor = UIColor.white
let lastColor = UIColor.black
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: [fistColor.cgColor, lastColor.cgColor], type: .radial)
gradient.frame = yourView.bounds
yourView.layer.addSublayer(gradient)

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

how to loop through each row of dataFrame in pyspark

Using list comprehensions in python, you can collect an entire column of values into a list using just two lines:

df = sqlContext.sql("show tables in default")
tableList = [x["tableName"] for x in df.rdd.collect()]

In the above example, we return a list of tables in database 'default', but the same can be adapted by replacing the query used in sql().

Or more abbreviated:

tableList = [x["tableName"] for x in sqlContext.sql("show tables in default").rdd.collect()]

And for your example of three columns, we can create a list of dictionaries, and then iterate through them in a for loop.

sql_text = "select name, age, city from user"
tupleList = [{name:x["name"], age:x["age"], city:x["city"]} 
             for x in sqlContext.sql(sql_text).rdd.collect()]
for row in tupleList:
    print("{} is a {} year old from {}".format(
        row["name"],
        row["age"],
        row["city"]))

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

How can I get browser to prompt to save password?

The following code is tested on

  • Chrome 39.0.2171.99m: WORKING
  • Android Chrome 39.0.2171.93: WORKING
  • Android stock-browser (Android 4.4): NOT WORKING
  • Internet Explorer 5+ (emulated): WORKING
  • Internet Explorer 11.0.9600.17498 / Update-Version: 11.0.15: WORKING
  • Firefox 35.0: WORKING

JS-Fiddle:
http://jsfiddle.net/ocozggqu/

Post-code:

// modified post-code from https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method)
{
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.

    var form = document.createElement("form");
    form.id = "dynamicform" + Math.random();
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    form.setAttribute("style", "display: none");
    // Internet Explorer needs this
    form.setAttribute("onsubmit", "window.external.AutoCompleteSaveForm(document.getElementById('" + form.id + "'))");

    for (var key in params)
    {
        if (params.hasOwnProperty(key))
        {
            var hiddenField = document.createElement("input");
            // Internet Explorer needs a "password"-field to show the store-password-dialog
            hiddenField.setAttribute("type", key == "password" ? "password" : "text");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }

    var submitButton = document.createElement("input");
    submitButton.setAttribute("type", "submit");

    form.appendChild(submitButton);

    document.body.appendChild(form);

    //form.submit(); does not work on Internet Explorer
    submitButton.click(); // "click" on submit-button needed for Internet Explorer
}

Remarks

  • For dynamic login-forms a call to window.external.AutoCompleteSaveForm is needed
  • Internet Explorer need a "password"-field to show the store-password-dialog
  • Internet Explorer seems to require a click on submit-button (even if it's a fake click)

Here is a sample ajax login-code:

function login(username, password, remember, redirectUrl)
{
    // "account/login" sets a cookie if successful
    return $.postJSON("account/login", {
        username: username,
        password: password,
        remember: remember,
        returnUrl: redirectUrl
    })
    .done(function ()
    {
        // login succeeded, issue a manual page-redirect to show the store-password-dialog
        post(
            redirectUrl,
            {
                username: username,
                password: password,
                remember: remember,
                returnUrl: redirectUrl
            },
            "post");
    })
    .fail(function ()
    {
        // show error
    });
};

Remarks

  • "account/login" sets a cookie if successful
  • Page-redirect ("manually" initiated by js-code) seems to be required. I also tested an iframe-post, but I was not successful with that.

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

public ActionResult Index()
{
    byte[] contents = FetchPdfBytes();
    return File(contents, "application/pdf", "test.pdf");
}

and for opening the PDF inside the browser you will need to set the Content-Disposition header:

public ActionResult Index()
{
    byte[] contents = FetchPdfBytes();
    Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
    return File(contents, "application/pdf");
}

Youtube - downloading a playlist - youtube-dl

Download YouTube playlist videos in separate directory indexed by video order in a playlist

$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s'  https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re

Download all playlists of YouTube channel/user keeping each playlist in separate directory:

$ youtube-dl -o '%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/user/TheLinuxFoundation/playlists

Video Selection:

youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platform specific. It should work on your Unix box, on Windows or on macOS. It is released to the public domain, which means you can modify it, redistribute it or use it however you like.

$ youtube-dl [OPTIONS] URL [URL...]
--playlist-start NUMBER          Playlist video to start at (default is 1)

--playlist-end NUMBER            Playlist video to end at (default is last)

--playlist-items ITEM_SPEC       Playlist video items to download. Specify
                                 indices of the videos in the playlist
                                 separated by commas like: "--playlist-items
                                 1,2,5,8" if you want to download videos
                                 indexed 1, 2, 5, 8 in the playlist. You can
                                 specify range: "--playlist-items
                                 1-3,7,10-13", it will download the videos
                                 at index 1, 2, 3, 7, 10, 11, 12 and 13.

Where to get "UTF-8" string literal in Java?

This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

Multi-line bash commands in makefile

You can use backslash for line continuation. However note that the shell receives the whole command concatenated into a single line, so you also need to terminate some of the lines with a semicolon:

foo:
    for i in `find`;     \
    do                   \
        all="$$all $$i"; \
    done;                \
    gcc $$all

But if you just want to take the whole list returned by the find invocation and pass it to gcc, you actually don't necessarily need a multiline command:

foo:
    gcc `find`

Or, using a more shell-conventional $(command) approach (notice the $ escaping though):

foo:
    gcc $$(find)

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

How do I concatenate or merge arrays in Swift?

With Swift 5, according to your needs, you may choose one of the six following ways to concatenate/merge two arrays.


#1. Merge two arrays into a new array with Array's +(_:_:) generic operator

Array has a +(_:_:) generic operator. +(_:_:) has the following declaration:

Creates a new collection by concatenating the elements of a collection and a sequence.

static func + <Other>(lhs: Array<Element>, rhs: Other) -> Array<Element> where Other : Sequence, Self.Element == Other.Element

The following Playground sample code shows how to merge two arrays of type [Int] into a new array using +(_:_:) generic operator:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = array1 + array2
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

#2. Append the elements of an array into an existing array with Array's +=(_:_:) generic operator

Array has a +=(_:_:) generic operator. +=(_:_:) has the following declaration:

Appends the elements of a sequence to a range-replaceable collection.

static func += <Other>(lhs: inout Array<Element>, rhs: Other) where Other : Sequence, Self.Element == Other.Element

The following Playground sample code shows how to append the elements of an array of type [Int] into an existing array using +=(_:_:) generic operator:

var array1 = [1, 2, 3]
let array2 = [4, 5, 6]

array1 += array2
print(array1) // prints [1, 2, 3, 4, 5, 6]

#3. Append an array to another array with Array's append(contentsOf:) method

Swift Array has an append(contentsOf:) method. append(contentsOf:) has the following declaration:

Adds the elements of a sequence or collection to the end of this collection.

mutating func append<S>(contentsOf newElements: S) where S : Sequence, Self.Element == S.Element

The following Playground sample code shows how to append an array to another array of type [Int] using append(contentsOf:) method:

var array1 = [1, 2, 3]
let array2 = [4, 5, 6]

array1.append(contentsOf: array2)
print(array1) // prints [1, 2, 3, 4, 5, 6]

#4. Merge two arrays into a new array with Sequence's flatMap(_:) method

Swift provides a flatMap(_:) method for all types that conform to Sequence protocol (including Array). flatMap(_:) has the following declaration:

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

The following Playground sample code shows how to merge two arrays of type [Int] into a new array using flatMap(_:) method:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].flatMap({ (element: [Int]) -> [Int] in
    return element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

#5. Merge two arrays into a new array with Sequence's joined() method and Array's init(_:) initializer

Swift provides a joined() method for all types that conform to Sequence protocol (including Array). joined() has the following declaration:

Returns the elements of this sequence of sequences, concatenated.

func joined() -> FlattenSequence<Self>

Besides, Swift Array has a init(_:) initializer. init(_:) has the following declaration:

Creates an array containing the elements of a sequence.

init<S>(_ s: S) where Element == S.Element, S : Sequence

Therefore, the following Playground sample code shows how to merge two arrays of type [Int] into a new array using joined() method and init(_:) initializer:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenCollection = [array1, array2].joined() // type: FlattenBidirectionalCollection<[Array<Int>]>
let flattenArray = Array(flattenCollection)
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

#6. Merge two arrays into a new array with Array's reduce(_:_:) method

Swift Array has a reduce(_:_:) method. reduce(_:_:) has the following declaration:

Returns the result of combining the elements of the sequence using the given closure.

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

The following Playground code shows how to merge two arrays of type [Int] into a new array using reduce(_:_:) method:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
    return result + element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

How to get child process from parent process

The shell process is $$ since it is a special parameter

On Linux, the proc(5) filesystem gives a lot of information about processes. Perhaps pgrep(1) (which accesses /proc) might help too.

So try cat /proc/$$/status to get the status of the shell process.

Hence, its parent process id could be retrieved with e.g.

  parpid=$(awk '/PPid:/{print $2}' /proc/$$/status)

Then use $parpid in your script to refer to the parent process pid (the parent of the shell).

But I don't think you need it!

Read some Bash Guide (or with caution advanced bash scripting guide, which has mistakes) and advanced linux programming.

Notice that some server daemon processes (wich usually need to be unique) are explicitly writing their pid into /var/run, e.g. the  sshd server daemon is writing its pid into the textual file /var/run/sshd.pid). You may want to add such a feature into your own server-like programs (coded in C, C++, Ocaml, Go, Rust or some other compiled language).

What are naming conventions for MongoDB?

Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id.

For example, in a dogs collection, a document would have manual references to external documents named like this:

{
  name: 'fido',
  owner_id: '5358e4249611f4a65e3068ab',
  race_id: '5358ee549611f4a65e3068ac',
  colour: 'yellow'
  ...
}

This follows the Mongo convention of naming _id the identifier for every document.

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

How do I show my global Git configuration?

Git 2.6 (Sept/Oct 2015) will add the option --name-only to simplify the output of a git config -l:

See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit fc9dfda, 31 Aug 2015)

config: add '--name-only' option to list only variable names

'git config' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list' or '--get-regexp' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.

Though 'git config' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.

Even our own bash completion script suffers from these issues.

Help the completion script, and shell scripts in general, by introducing the '--name-only' option to modify the output of '--list' and '--get-regexp' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

When should I use double or single quotes in JavaScript?

The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.

Where does Hive store files in HDFS?

The location they are stored on the HDFS is fairly easy to figure out once you know where to look. :)

If you go to http://NAMENODE_MACHINE_NAME:50070/ in your browser it should take you to a page with a Browse the filesystem link.

In the $HIVE_HOME/conf directory there is the hive-default.xml and/or hive-site.xml which has the hive.metastore.warehouse.dir property. That value is where you will want to navigate to after clicking the Browse the filesystem link.

In mine, it's /usr/hive/warehouse. Once I navigate to that location, I see the names of my tables. Clicking on a table name (which is just a folder) will then expose the partitions of the table. In my case, I currently only have it partitioned on date. When I click on the folder at this level, I will then see files (more partitioning will have more levels). These files are where the data is actually stored on the HDFS.

I have not attempted to access these files directly, I'm assuming it can be done. I would take GREAT care if you are thinking about editing them. :) For me - I'd figure out a way to do what I need to without direct access to the Hive data on the disk. If you need access to raw data, you can use a Hive query and output the result to a file. These will have the exact same structure (divider between columns, ect) as the files on the HDFS. I do queries like this all the time and convert them to CSVs.

The section about how to write data from queries to disk is https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Writingdataintothefilesystemfromqueries

UPDATE

Since Hadoop 3.0.0 - Alpha 1 there is a change in the default port numbers. NAMENODE_MACHINE_NAME:50070 changes to NAMENODE_MACHINE_NAME:9870. Use the latter if you are running on Hadoop 3.x. The full list of port changes are described in HDFS-9427

Best implementation for Key Value Pair Data Structure?

One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:

public class TokenTree : Dictionary<string, string>
{
    public IDictionary<string, string> SubPairs;
}

This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).

And yup you got the concept of the constructor right :)