Programs & Examples On #Local files

How to fetch data from local JSON file on react native?

Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

Check if a file exists locally using JavaScript only

Try this:

window.onclick=(function(){
  try {
    var file = window.open("file://mnt/sdcard/download/Click.ogg");
    setTimeout('file.close()', 100);
    setTimeout("alert('Audio file found. Have a nice day!');", 101);
  } catch(err) {
    var wantstodl=confirm("Warning:\n the file, Click.ogg is not found.\n do you want to download it?\n "+err.message);
    if (wantstodl) {
      window.open("https://www.dropbox.com/s/qs9v6g2vru32xoe/Click.ogg?dl=1"); //downloads the audio file
    }
  }
});

How can I create a link to a local file on a locally-run web page?

Janky at best

<a href="file://///server/folders/x/x/filename.ext">right click </a></td>

and then right click, select "copy location" option, and then paste into url.

Loading local JSON file

function readTextFile(srcfile) {
        try { //this is for IE
            var fso = new ActiveXObject("Scripting.FileSystemObject");;
            if (fso.FileExists(srcfile)) {
                var fileReader = fso.OpenTextFile(srcfile, 1);
                var line = fileReader.ReadLine();
                var jsonOutput = JSON.parse(line); 
            }

        } catch (e) {

        }
}

readTextFile("C:\\Users\\someuser\\json.txt");

What I did was, first of all, from network tab, record the network traffic for the service, and from response body, copy and save the json object in a local file. Then call the function with the local file name, you should be able to see the json object in jsonOutout above.

How do I obtain the frequencies of each value in an FFT?

The first bin in the FFT is DC (0 Hz), the second bin is Fs / N, where Fs is the sample rate and N is the size of the FFT. The next bin is 2 * Fs / N. To express this in general terms, the nth bin is n * Fs / N.

So if your sample rate, Fs is say 44.1 kHz and your FFT size, N is 1024, then the FFT output bins are at:

  0:   0 * 44100 / 1024 =     0.0 Hz
  1:   1 * 44100 / 1024 =    43.1 Hz
  2:   2 * 44100 / 1024 =    86.1 Hz
  3:   3 * 44100 / 1024 =   129.2 Hz
  4: ...
  5: ...
     ...
511: 511 * 44100 / 1024 = 22006.9 Hz

Note that for a real input signal (imaginary parts all zero) the second half of the FFT (bins from N / 2 + 1 to N - 1) contain no useful additional information (they have complex conjugate symmetry with the first N / 2 - 1 bins). The last useful bin (for practical aplications) is at N / 2 - 1, which corresponds to 22006.9 Hz in the above example. The bin at N / 2 represents energy at the Nyquist frequency, i.e. Fs / 2 ( = 22050 Hz in this example), but this is in general not of any practical use, since anti-aliasing filters will typically attenuate any signals at and above Fs / 2.

How can I find and run the keytool

keytool is part of the JDK.

Try to prepend %{JAVA_HOME}\ to the exec statement or c:\{path to jdk}\bin.

Need to get current timestamp in Java

Print a Timestamp in java, using the java.sql.Timestamp.

import java.sql.Timestamp;
import java.util.Date;

public class GetCurrentTimeStamp {
    public static void main( String[] args ){
        java.util.Date date= new java.util.Date();
        System.out.println(new Timestamp(date.getTime()));
    }
}

This prints:

2014-08-07 17:34:16.664

Print a Timestamp in Java using SimpleDateFormat on a one-liner.

import java.util.Date;
import java.text.SimpleDateFormat;

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

        System.out.println(
            new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));

    }

}

Prints:

08/14/2014 14:10:38

Java date format legend:

G Era designation      Text               AD
y Year                 Year               1996; 96
M Month in year        Month              July; Jul; 07
w Week in year         Number             27
W Week in month        Number             2
D Day in year          Number             189
d Day in month         Number             10
F Day of week in month Number             2
E Day in week          Text               Tuesday; Tue
a Am/pm marker         Text               PM
H Hour in day (0-23)   Number             0
k Hour in day (1-24)   Number             24
K Hour in am/pm (0-11) Number             0
h Hour in am/pm (1-12) Number             12
m Minute in hour       Number             30
s Second in minute     Number             55
S Millisecond          Number             978
z Time zone            General time zone  Pacific Standard Time; PST; GMT-08:00
Z Time zone            RFC 822 time zone  -0800

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

How do I determine the size of an object in Python?

Python 3.8 (Q1 2019) will change some of the results of sys.getsizeof, as announced here by Raymond Hettinger:

Python containers are 8 bytes smaller on 64-bit builds.

tuple ()  48 -> 40       
list  []  64 ->56
set()    224 -> 216
dict  {} 240 -> 232

This comes after issue 33597 and Inada Naoki (methane)'s work around Compact PyGC_Head, and PR 7043

This idea reduces PyGC_Head size to two words.

Currently, PyGC_Head takes three words; gc_prev, gc_next, and gc_refcnt.

  • gc_refcnt is used when collecting, for trial deletion.
  • gc_prev is used for tracking and untracking.

So if we can avoid tracking/untracking while trial deletion, gc_prev and gc_refcnt can share same memory space.

See commit d5c875b:

Removed one Py_ssize_t member from PyGC_Head.
All GC tracked objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.

Are HTTP headers case-sensitive?

tldr; both HTTP/1.1 and HTTP/2 headers are case-insensitive.

According to RFC 7230 (HTTP/1.1):

Each header field consists of a case-insensitive field name followed by a colon (":"), optional leading whitespace, the field value, and optional trailing whitespace.

https://tools.ietf.org/html/rfc7230#section-3.2

Also, RFC 7540 (HTTP/2):

Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive fashion.

https://tools.ietf.org/html/rfc7540#section-8.1.2

What is private bytes, virtual bytes, working set?

You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.

A previous reply to this question has given a great explanation of what the various types are.

You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.

http://www.softwareverify.com/cpp/memory/index.html

Disclaimer: I designed Memory Validator.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

is inaccessible due to its protection level

In your Main method, you're trying to access, for instance, club (which is protected), when you should be accessing myclub which is the public property that you created.

Use jQuery to change an HTML tag?

This is my solution. It allows to toggle between tags.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title></title>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
<script type="text/javascript">_x000D_
_x000D_
function wrapClass(klass){_x000D_
 return 'to-' + klass;_x000D_
}_x000D_
_x000D_
function replaceTag(fromTag, toTag){_x000D_
 _x000D_
 /** Create selector for all elements you want to change._x000D_
   * These should be in form: <fromTag class="to-toTag"></fromTag>_x000D_
   */_x000D_
 var currentSelector = fromTag + '.' + wrapClass(toTag);_x000D_
_x000D_
 /** Select all elements */_x000D_
 var $selected = $(currentSelector);_x000D_
_x000D_
 /** If you found something then do the magic. */_x000D_
 if($selected.size() > 0){_x000D_
_x000D_
  /** Replace all selected elements */_x000D_
  $selected.each(function(){_x000D_
_x000D_
   /** jQuery current element. */_x000D_
   var $this = $(this);_x000D_
_x000D_
   /** Remove class "to-toTag". It is no longer needed. */_x000D_
   $this.removeClass(wrapClass(toTag));_x000D_
_x000D_
   /** Create elements that will be places instead of current one. */_x000D_
   var $newElem = $('<' + toTag + '>');_x000D_
_x000D_
   /** Copy all attributes from old element to new one. */_x000D_
   var attributes = $this.prop("attributes");_x000D_
   $.each(attributes, function(){_x000D_
    $newElem.attr(this.name, this.value);_x000D_
   });_x000D_
_x000D_
   /** Add class "to-fromTag" so you can remember it. */_x000D_
   $newElem.addClass(wrapClass(fromTag));_x000D_
_x000D_
   /** Place content of current element to new element. */_x000D_
   $newElem.html($this.html());_x000D_
_x000D_
   /** Replace old with new. */_x000D_
   $this.replaceWith($newElem);_x000D_
  });_x000D_
_x000D_
  /** It is possible that current element has desired elements inside._x000D_
    * If so you need to look again for them._x000D_
    */_x000D_
  replaceTag(fromTag, toTag);_x000D_
 }_x000D_
}_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<style type="text/css">_x000D_
 _x000D_
 section {_x000D_
  background-color: yellow;_x000D_
 }_x000D_
_x000D_
 div {_x000D_
  background-color: red;_x000D_
 }_x000D_
_x000D_
 .big {_x000D_
  font-size: 40px;_x000D_
 }_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<button onclick="replaceTag('div', 'section');">Section -> Div</button>_x000D_
<button onclick="replaceTag('section', 'div');">Div -> Section</button>_x000D_
_x000D_
<div class="to-section">_x000D_
 <p>Matrix has you!</p>_x000D_
 <div class="to-section big">_x000D_
  <p>Matrix has you inside!</p>_x000D_
 </div>_x000D_
</div>_x000D_
_x000D_
<div class="to-section big">_x000D_
 <p>Matrix has me too!</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

jQuery - on change input text

This is from a comment on the jQuery documentation page:

In older, pre-HTML5 browsers, "keyup" is definitely what you're looking for.

In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form.

$('element').bind('input',function);

How to read an http input stream

It looks like the documentation is just using readStream() to mean:

Ok, we've shown you how to get the InputStream, now your code goes in readStream()

So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.

Read response body in JAX-RS client from a post request

For my use case, none of the previous answers worked because I was writing a server-side unit test which was failing due the following error message as described in the Unable to Mock Glassfish Jersey Client Response Object question:

java.lang.IllegalStateException: Method not supported on an outbound message.
at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145)
at ...

This exception occurred on the following line of code:

String actJsonBody = actResponse.readEntity(String.class);

The fix was to turn the problem line of code into:

String actJsonBody = (String) actResponse.getEntity();

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My problem was took IBOutlet but didn't connect with interface builder and using in swift file.

Namespace for [DataContract]

In visual studio for .Net 4.0 framework,

  1. Try to add new reference to project.
  2. On .Net Tab, Search System.Runtime.Serialization.
  3. Now, you can use using System.Runtime.Serialization. And the error will not be shown.

Why is __dirname not defined in node REPL?

I was also trying to join my path using path.join(__dirname, 'access.log') but it was throwing the same error.

Here is how I fixed it:

I first imported the path package and declared a variable named __dirname, then called the resolve path method.

In CommonJS

var path = require("path");

var __dirname = path.resolve();

In ES6+

import path  from 'path';

const __dirname = path.resolve();

Happy coding.......

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

Directory-tree listing in Python

Here is a one line Pythonic version:

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

This code lists the full path of all files and directories in the given directory name.

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

Eclipse - java.lang.ClassNotFoundException

Carlos approach helped! Eclipse - java.lang.ClassNotFoundException

Try to check the classpath of the junit run configuration:

  1. Open your run configurations
  2. Click on the jUnit-Test you want to start
  3. go to the classpath tab
  4. Try to add a folder (click on user entries, click on advanced, click on add folders, click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source))

works for me.

Use :hover to modify the css of another class?

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.

302 is that the requested resource resides temporarily under a different URI.

Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.

This response is only cachable if indicated by a Cache-Control or Expires header field.

Why is it OK to return a 'vector' from a function?

To well understand the behaviour, you can run this code:

#include <iostream>

class MyClass
{
  public:
    MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
    ~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
    MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
    MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};

MyClass my_function()
{
  std::cout << "run my_function()" << std::endl;
  MyClass a;
  std::cout << "my_function is going to return a..." << std::endl;
  return a;
}

int main(int argc, char** argv)
{
  MyClass b = my_function();

  MyClass c;
  c = my_function();

  return 0;
}

The output is the following:

run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()

Note that this example was provided in C++03 context, it could be improved for C++ >= 11

How do you dynamically add elements to a ListView on Android?

instead of

listItems.add("New Item");
adapter.notifyDataSetChanged();

you can directly call

adapter.add("New Item");

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Worked for me, based on this answer

In Eclipse go to

Window->Preference->Android->DDMS

Then tick "Use ADBHOST" as "127.0.0.1".

Then just restart eclipse

When should I use Lazy<T>?

From MSDN:

Use an instance of Lazy to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

In addition to James Michael Hare's answer, Lazy provides thread-safe initialization of your value. Take a look at LazyThreadSafetyMode enumeration MSDN entry describing various types of thread safety modes for this class.

Angular 2.0 router not working on reloading the browser

The answer is quite tricky. If you use a plain old Apache Server (or IIS), you get the problem because the Angular pages do not exist for real. They are "computed" from the Angular route.

There are several ways to fix the issue. One is to use the HashLocationStrategy offered by Angular. But a sharp sign is added in the URL. This is mainly for compatibility with Angular 1 (I assume). The fact is the part after the sharp is not part of the URL (then the server resolves the part before the "#" sign). That can be perfect.

Here an enhanced method (based on the 404 trick). I assume you have a "distributed" version of your angular application (ng build --prod if you use Angular-CLI) and you access the pages directly with your server and PHP is enabled.

If your website is based on pages (Wordpress for example) and you have only one folder dedicated to Angular (named "dist" in my example), you can do something weird but, at the end, simple. I assume you have stored your Angular pages in "/dist" (with the according <BASE HREF="/dist/">). Now use a 404 redirection and the help of PHP.

In your Apache configuration (or in the .htaccess file of your angular application directory), you must add ErrorDocument 404 /404.php

The 404.php will start with the following code:

<?php
$angular='/dist/';
if( substr($_SERVER['REQUEST_URI'], 0, strlen($angular)) == $angular ){
    $index = $_SERVER['DOCUMENT_ROOT'] . $angular . "index.html";
    http_response_code(200);
    include $index;
    die;
}

// NOT ANGULAR...
echo "<h1>Not found.</h1>"

where $angular is the value stored in the HREF of your angular index.html.

The principle is quite simple, if Apache does not find the page, a 404 redirection is made to the PHP script. We just check if the page is inside the angular application directory. If it is the case, we just load the index.html directly (without redirecting): this is necessary to keep the URL unchanged. We also change the HTTP code from 404 to 200 (just better for crawlers).

What if the page does not exist in the angular application? Well, we use the "catch all" of the angular router (see Angular router documentation).

This method works with an embedded Angular application inside a basic website (I think it will be the case in future).

NOTES:

  • Trying to do the same with the mod_redirect (by rewriting the URLs) is not at all a good solution because files (like assets) have to be really loaded then it is much more risky than just using the "not found" solution.
  • Just redirecting using ErrorDocument 404 /dist/index.html works but Apache is still responding with a 404 error code (which is bad for crawlers).

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Swipe ListView item From right to left show delete button

I just got his working using the ViewSwitcher in a ListItem.

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ViewSwitcher
    android:id="@+id/list_switcher"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right"
    android:measureAllChildren="false" >
    <TextView
        android:id="@+id/tv_item_name"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:maxHeight="50dp"
        android:paddingLeft="10dp" />

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:clickable="false"
        android:gravity="center"
        >

    <Button
        android:id="@+id/b_edit_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"

         />
    <Button
        android:id="@+id/b_delete_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:background="@android:color/holo_red_dark"
        />
    </LinearLayout>
</ViewSwitcher>

In the ListAdapter: Implement OnclickListeners for the Edit and Delete button in the getView() method. The catch here is to get the position of the ListItem clicked inside the onClick methods. setTag() and getTag() methods are used for this.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.list_item, null);
        viewHolder.viewSwitcher=(ViewSwitcher)convertView.findViewById(R.id.list_switcher);
        viewHolder.itemName = (TextView) convertView
                .findViewById(R.id.tv_item_name);
        viewHolder.deleteitem=(Button)convertView.findViewById(R.id.b_delete_in_list);
        viewHolder.deleteItem.setTag(position);
        viewHolder.editItem=(Button)convertView.findViewById(R.id.b_edit_in_list);
        viewHolder.editItem.setTag(position);
        viewHolder.deleteItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.deleteItemList((Integer)v.getTag());
            }
        });

        viewHolder.editItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.editItemList(position);
            }
        });
        convertView.setTag(viewHolder);
} else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.itemName.setText(itemlist[position]);
return convertView;  
}

In the Fragment, Add a Gesture Listener to detect the Fling Gesture:

public class MyGestureListener extends SimpleOnGestureListener {
    private ListView list;

    public MyGestureListener(ListView list) {
        this.list = list;
    }

    // CONDITIONS ARE TYPICALLY VELOCITY OR DISTANCE

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // if (INSERT_CONDITIONS_HERE)

        ltor=(e2.getX()-e1.getX()>DELTA_X);
        if (showDeleteButton(e1))
        {
            return true;
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    private boolean showDeleteButton(MotionEvent e1) {
        int pos = list.pointToPosition((int) e1.getX(), (int) e1.getY());
        return showDeleteButton(pos);
    }

    private boolean showDeleteButton(int pos) {

        View child = list.getChildAt(pos);
        if (child != null) {
            Button delete = (Button) child
                    .findViewById(R.id.b_edit_in_list);
            ViewSwitcher viewSwitcher = (ViewSwitcher) child
                    .findViewById(R.id.host_list_switcher);
            TextView hostName = (TextView) child
                    .findViewById(R.id.tv_host_name);
            if (delete != null) {
                    viewSwitcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_left));
                    viewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_right));
                }

                viewSwitcher.showNext();
                // frameLayout.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return false;
    }
}

In the onCreateView method of the Fragment,

GestureDetector gestureDetector = new GestureDetector(getActivity(),
            new MyGestureListener(hostList));
    hostList.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }

        }
    });

This worked for me. Should refine it more.

How can I escape a double quote inside double quotes?

Store the double quote character in a variable:

dqt='"'
echo "Double quotes ${dqt}X${dqt} inside a double quoted string"

Output:

Double quotes "X" inside a double quoted string

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

After reading the documentation of VideoCapture. I figured out that you can tell VideoCapture, which frame to process next time we call VideoCapture.read() (or VideoCapture.grab()).

The problem is that when you want to read() a frame which is not ready, the VideoCapture object stuck on that frame and never proceed. So you have to force it to start again from the previous frame.

Here is the code

import cv2

cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
    cap = cv2.VideoCapture("./out.mp4")
    cv2.waitKey(1000)
    print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
    flag, frame = cap.read()
    if flag:
        # The frame is ready and already captured
        cv2.imshow('video', frame)
        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
        print str(pos_frame)+" frames"
    else:
        # The next frame is not ready, so we try to read it again
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
        print "frame is not ready"
        # It is better to wait for a while for the next frame to be ready
        cv2.waitKey(1000)

    if cv2.waitKey(10) == 27:
        break
    if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        # If the number of captured frames is equal to the total number of frames,
        # we stop
        break

Count the occurrences of DISTINCT values

SELECT name,COUNT(*) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

How do I read the file content from the Internal storage - Android App

Call To the following function with argument as you file path:

private String getFileContent(String targetFilePath){
           File file = new File(targetFilePath);
           try {
                    fileInputStream = new FileInputStream(file);
           }
           } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  Log.e("",""+e.printStackTrace());
           }
           StringBuilder sb;
           while(fileInputStream.available() > 0) {

                 if(null== sb)  sb = new StringBuilder();

            sb.append((char)fileInputStream.read());
           }
       String fileContent;
       if(null!=sb){
            fileContent= sb.toString();
            // This is your fileContent in String.


       }
       try {
          fileInputStream.close();
       }
       catch(Exception e){
           // TODO Auto-generated catch block
           Log.e("",""+e.printStackTrace());
       }
           return fileContent;
}

HTML5 Pre-resize images before uploading

Modification to the answer by Justin that works for me:

  1. Added img.onload
  2. Expand the POST request with a real example

function handleFiles()
{
    var dataurl = null;
    var filesToUpload = document.getElementById('photo').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
        img.src = e.target.result;

        img.onload = function () {
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);

            var MAX_WIDTH = 800;
            var MAX_HEIGHT = 600;
            var width = img.width;
            var height = img.height;

            if (width > height) {
              if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
              }
            } else {
              if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
              }
            }
            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);

            dataurl = canvas.toDataURL("image/jpeg");

            // Post the data
            var fd = new FormData();
            fd.append("name", "some_filename.jpg");
            fd.append("image", dataurl);
            fd.append("info", "lah_de_dah");
            $.ajax({
                url: '/ajax_photo',
                data: fd,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                    $('#form_photo')[0].reset();
                    location.reload();
                }
            });
        } // img.onload
    }
    // Load files into file reader
    reader.readAsDataURL(file);
}

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

In android studio you may see the following folder drawable xhdpi, drawable-hdpi, drawable-mdpi and more... You can put images of different dpi in these folder accordingly and android will take care which images should be draw according to the screen density of device.

NOTE: You have to put the images with the same name.

Best way to convert text files between character sets?

Simply change encoding of loaded file in IntelliJ IDEA IDE, on the right of status bar (bottom), where current charset is indicated. It prompts to Reload or Convert, use Convert. Make sure you backed up original file in advance.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Update MySQL using HTML Form and PHP

Use mysqli instead of mysql, and you need to pass the database name or schema:

before:

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

after:

$conn = mysql_connect($dbhost, $dbuser, $dbpass, $myDBname);

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

How do I print output in new line in PL/SQL?

You can concatenate the CR and LF:

chr(13)||chr(10)

(on windows)

or just:

chr(10)

(otherwise)

dbms_output.put_line('Hi,'||chr(13)||chr(10) ||'good' || chr(13)||chr(10)|| 'morning' ||chr(13)||chr(10) || 'friends');

Evaluating string "3*(4+2)" yield int 18

This is right to left execution, so need to use proper parathesis to execute expression

    // 2+(100/5)+10 = 32
    //((2.5+10)/5)+2.5 = 5
    // (2.5+10)/5+2.5 = 1.6666
    public static double Evaluate(String expr)
    {

        Stack<String> stack = new Stack<String>();

        string value = "";
        for (int i = 0; i < expr.Length; i++)
        {
            String s = expr.Substring(i, 1);
            char chr = s.ToCharArray()[0];

            if (!char.IsDigit(chr) && chr != '.' && value != "")
            {
                stack.Push(value);
                value = "";
            }

            if (s.Equals("(")) {

                string innerExp = "";
                i++; //Fetch Next Character
                int bracketCount=0;
                for (; i < expr.Length; i++)
                {
                    s = expr.Substring(i, 1);

                    if (s.Equals("("))
                        bracketCount++;

                    if (s.Equals(")"))
                        if (bracketCount == 0)
                            break;
                        else
                            bracketCount--;


                    innerExp += s;
                }

                stack.Push(Evaluate(innerExp).ToString());

            }
            else if (s.Equals("+")) stack.Push(s);
            else if (s.Equals("-")) stack.Push(s);
            else if (s.Equals("*")) stack.Push(s);
            else if (s.Equals("/")) stack.Push(s);
            else if (s.Equals("sqrt")) stack.Push(s);
            else if (s.Equals(")"))
            {
            }
            else if (char.IsDigit(chr) || chr == '.')
            {
                value += s;

                if (value.Split('.').Length > 2)
                    throw new Exception("Invalid decimal.");

                if (i == (expr.Length - 1))
                    stack.Push(value);

            }
            else
                throw new Exception("Invalid character.");

        }


        double result = 0;
        while (stack.Count >= 3)
        {

            double right = Convert.ToDouble(stack.Pop());
            string op = stack.Pop();
            double left = Convert.ToDouble(stack.Pop());

            if (op == "+") result = left + right;
            else if (op == "+") result = left + right;
            else if (op == "-") result = left - right;
            else if (op == "*") result = left * right;
            else if (op == "/") result = left / right;

            stack.Push(result.ToString());
        }


        return Convert.ToDouble(stack.Pop());
    }

How to change theme for AlertDialog

You can directly assign a theme when you initiate the Builder:

AlertDialog.Builder builder = new AlertDialog.Builder(
                    getActivity(), R.style.MyAlertDialogTheme);

Then customize your theme in your values/styles.xml

<!-- Alert Dialog -->
<style name="MyAlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:colorBackground">@color/alertDialogBackground</item>
    <item name="android:windowBackground">@color/alertDialogBackground</item>
</style>

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Use latest version of Internet Explorer in the webbrowser control

Combine the answers of RooiWillie and MohD
and remember to run your app with administrative right.

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

RegistryKey Regkey = null;
try
{
    int BrowserVer, RegVal;

    // get the installed IE version
    using (WebBrowser Wb = new WebBrowser())
        BrowserVer = Wb.Version.Major;

    // set the appropriate IE version
    if (BrowserVer >= 11)
        RegVal = 11001;
    else if (BrowserVer == 10)
        RegVal = 10001;
    else if (BrowserVer == 9)
        RegVal = 9999;
    else if (BrowserVer == 8)
        RegVal = 8888;
    else
        RegVal = 7000;

    //For 64 bit Machine 
    if (Environment.Is64BitOperatingSystem)
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
    else  //For 32 bit Machine 
        Regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

    //If the path is not correct or 
    //If user't have priviledges to access registry 
    if (Regkey == null)
    {
        MessageBox.Show("Registry Key for setting IE WebBrowser Rendering Address Not found. Try run the program with administrator's right.");
        return;
    }

    string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

    //Check if key is already present 
    if (FindAppkey == RegVal.ToString())
    {
        Regkey.Close();
        return;
    }

    Regkey.SetValue(appName, RegVal, RegistryValueKind.DWord);
}
catch (Exception ex)
{
    MessageBox.Show("Registry Key for setting IE WebBrowser Rendering failed to setup");
    MessageBox.Show(ex.Message);
}
finally
{
    //Close the Registry 
    if (Regkey != null)
        Regkey.Close();
}

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).

In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.

Returning to your query:

1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).

define REGEX_DATE = "'your regex pattern goes here'"

Don't forget a single quote inside a double quote around your Regex :-)

A comprehensive thread about Regex date validation you'll find here.

2. Use it as the first CASE condition:

To use Regex validation in the SELECT statement, you cannot use REGEXP_LIKE (it's only valid in WHERE. It took me a long time to understand why my code was not working. So it's certainly worth a note.

Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0 .

    DEFINE REGEX_DATE = "'your regex pattern goes here'"

    SELECT   c.contract_num,
         CASE
            WHEN REGEXP_INSTR(c.event_dt, &REGEX_DATE) = 0 THEN NULL
            WHEN   (  MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                    - MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                 / COUNT (c.event_occurrence) < 32
            THEN
              'Monthly'
            WHEN       (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) >= 32
                 AND   (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) < 91
            THEN
              'Quarterley'
            ELSE
              'Yearly'
         END
FROM     ps_ca_bp_events c
GROUP BY c.contract_num;

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

Session state can only be used when enableSessionState is set to true either in a configuration

This error was raised for me because of an unhandled exception thrown in the Public Sub New() (Visual Basic) constructor function of the Web Page in the code behind.

If you implement the constructor function wrap the code in a Try/Catch statement and see if it solves the problem.

The application has stopped unexpectedly: How to Debug?

I'm an Eclipse/Android beginner as well, but hopefully my simple debugging process can help...

You set breakpoints in Eclipse by right-clicking next to the line you want to break at and selecting "Toggle Breakpoint". From there you'll want to select "Debug" rather than the standard "Run", which will allow you to step through and so on. Use the filters provided by LogCat (referenced in your tutorial) so you can target the messages you want rather than wading through all the output. That will (hopefully) go a long way in helping you make sense of your errors.

As for other good tutorials, I was searching around for a few myself, but didn't manage to find any gems yet.

Trim spaces from start and end of string

Just use string.trim() method. It's supported by all major browsers. Reference here: http://www.w3schools.com/jsref/jsref_trim_string.asp

Scatter plot with error bars

To summarize Laryx Decidua's answer:

define and use a function like the following

plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
  if (is.null(ylim))
    ylim <- c(min(y-err), max(y+err))
  plot(x, y, ylim=ylim, pch=19, ...)
  arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}

where one can override the automatic ylim, and also pass extra parameters such as main, xlab, ylab.

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

Do we need type="text/css" for <link> in HTML5

For LINK elements the content-type is determined in the HTTP-response so the type attribute is superfluous. This is OK for all browsers.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

how to run vibrate continuously in iphone?

The above answers are good and you can do it in a simple way also.

You can use the recursive method calls.

func vibrateTheDeviceContinuously() throws {
        
        // Added concurrent queue for next & Vibrate device
        DispatchQueue.global(qos: .utility).async {
            
            //Vibrate the device
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

            self.incrementalCount += 1
            usleep(800000) // if you don't want, remove this line.

            do {
                if let isKeepBuzzing = self.iShouldKeepBuzzing , isKeepBuzzing == true {
                    try self.vibrateTheDeviceContinuously()
                }
                 else {
                    return 
                 }
                
            } catch  {
                //Exception handle
               print("exception")
            }
            
        }
    }

To stop the device vibration use the following line.

self.iShouldKeepBuzzing = false

What is the purpose of the : (colon) GNU Bash builtin?

Self-documenting functions

You can also use : to embed documentation in a function.

Assume you have a library script mylib.sh, providing a variety of functions. You could either source the library (. mylib.sh) and call the functions directly after that (lib_function1 arg1 arg2), or avoid cluttering your namespace and invoke the library with a function argument (mylib.sh lib_function1 arg1 arg2).

Wouldn't it be nice if you could also type mylib.sh --help and get a list of available functions and their usage, without having to manually maintain the function list in the help text?

#!/bin/bash

# all "public" functions must start with this prefix
LIB_PREFIX='lib_'

# "public" library functions
lib_function1() {
    : This function does something complicated with two arguments.
    :
    : Parameters:
    : '   arg1 - first argument ($1)'
    : '   arg2 - second argument'
    :
    : Result:
    : "   it's complicated"

    # actual function code starts here
}

lib_function2() {
    : Function documentation

    # function code here
}

# help function
--help() {
    echo MyLib v0.0.1
    echo
    echo Usage: mylib.sh [function_name [args]]
    echo
    echo Available functions:
    declare -f | sed -n -e '/^'$LIB_PREFIX'/,/^}$/{/\(^'$LIB_PREFIX'\)\|\(^[ \t]*:\)/{
        s/^\('$LIB_PREFIX'.*\) ()/\n=== \1 ===/;s/^[ \t]*: \?['\''"]\?/    /;s/['\''"]\?;\?$//;p}}'
}

# main code
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    # the script was executed instead of sourced
    # invoke requested function or display help
    if [ "$(type -t - "$1" 2>/dev/null)" = function ]; then
        "$@"
    else
        --help
    fi
fi

A few comments about the code:

  1. All "public" functions have the same prefix. Only these are meant to be invoked by the user, and to be listed in the help text.
  2. The self-documenting feature relies on the previous point, and uses declare -f to enumerate all available functions, then filters them through sed to only display functions with the appropriate prefix.
  3. It is a good idea to enclose the documentation in single quotes, to prevent undesired expansion and whitespace removal. You'll also need to be careful when using apostrophes/quotes in the text.
  4. You could write code to internalize the library prefix, i.e. the user only has to type mylib.sh function1 and it gets translated internally to lib_function1. This is an exercise left to the reader.
  5. The help function is named "--help". This is a convenient (i.e. lazy) approach that uses the library invoke mechanism to display the help itself, without having to code an extra check for $1. At the same time, it will clutter your namespace if you source the library. If you don't like that, you can either change the name to something like lib_help or actually check the args for --help in the main code and invoke the help function manually.

Psql could not connect to server: No such file or directory, 5432 error?

I recommend you should clarify port that postgres. In my case I didn't know which port postgres was running on.

lsof -i | grep 'post'

then you can know which port is listening.

psql -U postgres -p "port_in_use"

with port option, might be answer. you can use psql.

How to install python3 version of package via pip on Ubuntu?

Well, on ubuntu 13.10/14.04, things are a little different.

Install

$ sudo apt-get install python3-pip

Install packages

$ sudo pip3 install packagename

NOT pip-3.3 install

Is there a way to style a TextView to uppercase all of its letters?

PixlUI project allows you to use textAllCaps in any textview or subclass of textview including: Button, EditText AutoCompleteEditText Checkbox RadioButton and several others.

You will need to create your textviews using the pixlui version rather than the ones from the android source, meaning you have to do this:

<com.neopixl.pixlui.components.textview.TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        pixlui:textAllCaps="true" />

PixlUI also allows you to set a custom typeface/font which you put in your assets folder.

I'm working on a Gradle fork of the PixlUI framework which uses gradle and allows one to specify textAllCaps as well as the typeface from styles rather than requiring them inline as the original project does.

Limiting the output of PHP's echo to 200 characters

echo strlen($row['style-info'])<=200 ? $row['style-info'] : substr($row['style-info'],0,200).'...';

How to click a href link using Selenium

 webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

The above line works fine. Please remove the space after href.

Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

Calculate age given the birth date in the format YYYYMMDD

$("#birthday").change(function (){


var val=this.value;

var current_year=new Date().getFullYear();
if(val!=null){
    var Split = val.split("-");
    var birth_year=parseInt(Split[2]);

    if(parseInt(current_year)-parseInt(birth_year)<parseInt(18)){

  $("#maritial_status").attr('disabled', 'disabled');
        var val2= document.getElementById("maritial_status");
        val2.value = "Not Married";
        $("#anniversary").attr('disabled', 'disabled');
        var val1= document.getElementById("anniversary");
        val1.value = "NA";

    }else{
        $("#maritial_status").attr('disabled', false);
        $("#anniversary").attr('disabled', false);

    }
}
});

Selecting the last value of a column

This one works for me:

=INDEX(I:I;MAX((I:I<>"")*(ROW(I:I))))

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

iOS Launching Settings -> Restrictions URL Scheme

AS @Nix Wang's ANSWER THIS IS NOT WORK IN IOS 10


WARNING: This method will not work for devices running iOS 5.1 and greater - See Hlung's comment below.

It's possible that the path component has a different name than the actual section, but it's also possible that you can't currently access that section straight from a URL. I found a list of possible URLs and Restrictions is not on it, maybe it's just not found out yet.

List of currently known URLs in the Settings app:

  • prefs:root=General&path=About
  • prefs:root=General&path=ACCESSIBILITY
  • prefs:root=AIRPLANE_MODE
  • prefs:root=General&path=AUTOLOCK
  • prefs:root=General&path=USAGE/CELLULAR_USAGE
  • prefs:root=Brightness
  • prefs:root=General&path=Bluetooth
  • prefs:root=General&path=DATE_AND_TIME
  • prefs:root=FACETIME
  • prefs:root=General
  • prefs:root=General&path=Keyboard
  • prefs:root=CASTLE
  • prefs:root=CASTLE&path=STORAGE_AND_BACKUP
  • prefs:root=General&path=INTERNATIONAL
  • prefs:root=LOCATION_SERVICES
  • prefs:root=ACCOUNT_SETTINGS
  • prefs:root=MUSIC
  • prefs:root=MUSIC&path=EQ
  • prefs:root=MUSIC&path=VolumeLimit
  • prefs:root=General&path=Network
  • prefs:root=NIKE_PLUS_IPOD
  • prefs:root=NOTES
  • prefs:root=NOTIFICATIONS_ID
  • prefs:root=Phone
  • prefs:root=Photos
  • prefs:root=General&path=ManagedConfigurationList
  • prefs:root=General&path=Reset
  • prefs:root=Sounds&path=Ringtone
  • prefs:root=Safari
  • prefs:root=General&path=Assistant
  • prefs:root=Sounds
  • prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • prefs:root=STORE
  • prefs:root=TWITTER
  • prefs:root=General&path=USAGE
  • prefs:root=VIDEO
  • prefs:root=General&path=Network/VPN
  • prefs:root=Wallpaper
  • prefs:root=WIFI
  • prefs:root=INTERNET_TETHERING

How to close <img> tag properly?

This one is valid HTML5 and it is absolutely fine without closing it. It is a so-called void element:

<img src='stackoverflow.png'>

The following are valid XHTML tags. They have to be closed. The later one is also fine in HTML 5:

<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />

How to select a schema in postgres when using psql?

\l - Display database
\c - Connect to database
\dn - List schemas
\dt - List tables inside public schemas
\dt schema1. - List tables inside particular schemas. For eg: 'schema1'.

How do you make a LinearLayout scrollable?

You need to wrap your linear layout with a scroll view

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


    </LinearLayout>
</ScrollView>

Can one do a for each loop in java in reverse order?

AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.

You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.

This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.

Variable name as a string in Javascript

When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.

Run in jsfiddle

var jack = 'jill';
function window_getVarName(what)
{
  for (var name in window)
  {
    if (window[name]==what)
    return(name);
  }
  return("");
}
document.write(window_getVarName(jack));

Will write to the window 'jack'.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

The namespace name http://www.w3.org/1999/xhtml 
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail

PHP shell_exec() vs exec()

shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See

How to stop console from closing on exit?

You can simply press Ctrl+F5 instead of F5 to run the built code. Then it will prompt you to press any key to continue. Or you can use this line -> system("pause"); at the end of the code to make it wait until you press any key.

However, if you use the above line, system("pause"); and press Ctrl+F5 to run, it will prompt you twice!

How to dump a dict to a json file?

with pretty-print format:

import json

with open(path_to_file, 'w') as file:
    json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
    file.write(json_string)

HttpRequest maximum allowable size in tomcat?

Although other answers include some of the following information, this is the absolute minimum that needs to be changed on EC2 instances, specifically regarding deployment of large WAR files, and is the least likely to cause issues during future updates. I've been running into these limits about every other year due to the ever-increasing size of the Jenkins WAR file (now ~72MB).

More specifically, this answer is applicable if you encounter a variant of the following error in catalina.out:

SEVERE [https-jsse-nio-8443-exec-17] org.apache.catalina.core.ApplicationContext.log HTMLManager:
FAIL - Deploy Upload Failed, Exception:
[org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:
the request was rejected because its size (75333656) exceeds the configured maximum (52428800)]

On Amazon EC2 Linux instances, the only file that needs to be modified from the default installation of Tomcat (sudo yum install tomcat8) is:

/usr/share/tomcat8/webapps/manager/WEB-INF/web.xml

By default, the maximum upload size is exactly 50MB:

<multipart-config>
  <!-- 50MB max -->
  <max-file-size>52428800</max-file-size>
  <max-request-size>52428800</max-request-size>
  <file-size-threshold>0</file-size-threshold>
</multipart-config>

There are only two values that need to be modified (max-file-size and max-request-size):

<multipart-config>
  <!-- 100MB max -->
  <max-file-size>104857600</max-file-size>
  <max-request-size>104857600</max-request-size>
  <file-size-threshold>0</file-size-threshold>
</multipart-config>

When Tomcat is upgraded on these instances, the new version of the manager web.xml will be placed in web.xml.rpmnew, so any modifications to the original file will not be overwritten during future updates.

Get the difference between dates in terms of weeks, months, quarters, and years

All the existing answers are imperfect (IMO) and either make assumptions about the desired output or don't provide flexibility for the desired output.

Based on the examples from the OP, and the OP's stated expected answers, I think these are the answers you are looking for (plus some additional examples that make it easy to extrapolate).

(This only requires base R and doesn't require zoo or lubridate)

Convert to Datetime Objects

date_strings = c("14.01.2013", "26.03.2014")
datetimes = strptime(date_strings, format = "%d.%m.%Y") # convert to datetime objects

Difference in Days

You can use the diff in days to get some of our later answers

diff_in_days = difftime(datetimes[2], datetimes[1], units = "days") # days
diff_in_days
#Time difference of 435.9583 days

Difference in Weeks

Difference in weeks is a special case of units = "weeks" in difftime()

diff_in_weeks = difftime(datetimes[2], datetimes[1], units = "weeks") # weeks
diff_in_weeks
#Time difference of 62.27976 weeks

Note that this is the same as dividing our diff_in_days by 7 (7 days in a week)

as.double(diff_in_days)/7
#[1] 62.27976

Difference in Years

With similar logic, we can derive years from diff_in_days

diff_in_years = as.double(diff_in_days)/365 # absolute years
diff_in_years
#[1] 1.194406

You seem to be expecting the diff in years to be "1", so I assume you just want to count absolute calendar years or something, which you can easily do by using floor()

# get desired output, given your definition of 'years'
floor(diff_in_years)
#[1] 1

Difference in Quarters

# get desired output for quarters, given your definition of 'quarters'
floor(diff_in_years * 4)
#[1] 4

Difference in Months

Can calculate this as a conversion from diff_years

# months, defined as absolute calendar months (this might be what you want, given your question details)
months_diff = diff_in_years*12
floor(month_diff)
#[1] 14

I know this question is old, but given that I still had to solve this problem just now, I thought I would add my answers. Hope it helps.

What's the difference between TRUNCATE and DELETE in SQL

By issuing a TRUNCATE TABLE statement, you are instructing SQL Server to delete every record within a table, without any logging or transaction processing taking place.

How can I get Docker Linux container information from within the container itself?

This will get the full container id from within a container:

cat /proc/self/cgroup | grep "cpu:/" | sed 's/\([0-9]\):cpu:\/docker\///g'

Map<String, String>, how to print both the "key string" and "value string" together

final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
        .stream()
        //depending on how you want to join K and V use different delimiter
        .map(entry -> 
        String.join(":", entry.getKey(),entry.getValue()))
        .forEach(System.out::println);

how to convert java string to Date object

The concise version:

String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);  

Add a try/catch block for a ParseException to ensure the format is a valid date.

How to remove all .svn directories from my application directories

In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

Auto generate function documentation in Visual Studio

Make that "three single comment-markers"

In C# it's ///

which as default spits out:

/// <summary>
/// 
/// </summary>
/// <returns></returns>

Here's some tips on editing VS templates.

Click event doesn't work on dynamically generated elements

I found two solutions at the jQuery's documentation:

First: Use delegate on Body or Document

E.g:

 $("body").delegate('.test', 'click', function(){
 ...
  alert('test');
 });

Why?

Answer: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. link: http://api.jquery.com/delegate/

Second: Put the your function at the "$( document )", using "on" and attach it to the element that you want to trigger this. The first parameter is the "event handler", the second: the element and the third: the function. E.g:

 $( document ).on( 'click', '.test', function () {
 ...
  alert('test');
 });

Why?

Answer: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next ... link: https://api.jquery.com/on/

Insert line after first match using sed

Try doing this using GNU sed:

sed '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

if you want to substitute in-place, use

sed -i '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

Output

CLIENTSCRIPT="foo"
CLIENTSCRIPT2="hello"
CLIENTFILE="bar"

Doc

  • see sed doc and search \a (append)

Why does this "Slow network detected..." log appear in Chrome?

I also had the same errors with fontawesome's fonts. Then I downloaded the lastest fontawesome's fonts and replace to the old fonts. And the errors are gone.

How to sort findAll Doctrine's method?

Simple:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findBy(
    array(),
    array('username' => 'ASC')
);

How to change port for jenkins window service when 8080 is being used

  1. Go to the directory where you installed Jenkins (by default, it's under Program Files/Jenkins)
  2. Open the Jenkins.xml configuration file
  3. Search --httpPort=8080 and replace the 8080 with the new port number that you wish
  4. Restart Jenkins for changes to take effect

Enable CORS in Web API 2

Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.

how to do file upload using jquery serialization

A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {
    $('#ifoftheform').ajaxForm(function(result) {
        alert('the form was successfully processed');
    });
});

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.

jQuery select change event get selected option

See official API documentation https://api.jquery.com/selected-selector/

This good works:

$( "select" ).on('change',function() {
  var str = "";
  // For multiple choice
  $( "select option:selected" ).each(function() {
    str += $( this ).val() + " "; 
  });
});

and

$( "select" ).on('change',function() {
  // For unique choice
  var selVal = $( "select option:selected" ).val(); 
});

and be easy for unique choice

var SelVal = $( "#idSelect option:selected" ).val();

How to implement zoom effect for image view in android?

Below is the code for ImageFullViewActivity Class

 public class ImageFullViewActivity extends AppCompatActivity {

        private ScaleGestureDetector mScaleGestureDetector;
        private float mScaleFactor = 1.0f;
        private ImageView mImageView;

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

            mImageView = (ImageView) findViewById(R.id.imageView);
            mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

        }

        @Override
        public boolean onTouchEvent(MotionEvent motionEvent) {
            mScaleGestureDetector.onTouchEvent(motionEvent);
            return true;
        }

        private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
            @Override
            public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
                mScaleFactor *= scaleGestureDetector.getScaleFactor();
                mScaleFactor = Math.max(0.1f,
                        Math.min(mScaleFactor, 10.0f));
                mImageView.setScaleX(mScaleFactor);
                mImageView.setScaleY(mScaleFactor);
                return true;
            }
        }
    }

jQuery UI Dialog OnBeforeUnload

This works for me:

_x000D_
_x000D_
window.addEventListener("beforeunload", function(event) {_x000D_
  event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_
_x000D_
_x000D_

Is there StartsWith or Contains in t sql with variables?

It seems like what you want is http://msdn.microsoft.com/en-us/library/ms186323.aspx.

In your example it would be (starts with):

set @isExpress = (CharIndex('Express Edition', @edition) = 1)

Or contains

set @isExpress = (CharIndex('Express Edition', @edition) >= 1)

cut or awk command to print first field of first row

awk, sed, pipe, that's heavy

set `cat /etc/*release`; echo $1

CSS Box Shadow Bottom Only

try this to get the box-shadow under your full control.

    <html>

    <head>
        <style> 
            div {
                width:300px;
                height:100px;
                background-color:yellow;
                box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
           }
        </style>
    </head>
    <body>
        <div>
        </div>
    </body>

    </html>

this would apply to outer box-shadow as well.

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

Java Package Does Not Exist Error

You need to have org/name dirs at /usr/share/stuff and place your org.name package sources at this dir.

Laravel 5.5 ajax call 419 (unknown status)

just serialize the form data and get your problem solved.

data: $('#form_id').serialize(),

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Why is <deny users="?" /> included in the following example?

ASP.NET grants access from the configuration file as a matter of precedence. In case of a potential conflict, the first occurring grant takes precedence. So,

deny user="?" 

denies access to the anonymous user. Then

allow users="dan,matthew" 

grants access to that user. Finally, it denies access to everyone. This shakes out as everyone except dan,matthew is denied access.

Edited to add: and as @Deviant points out, denying access to unauthenticated is pointless, since the last entry includes unauthenticated as well. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog

Disallow Twitter Bootstrap modal window from closing

I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.

Example:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

OR if you are using JavaScript:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

How do I install a pip package globally instead of locally?

Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

How would you make two <div>s overlap?

If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:

#logo {
    float: left;
    margin: 0 10px 10px 20px;
}

#content {
    margin: 10px 0 0 10px;
}

or whatever margin you want.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

This error is generally caused by one of your Chrome extensions.

I recommend installing this One-Click Extension Disabler, I use it with the keyboard shortcut COMMAND (?) + SHIFT (?) + D — to quickly disable/enable all my extensions.

Once the extensions are disabled this error message should go away.

Peace! ??

Ineligible Devices section appeared in Xcode 6.x.x

You can try below solutions to run build in your device.

  1. Restart your iOS device (If device is recently updated) and your Xcode.

  2. Make Sure that in build settings "iOS Deployment Target" is <= the version of your iDevice. enter image description here

Otherwise you can goto - Product > Destination, select your device which would be showing as ineligible device.You will be able to select your device and run your build.

I also came across that if you have the iOS 8.4 then your Xcode doesn't have the SDK for iOS 8.4 due to which devices show as ineligible. To solve this issue

Download Xcode 6.4

Priority queue in .Net

As mentioned in Microsoft Collections for .NET, Microsoft has written (and shared online) 2 internal PriorityQueue classes within the .NET Framework. Their code is available to try out.

As @mathusum-mut commented, there is a bug in one of Microsoft's internal PriorityQueue classes (the SO community has, of course, provided fixes for it): Bug in Microsoft's internal PriorityQueue<T>?

How do I force a favicon refresh?

I recently restored my bookmarks and was looking for a way to restore the FavIcons without visiting each page. My search brought me to this thread.

For those in a similar circumstance merely download the FAVICON RELOADER addon. Once installed you will find the "reload favorite icons" command in your BOOKMARKS dropdown menu.

https://addons.mozilla.org/en-US/firefox/addon/faviconreloader/?src=api

How to find and replace all occurrences of a string recursively in a directory tree?

Try this command:

/home/user/ directory - find ./ -type f \
-exec sed -i -e 's/a.example.com/b.example.com/g' {} \;

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I too am frustrated by the outofmemory bug. And yes, I too found that this error pops up a lot when scaling images. At first I tried creating image sizes for all densities, but I found this substantially increased the size of my app. So I'm now just using one image for all densities and scaling my images.

My application would throw an outofmemory error whenever the user went from one activity to another. Setting my drawables to null and calling System.gc() didn't work, neither did recycling my bitmapDrawables with getBitMap().recycle(). Android would continue to throw the outofmemory error with the first approach, and it would throw a canvas error message whenever it tried using a recycled bitmap with the second approach.

I took an even third approach. I set all views to null and the background to black. I do this cleanup in my onStop() method. This is the method that gets called as soon as the activity is no longer visible. If you do it in the onPause() method, users will see a black background. Not ideal. As for doing it in the onDestroy() method, there is no guarantee that it will get called.

To prevent a black screen from occurring if the user presses the back button on the device, I reload the activity in the onRestart() method by calling the startActivity(getIntent()) and then finish() methods.

Note: it's not really necessary to change the background to black.

Delete all the records

Use the DELETE statement

Delete From <TableName>

Eg:

Delete from Student;

What is "Advanced" SQL?

Some "Advanced" features

  • recursive queries
  • windowing/ranking functions
  • pivot and unpivot
  • performance tuning

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

How to display all methods of an object?

var methods = [];
for (var m in obj) {
    if (typeof obj[m] == "function") {
        methods.push(m);
    }
}
alert(methods.join(","));

This way, you will get all methods that you can call on obj. This includes the methods that it "inherits" from its prototype (like getMethods() in java). If you only want to see those methods defined directly by obj you can check with hasOwnProperty:

var methods = [];
for (var m in obj) {        
    if (typeof obj[m] == "function" && obj.hasOwnProperty(m)) {
        methods.push(m);
    }
}
alert(methods.join(","));

Build .NET Core console application to output an EXE

For debugging purposes, you can use the DLL file. You can run it using dotnet ConsoleApp2.dll. If you want to generate an EXE file, you have to generate a self-contained application.

To generate a self-contained application (EXE in Windows), you must specify the target runtime (which is specific to the operating system you target).

Pre-.NET Core 2.0 only: First, add the runtime identifier of the target runtimes in the .csproj file (list of supported RIDs):

<PropertyGroup>
    <RuntimeIdentifiers>win10-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</PropertyGroup>

The above step is no longer required starting with .NET Core 2.0.

Then, set the desired runtime when you publish your application:

dotnet publish -c Release -r win10-x64
dotnet publish -c Release -r ubuntu.16.10-x64

How to access model hasMany Relation with where condition?

I think that this is the correct way:

class Game extends Eloquent {
    // many more stuff here

    // relation without any constraints ...works fine 
    public function videos() {
        return $this->hasMany('Video');
    }

    // results in a "problem", se examples below
    public function available_videos() {
        return $this->videos()->where('available','=', 1);
    }
}

And then you'll have to

$game = Game::find(1);
var_dump( $game->available_videos()->get() );

Vertical and horizontal align (middle and center) with CSS

This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.

The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.

Example: http://jsbin.com/ipawe/edit

Basic CSS:

#mydiv { 
    position: absolute;
    top: 50%;
    left: 50%;
    height: 400px;
    width: 700px;
    margin-top: -200px; /* -(1/2 height) */
    margin-left: -350px; /* -(1/2 width) */
  }

How to make an "alias" for a long path?

Put the following line in your myscript

set myFold = '~/Files/Scripts/Main'

In the terminal use

source myscript
cd $myFold

Fatal error: Call to undefined function curl_init()

Experienced this on ubuntu 16.04 running PHP 7.1.14. To resolve,first put this in a script and execute. It will return true if curl is installed and enabled,otherwise, it will return false.

<?php
    var_dump(extension_loaded('curl'));
?>

If it returns false, run

sudo apt-get install php7.1-curl

And finally,

sudo service apache2 restart

After the restart, the script will return true and hopefully, your error should be resolved.

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

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

How can I remove the outline around hyperlinks images?

Please note that the focus styles are there for a reason: if you decide to remove them, people who navigate via the keyboard only don't know what's in focus anymore, so you're hurting the accessibility of your website.

(Keeping them in place also helps power users that don't like to use their mouse)

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

Storing sex (gender) in database

CREATE TABLE Admission (
    Rno INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(25) NOT NULL,
    Gender ENUM('M','F'),
    Boolean_Valu boolean,
    Dob Date,
    Fees numeric(7,2) NOT NULL
);




insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;

enter link description here

"No such file or directory" but it exists

Below command worked on 16.4 Ubuntu

This issue comes when your .sh file is corrupt or not formatted as per unix protocols.

dos2unix converts the .sh file to Unix format!

sudo apt-get install dos2unix -y
dos2unix test.sh
sudo chmod u+x test.sh 
sudo ./test.sh

Display a loading bar before the entire page is loaded

Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

<div class="loader"></div>

CSS .

.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);

jQuery

$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

enter image description here

Xpath for href element

This works properly try this code-

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was getting this from webpack lazy loading like this

import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: Loader, // warning
});
render() {
    return <WishlistPageComponent />;
}


// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: '', // all good
});    

MySQL query to select events between start/end date

I am assuming that active events in a time period means at least one day of the event falls inside the time period. This is a simple "find overlapping dates" problem and there is a generic solution:

-- [@d1, @d2] is the date range to check against
SELECT * FROM events WHERE @d2 >= start AND end >= @d1

Some tests:

-- list of events
SELECT * FROM events;
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    1 | 2013-06-14 | 2013-06-14 |
|    2 | 2013-06-15 | 2013-08-21 |
|    3 | 2013-06-22 | 2013-06-25 |
|    4 | 2013-07-01 | 2013-07-10 |
|    5 | 2013-07-30 | 2013-07-31 |
+------+------------+------------+

-- events between [2013-06-01, 2013-06-15]
SELECT * FROM events WHERE '2013-06-15' >= start AND end >= '2013-06-01';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    1 | 2013-06-14 | 2013-06-14 |
|    2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+

-- events between [2013-06-16, 2013-06-30]
SELECT * FROM events WHERE '2013-06-30' >= start AND end >= '2013-06-16';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
|    3 | 2013-06-22 | 2013-06-25 |
+------+------------+------------+

-- events between [2013-07-01, 2013-07-01]
SELECT * FROM events WHERE '2013-07-01' >= start AND end >= '2013-07-01';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
|    4 | 2013-07-01 | 2013-07-10 |
+------+------------+------------+

-- events between [2013-07-11, 2013-07-29]
SELECT * FROM events WHERE '2013-07-29' >= start AND end >= '2013-07-11';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+

How to update data in one table from corresponding data in another table in SQL Server 2005

If the two databases are on the same server, you should be able to create a SQL statement something like this:

UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
   Test1.dbo.Employee.EmployeeID = emp2.EmployeeID

From your post, I'm not quite clear whether you want to update Test1.dbo.Employee with the values from Test2.dbo.Employee (that's what my query does), or the other way around (since you mention the db on Test1 was the new table......)

Adding rows dynamically with jQuery

Untested. Modify to suit:

$form = $('#my-form');

$rows = $form.find('.person-input-row');

$('button#add-new').click(function() {

    $rows.find(':first').clone().insertAfter($rows.find(':last'));

    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);


});

This is better than copying innerHTML because you will lose all attached events etc.

Why is document.body null in my javascript?

Browser parses your html from top down, your script runs before body is loaded. To fix put script after body.

  <html>
  <head>
       <title> Javascript Tests </title> 
  </head>
 <body>
 </body>
  <script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>
</html>

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

For Unix Users

find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;

Right-click your project and choose Update Dependencies

For Windows

  • CD (change directory) to .m2\repository
  • execute the command for /r %i in (*.lastUpdated) do del %i
  • Then right-click your project and choose Update Dependencies

How to set up a Web API controller for multipart/form-data

You're getting HTTP 415 "The request entity's media type 'multipart/form-data' is not supported for this resource." because you haven't mention the correct content type in your request.

How do I append to a table in Lua

I'd personally make use of the table.insert function:

table.insert(a,"b");

This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

Find package name for Android apps to use Intent to launch Market app from web

If you want this information in your phone, then best is to use an app like 'APKit' that shows the full package name of each app in you phone. This information can then be used in your phone.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

How do I get a reference to the app delegate in Swift?

Convenience Constructors

Add in AppDelegate Class at the end of code

Swift 5

func appDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

To use AppDelegate reference in your class?


Call AppDelegate Method

appDelegate().setRoot()

How to get complete current url for Cakephp

In View:

Blank URL: <?php echo $this->Html->Url('/') ?>
Blank Full Url: <?php echo $this->Html->Url('/', true) ?>
Current URL: <?php echo $this->Html->Url($this->here) ?>
Current Full URL: <?php echo $this->Html->Url($this->here, true) ?>

In Controller

Blank URL: <?php echo Router::url('/') ?>
Blank Full Url: <?php echo Router::url('/', true) ?>
Current URL: <?php echo Router::url($this->request->here()) ?>
Current Full URL: <?php echo Router::url($this->request->here(), true) ?>

How can I remove Nan from list Python/NumPy

The question has changed, so to has the answer:

Strings can't be tested using math.isnan as this expects a float argument. In your countries list, you have floats and strings.

In your case the following should suffice:

cleanedList = [x for x in countries if str(x) != 'nan']

Old answer

In your countries list, the literal 'nan' is a string not the Python float nan which is equivalent to:

float('NaN')

In your case the following should suffice:

cleanedList = [x for x in countries if x != 'nan']

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Twitter Bootstrap Datepicker within modal window

Try to change z-index value for .modal and .modal-backdrop less than .datepicker z-index value.

Eclipse not recognizing JVM 1.8

JRE is a Run-Time Environment for running Java stuffs on your machine. What Eclipse needs is JDK as a Development Kit.

Install the latest JDK (and not JRE) from http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html and you should be good on Mac!

jQuery append() vs appendChild()

appendChild is a DOM vanilla-js function.

append is a jQuery function.

They each have their own quirks.

How to center canvas in html5

You can give your canvas the ff CSS properties:

#myCanvas
{
    display: block;
    margin: 0 auto;
}

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

How to echo or print an array in PHP?

Loop through and print all the values of an associative array, you could use a foreach loop, like this:

foreach($results as $x => $value) {
    echo $value;
}

Running interactive commands in Paramiko

You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:

def SpecialConfirmation(command, message, reply):
    net_connect.config_mode()    # To enter config mode
    net_connect.remote_conn.sendall(str(command)+'\n' )
    time.sleep(3)
    output = net_connect.remote_conn.recv(65535).decode('utf-8')
    ReplyAppend=''
    if str(message) in output:
        for i in range(0,(len(reply))):
            ReplyAppend+=str(reply[i])+'\n'
        net_connect.remote_conn.sendall(ReplyAppend)
        output = net_connect.remote_conn.recv(65535).decode('utf-8') 
    print (output)
    return output

CryptoPkiEnroll=['','','no','no','yes']

output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)

What is the difference between Builder Design pattern and Factory Design pattern?

Both are Creational patterns, to create Object.

1) Factory Pattern - Assume, you have one super class and N number of sub classes. The object is created depends on which parameter/value is passed.

2) Builder pattern - to create complex object.

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.

If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.

Shortcut for changing font size

Ctrl + Alt + MouseWheel will work in Visual Studio 2015.

How to change text color of simple list item

I'm also faced this situation. You can handle above method. but simple if you pass simple_dropdown_item_1line as resource. It will be black color text by default.

This is my code I have achieved in kind of situation.

ArrayAdapter<String> arrAdapter = 
new ArrayAdapter<String>(context,android.R.layout.simple_dropdown_item_1line,countryList);
        listView.setAdapter(arrAdapter);

Your code below:

setListAdapter(new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_dropdown_item_1line, mStringList));

Actually android.R.layout.simple_dropdown_item_1line is used for dropdown. I urge u to see this layout content once. It just simple textview. thats all. It's property will not affect your task. I checked It works fine.

WPF User Control Parent

Try using the following:

Window parentWindow = Window.GetWindow(userControlReference);

The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

How to calculate the number of occurrence of a given character in each row of a column of strings?

The next expression does the job and also works for symbols, not only letters.

The expression works as follows:

1: it uses lapply on the columns of the dataframe q.data to iterate over the rows of the column 2 ("lapply(q.data[,2],"),

2: it apply to each row of the column 2 a function "function(x){sum('a' == strsplit(as.character(x), '')[[1]])}". The function takes each row value of column 2 (x), convert to character (in case it is a factor for example), and it does the split of the string on every character ("strsplit(as.character(x), '')"). As a result we have a a vector with each character of the string value for each row of the column 2.

3: Each vector value of the vector is compared with the desired character to be counted, in this case "a" (" 'a' == "). This operation will return a vector of True and False values "c(True,False,True,....)", being True when the value in the vector matches the desired character to be counted.

4: The total times the character 'a' appears in the row is calculated as the sum of all the 'True' values in the vector "sum(....)".

5: Then it is applied the "unlist" function to unpack the result of the "lapply" function and assign it to a new column in the dataframe ("q.data$number.of.a<-unlist(....")

q.data$number.of.a<-unlist(lapply(q.data[,2],function(x){sum('a' == strsplit(as.character(x), '')[[1]])}))

>q.data

#  number     string     number.of.a
#1   greatgreat         2
#2      magic           1
#3      not             0

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

It's not your specific case, but it's worth noting for anybody else that this error can occur if you try to reference some fields in a table that are not the whole primary key of that table. Obviously this is not allowed.

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

git with development, staging and production branches

We do it differently. IMHO we do it in an easier way: in master we are working on the next major version.

Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.

To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.

If a new release is coming, we create a side-branch out of master, e.g. release-5 where only bugs get fixed.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

CSS3 Rotate Animation

Here is a demo. The correct animation CSS:

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin 4s linear infinite;_x000D_
    -moz-animation:spin 4s linear infinite;_x000D_
    animation:spin 4s linear infinite;_x000D_
}_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<img class="image" src="http://i.stack.imgur.com/pC1Tv.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_


Some notes on your code:

  1. You've nested the keyframes inside the .image rule, and that's incorrect
  2. float:left won't work on absolutely positioned elements
  3. Have a look at caniuse: IE10 doesn't need the -ms- prefix

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

css to make bootstrap navbar transparent

If you are using the latest version of Bootstrap i.e 4.0.0 you just need to use the 'transparent' keyword as:

<nav class="navbar navbar-light transparent">

There is simply no need to apply any css for this as bootstrap has this property inbuilt.

How to check for changes on remote (origin) Git repository

git remote update && git status 

Found this on the answer to Check if pull needed in Git

git remote update to bring your remote refs up to date. Then you can do one of several things, such as:

  1. git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.

  2. git show-branch *master will show you the commits in all of the branches whose names end in master (eg master and origin/master).

If you use -v with git remote update you can see which branches got updated, so you don't really need any further commands.

The project cannot be built until the build path errors are resolved.

1-Right CLick on your project folder, Choose Build Path > Configure Build Path
2-Select Libraries Tab and delete any arbitrary library present there.
3-Click on Add Library option, Select JRE System Library and click Next.
4-Choose last Radiobutton option Workspace default JRE and click Finish.
5-press f5 for refresh.
6-run ur program .

How to add minutes to current time in swift

You can use in swift 4 or 5

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)

    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)

output:

before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15

'IF' in 'SELECT' statement - choose output value based on column values

SELECT CompanyName, 
    CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
         WHEN Country = 'Brazil' THEN 'South America'
         ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

MongoDB and "joins"

I came across lot of posts searching for the same - "Mongodb Joins" and alternatives or equivalents. So my answer would help many other who are like me. This is the answer I would be looking for.

I am using Mongoose with Express framework. There is a functionality called Population in place of joins.

As mentioned in Mongoose docs.

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.

This StackOverflow answer shows a simple example on how to use it.

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

Reverse each individual word of "Hello World" string with Java

example with stream API

    public static String reverseAllWords(String str) {
    String[] arr = str.split(" ");
    String res = "";
    for (int x = 0; x < arr.length; x++) {
        res = res + Stream.of(arr[x].split("")).reduce("", (a, b) -> b + a) + " ";
    }
    return res;
}

Reading and displaying data from a .txt file

Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).

import java.io.*;
import java.util.Scanner;
import java.io.*;

public class TestRead
{
public static void main(String[] input)
{
    String fname;
    Scanner scan = new Scanner(System.in);

    /* enter filename with extension to open and read its content */

    System.out.print("Enter File Name to Open (with extension like file.txt) : ");
    fname = scan.nextLine();

    /* this will reference only one line at a time */

    String line = null;
    try
    {
        /* FileReader reads text files in the default encoding */
        FileReader fileReader = new FileReader(fname);

        /* always wrap the FileReader in BufferedReader */
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null)
        {
            System.out.println(line);
        }

        /* always close the file after use */
        bufferedReader.close();
    }
    catch(IOException ex)
    {
        System.out.println("Error reading file named '" + fname + "'");
    }
}

}

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

The error comes (at least sometimes) from paths that are too long. In my project simply reducing the output file path does the job: "Properties/Configuration Properties/General/Intermediate Directory"

Seems that I have hit the 250 character path limitation.

Deleting rows with MySQL LEFT JOIN

You simply need to specify on which tables to apply the DELETE.

Delete only the deadline rows:

DELETE `deadline` FROM `deadline` LEFT JOIN `job` ....

Delete the deadline and job rows:

DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....

Delete only the job rows:

DELETE `job` FROM `deadline` LEFT JOIN `job` ....

Angular Material: mat-select not selecting default

My solution is little tricky and simpler.

<div>
    <mat-select
        [placeholder]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

I just made use of the placeholder. The default color of material placeholder is light gray. To make it look like the option is selected, I just manipulated the CSS as follows:

::ng-deep .mat-select-placeholder {
    color: black;
}

How to handle query parameters in angular 2

Angular 5+ Update

The route.snapshot provides the initial value of the route parameter map. You can access the parameters directly without subscribing or adding observable operators. It's much simpler to write and read:

Quote from the Angular Docs

To break it down for you, here is how to do it with the new router:

this.router.navigate(['/login'], { queryParams: { token:'1234'} });

And then in the login component (notice the new .snapshot added):

constructor(private route: ActivatedRoute) {}
ngOnInit() {
    this.sessionId = this.route.snapshot.queryParams['token']

}

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Maybe you are trying to set it in Apache's php.ini, but your CLI (Command Line Interface) php.ini is not good.

Find your php.ini file with the following command:

php -i | grep php.ini

And then search for date.timezone and set it to "Europe/Amsterdam". all valid timezone will be found here http://php.net/manual/en/timezones.php

Another way (if the other does not work), search for the file AppKernel.php, which should be under the folder app of your Symfony project directory. Overwrite the __construct function below in the class AppKernel:

<?php     

class AppKernel extends Kernel
{
    // Other methods and variables


    // Append this init function below

    public function __construct($environment, $debug)
    {
        date_default_timezone_set( 'Europe/Paris' );
        parent::__construct($environment, $debug);
    }

}

How to start a stopped Docker container with a different command?

Find your stopped container id

docker ps -a

Commit the stopped container:

This command saves modified container state into a new image user/test_image

docker commit $CONTAINER_ID user/test_image

Start/run with a different entry point:

docker run -ti --entrypoint=sh user/test_image

Entrypoint argument description: https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime

Note:

Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.

Steps to start a stopped container have been borrowed from here: (last comment) https://github.com/docker/docker/issues/18078

Create Table from View

If you want to create a new A you can use INTO;

select * into A from dbo.myView

Git reset --hard and push to remote repository

To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:

user@remote$ git config receive.denyNonFastforwards false

Then go back to your local repo, try again to do your commit with --force:

user@local$ git push origin +master:master --force

And finally revert the server's setting in the original protected state:

user@remote$ git config receive.denyNonFastforwards true

How to strip a specific word from a string?

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

How to load external scripts dynamically in Angular?

a sample can be

script-loader.service.ts file

import {Injectable} from '@angular/core';
import * as $ from 'jquery';

declare let document: any;

interface Script {
  src: string;
  loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
public _scripts: Script[] = [];

/**
* @deprecated
* @param tag
* @param {string} scripts
* @returns {Promise<any[]>}
*/
load(tag, ...scripts: string[]) {
scripts.forEach((src: string) => {
  if (!this._scripts[src]) {
    this._scripts[src] = {src: src, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach((src) => promises.push(this.loadScript(tag, src)));

return Promise.all(promises);
}

 /**
 * Lazy load list of scripts
 * @param tag
 * @param scripts
 * @param loadOnce
 * @returns {Promise<any[]>}
 */
loadScripts(tag, scripts, loadOnce?: boolean) {
loadOnce = loadOnce || false;

scripts.forEach((script: string) => {
  if (!this._scripts[script]) {
    this._scripts[script] = {src: script, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach(
    (script) => promises.push(this.loadScript(tag, script, loadOnce)));

return Promise.all(promises);
}

/**
 * Lazy load a single script
 * @param tag
 * @param {string} src
 * @param loadOnce
 * @returns {Promise<any>}
 */
loadScript(tag, src: string, loadOnce?: boolean) {
loadOnce = loadOnce || false;

if (!this._scripts[src]) {
  this._scripts[src] = {src: src, loaded: false};
}

return new Promise((resolve, reject) => {
  // resolve if already loaded
  if (this._scripts[src].loaded && loadOnce) {
    resolve({src: src, loaded: true});
  }
  else {
    // load script tag
    let scriptTag = $('<script/>').
        attr('type', 'text/javascript').
        attr('src', this._scripts[src].src);

    $(tag).append(scriptTag);

    this._scripts[src] = {src: src, loaded: true};
    resolve({src: src, loaded: true});
  }
 });
 }
 }

and usage

first inject

  constructor(
  private _script: ScriptLoaderService) {
  }

then

ngAfterViewInit()  {
this._script.loadScripts('app-wizard-wizard-3',
['assets/demo/default/custom/crud/wizard/wizard.js']);

}

or

    this._script.loadScripts('body', [
  'assets/vendors/base/vendors.bundle.js',
  'assets/demo/default/base/scripts.bundle.js'], true).then(() => {
  Helpers.setLoading(false);
  this.handleFormSwitch();
  this.handleSignInFormSubmit();
  this.handleSignUpFormSubmit();
  this.handleForgetPasswordFormSubmit();
});

Is there a way to specify a max height or width for an image?

set a style for the image

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />

Maven Out of Memory Build Failure

Someone has already mentioned the problem with the 32 bit OS. In my case the problem was that I was compiling with 32 bit JDK.

Defining constant string in Java?

You can use

 public static final String HELLO = "hello";

if you have many string constants, you can use external property file / simple "constant holder" class

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.