Programs & Examples On #Redirectmode

postgres: upgrade a user to be a superuser?

You can create a SUPERUSER or promote USER, so for your case

$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"

or rollback

$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"

To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.

$  sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$  sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"

How to keep an iPhone app running on background fully operational

If any background task runs more than 10 minutes,then the task will be suspended and code block specified with beginBackgroundTaskWithExpirationHandler is called to clean up the task. background remaining time can be checked with [[UIApplication sharedApplication] backgroundTimeRemaining]. Initially when the App is in foreground backgroundTimeRemaining is set to bigger value. When the app goes to background, you can see backgroundTimeRemaining value decreases from 599.XXX ( 1o minutes). once the backgroundTimeRemaining becomes ZERO, the background task will be suspended.

        //1)Creating iOS Background Task
        __block UIBackgroundTaskIdentifier background_task;
        background_task = [application beginBackgroundTaskWithExpirationHandler:^ {

               //This code block is execute when the application’s 
               //remaining background time reaches ZERO.
          }];


        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //### background task starts

            //#### background task ends
        });

        //2)Making background task Asynchronous
        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
        {
            NSLog(@"Multitasking Supported");

            __block UIBackgroundTaskIdentifier background_task;
            background_task = [application beginBackgroundTaskWithExpirationHandler:^ {

                //Clean up code. Tell the system that we are done.
                [application endBackgroundTask: background_task];
                background_task = UIBackgroundTaskInvalid;
            }];


        **//Putting All together**
            //To make the code block asynchronous
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                //### background task starts
                NSLog(@"Running in the background\n");
                while(TRUE)
                {
                    NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
                    [NSThread sleepForTimeInterval:1]; //wait for 1 sec
                }
                //#### background task ends

                //Clean up code. Tell the system that we are done.
                [application endBackgroundTask: background_task];
                background_task = UIBackgroundTaskInvalid; 
            });
        }
        else
        {
            NSLog(@"Multitasking Not Supported");
        }

How to import XML file into MySQL database table using XML_LOAD(); function

you can specify fields like this:

LOAD XML LOCAL INFILE '/pathtofile/file.xml' 
INTO TABLE my_tablename(personal_number, firstname, ...); 

What's the difference between RANK() and DENSE_RANK() functions in oracle?

select empno
       ,salary
       ,row_number() over(order by salary desc) as Serial
       ,Rank() over(order by salary desc) as rank
       ,dense_rank() over(order by salary desc) as denseRank
from emp ;

Row_number() -> Used for generating serial number

Dense_rank() will give continuous rank but rank will skip rank in case of clash of rank.

How to use LINQ Distinct() with multiple fields

Answering the headline of the question (what attracted people here) and ignoring that the example used anonymous types....

This solution will also work for non-anonymous types. It should not be needed for anonymous types.

Helper class:

/// <summary>
/// Allow IEqualityComparer to be configured within a lambda expression.
/// From https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer
/// </summary>
/// <typeparam name="T"></typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
    readonly Func<T, T, bool> _comparer;
    readonly Func<T, int> _hash;

    /// <summary>
    /// Simplest constructor, provide a conversion to string for type T to use as a comparison key (GetHashCode() and Equals().
    /// https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer, user "orip"
    /// </summary>
    /// <param name="toString"></param>
    public LambdaEqualityComparer(Func<T, string> toString)
        : this((t1, t2) => toString(t1) == toString(t2), t => toString(t).GetHashCode())
    {
    }

    /// <summary>
    /// Constructor.  Assumes T.GetHashCode() is accurate.
    /// </summary>
    /// <param name="comparer"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer)
        : this(comparer, t => t.GetHashCode())
    {
    }

    /// <summary>
    /// Constructor, provide a equality comparer and a hash.
    /// </summary>
    /// <param name="comparer"></param>
    /// <param name="hash"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hash)
    {
        _comparer = comparer;
        _hash = hash;
    }

    public bool Equals(T x, T y)
    {
        return _comparer(x, y);
    }

    public int GetHashCode(T obj)
    {
        return _hash(obj);
    }    
}

Simplest usage:

List<Product> products = duplicatedProducts.Distinct(
    new LambdaEqualityComparer<Product>(p =>
        String.Format("{0}{1}{2}{3}",
            p.ProductId,
            p.ProductName,
            p.CategoryId,
            p.CategoryName))
        ).ToList();

The simplest (but not that efficient) usage is to map to a string representation so that custom hashing is avoided. Equal strings already have equal hash codes.

Reference:
Wrap a delegate in an IEqualityComparer

Parenthesis/Brackets Matching using Stack algorithm

Algorithm is:

1)Create a stack

2)while(end of input is not reached)

   i)if the character read is not a sysmbol to be balanced ,ignore it.

   ii)if the character is {,[,( then push it to stack

   iii)If it is a },),] then if 

        a)the stack is empty report an error(catch it) i.e not balanced

        b)else pop the stack 

   iv)if element popped is not corresponding to opening sysmbol,then report error.

3) In the end,if stack is not empty report error else expression is balanced.  

In Java code:

public class StackDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("--Bracket checker--");
        CharStackArray stack = new CharStackArray(10);
        stack.balanceSymbol("[a+b{c+(e-f[p-q])}]") ;
        stack.display();

    }

}    

class CharStackArray {
        private char[] array;
        private int top;
        private int capacity;

        public CharStackArray(int cap) {
            capacity = cap;
            array = new char[capacity];
            top = -1;
        }

        public void push(char data) {
            array[++top] = data;
        }

        public char pop() {
            return array[top--];
        }

        public void display() {
            for (int i = 0; i <= top; i++) {
                System.out.print(array[i] + "->");
            }
        }

        public char peek() throws Exception {
            return array[top];
        }

        /*Call this method by passing a string expression*/
        public void balanceSymbol(String str) {
            try {
                char[] arr = str.toCharArray();
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i] == '[' || arr[i] == '{' || arr[i] == '(')
                        push(arr[i]);
                    else if (arr[i] == '}' && peek() == '{')
                        pop();
                    else if (arr[i] == ']' && peek() == '[')
                        pop();
                    else if (arr[i] == ')' && peek() == '(')
                        pop();
                }
                if (isEmpty()) {
                    System.out.println("String is balanced");
                } else {
                    System.out.println("String is not balanced");
                }
            } catch (Exception e) {
                System.out.println("String not balanced");
            }

        }

        public boolean isEmpty() {
            return (top == -1);
        }
    }

Output:

--Bracket checker--

String is balanced

How to remove specific element from an array using python

There is an alternative solution to this problem which also deals with duplicate matches.

We start with 2 lists of equal length: emails, otherarray. The objective is to remove items from both lists for each index i where emails[i] == '[email protected]'.

This can be achieved using a list comprehension and then splitting via zip:

emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']

from operator import itemgetter

res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))

print(emails)      # ['[email protected]', '[email protected]']
print(otherarray)  # ['some', 'details']

How to grant remote access to MySQL for a whole subnet?

Just a note of a peculiarity I faced:
Consider:

db server:  192.168.0.101
web server: 192.168.0.102

If you have a user defined in mysql.user as 'user'@'192.168.0.102' with password1 and another 'user'@'192.168.0.%' with password2,

then,

if you try to connect to the db server from the web server as 'user' with password2,

it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102' authentication is used over the wildcard 'user'@'192.168.0.%' authentication.

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Double free or corruption after queue::push

You can also try to check null before delete such that

if(myArray) { delete[] myArray; myArray = NULL; }

or you can define all delete operations ina safe manner like this:

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }
#endif

#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p) = NULL; } }
#endif

and then use

SAFE_DELETE_ARRAY(myArray);

Why java.security.NoSuchProviderException No such provider: BC?

You can add security provider by editing java.security with using following code with creating static block:

static {
    Security.addProvider(new BouncyCastleProvider());
}

If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
</dependency>

If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.

http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

Automatically scroll down chat div

It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto).

I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/

I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function

function getMessages(letter) {
    var div = $("#messages");
    div.scrollTop(div.prop('scrollHeight'));
}

, in this case once on 'documentReady'.

prop('scrollHeight') will access the value of the property on the first element in the set of matched elements.

How to test abstract class in Java with JUnit?

You could do something like this

public abstract MyAbstractClass {

    @Autowire
    private MyMock myMock;        

    protected String sayHello() {
            return myMock.getHello() + ", " + getName();
    }

    public abstract String getName();
}

// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {

    @Mock
    private MyMock myMock;

    @InjectMocks
    private MyAbstractClass thiz = this;

    private String myName = null;

    @Override
    public String getName() {
        return myName;
    }

    @Test
    public void testSayHello() {
        myName = "Johnny"
        when(myMock.getHello()).thenReturn("Hello");
        String result = sayHello();
        assertEquals("Hello, Johnny", result);
    }
}

Swift - Remove " character from string

I've eventually got this to work in the playground, having multiple characters I'm trying to remove from a string:

var otherstring = "lat\" : 40.7127837,\n"
var new = otherstring.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "la t, \n \" ':"))
count(new) //result = 10
println(new) 
//yielding what I'm after just the numeric portion 40.7127837

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

Get form data in ReactJS

To improve the user experience; when the user clicks on the submit button, you can try to get the form to first show a sending message. Once we've received a response from the server, it can update the message accordingly. We achieve this in React by chaining statuses. See codepen or snippets below:

The following method makes the first state change:

handleSubmit(e) {
    e.preventDefault();
    this.setState({ message: 'Sending...' }, this.sendFormData);
}

As soon as React shows the above Sending message on screen, it will call the method that will send the form data to the server: this.sendFormData(). For simplicity I've added a setTimeout to mimic this.

sendFormData() {
  var formData = {
      Title: this.refs.Title.value,
      Author: this.refs.Author.value,
      Genre: this.refs.Genre.value,
      YearReleased: this.refs.YearReleased.value};
  setTimeout(() => { 
    console.log(formData);
    this.setState({ message: 'data sent!' });
  }, 3000);
}

In React, the method this.setState() renders a component with new properties. So you can also add some logic in render() method of the form component that will behave differently depending on the type of response we get from the server. For instance:

render() {
  if (this.state.responseType) {
      var classString = 'alert alert-' + this.state.type;
      var status = <div id="status" className={classString} ref="status">
                     {this.state.message}
                   </div>;
  }
return ( ...

codepen

Editing dictionary values in a foreach loop

This answer is for comparing two solutions, not a suggested solution.

Instead of creating another list as other answers suggested, you can used a for loop using the dictionary Count for the loop stop condition and Keys.ElementAt(i) to get the key.

for (int i = 0; i < dictionary.Count; i++)
{
    dictionary[dictionary.Keys.ElementAt(i)] = 0;
}

At firs I thought this would be more efficient because we do not need to create a key list. After running a test I found that the for loop solution is much less efficient. The reason is because ElementAt is O(n) on the dictionary.Keys property, it searches from the beginning of the collection until it gets to the nth item.

Test:

int iterations = 10;
int dictionarySize = 10000;
Stopwatch sw = new Stopwatch();

Console.WriteLine("Creating dictionary...");
Dictionary<string, int> dictionary = new Dictionary<string, int>(dictionarySize);
for (int i = 0; i < dictionarySize; i++)
{
    dictionary.Add(i.ToString(), i);
}
Console.WriteLine("Done");

Console.WriteLine("Starting tests...");

// for loop test
sw.Restart();
for (int i = 0; i < iterations; i++)
{
    for (int j = 0; j < dictionary.Count; j++)
    {
        dictionary[dictionary.Keys.ElementAt(j)] = 3;
    }
}
sw.Stop();
Console.WriteLine($"for loop Test:     {sw.ElapsedMilliseconds} ms");

// foreach loop test
sw.Restart();
for (int i = 0; i < iterations; i++)
{
    foreach (string key in dictionary.Keys.ToList())
    {
        dictionary[key] = 3;
    }
}
sw.Stop();
Console.WriteLine($"foreach loop Test: {sw.ElapsedMilliseconds} ms");

Console.WriteLine("Done");

Results:

Creating dictionary...
Done
Starting tests...
for loop Test:     2367 ms
foreach loop Test: 3 ms
Done

How to print / echo environment variables?

To bring the existing answers together with an important clarification:

As stated, the problem with NAME=sam echo "$NAME" is that $NAME gets expanded by the current shell before assignment NAME=sam takes effect.

Solutions that preserve the original semantics (of the (ineffective) solution attempt NAME=sam echo "$NAME"):

Use either eval[1] (as in the question itself), or printenv (as added by Aaron McDaid to heemayl's answer), or bash -c (from Ljm Dullaart's answer), in descending order of efficiency:

NAME=sam eval 'echo "$NAME"'  # use `eval` only if you fully control the command string
NAME=sam printenv NAME
NAME=sam bash -c 'echo "$NAME"'

printenv is not a POSIX utility, but it is available on both Linux and macOS/BSD.

What this style of invocation (<var>=<name> cmd ...) does is to define NAME:

  • as an environment variable
  • that is only defined for the command being invoked.

In other words: NAME only exists for the command being invoked, and has no effect on the current shell (if no variable named NAME existed before, there will be none after; a preexisting NAME variable remains unchanged).

POSIX defines the rules for this kind of invocation in its Command Search and Execution chapter.


The following solutions work very differently (from heemayl's answer):

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

While they produce the same output, they instead define:

  • a shell variable NAME (only) rather than an environment variable
    • if echo were a command that relied on environment variable NAME, it wouldn't be defined (or potentially defined differently from earlier).
  • that lives on after the command.

Note that every environment variable is also exposed as a shell variable, but the inverse is not true: shell variables are only visible to the current shell and its subshells, but not to child processes, such as external utilities and (non-sourced) scripts (unless they're marked as environment variables with export or declare -x).


[1] Technically, bash is in violation of POSIX here (as is zsh): Since eval is a special shell built-in, the preceding NAME=sam assignment should cause the the variable $NAME to remain in scope after the command finishes, but that's not what happens.
However, when you run bash in POSIX compatibility mode, it is compliant.
dash and ksh are always compliant.
The exact rules are complicated, and some aspects are left up to the implementations to decide; again, see Command Search and Execution.
Also, the usual disclaimer applies: Use eval only on input you fully control or implicitly trust.

Meaning of *& and **& in C++

To understand those phrases let's look at the couple of things:

typedef double Foo;
void fooFunc(Foo &_bar){ ... }

So that's passing a double by reference.

typedef double* Foo;
void fooFunc(Foo &_bar){ ... }

now it's passing a pointer to a double by reference.

typedef double** Foo;
void fooFunc(Foo &_bar){ ... }

Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.

How to clear react-native cache?

For React Native Init approach (without expo) use:

npm start -- --reset-cache

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

 package MujeebWorkspace.helps;
 // [email protected]

 public class Mujeeb {

     static String str= "This code is simple to reverse the word without changing positions";
     static String[] reverse = str.split(" ");

     public static void main(String [] args){  
         reverseMethod();
     }

     public static void reverseMethod(){
         for (int k=0; k<=reverse.length-1; k++) {
             String word =reverse[reverse.length-(reverse.length-k)];
             String subword = (word+" ");
             String [] splitsubword = subword.split("");

             for (int i=subword.length(); i>0; i--){
                 System.out.print(splitsubword[i]);  
             }
         }
     }
 }

How do you determine a processing time in Python?

For some further information on how to determine the processing time, and a comparison of a few methods (some mentioned already in the answers of this post) - specifically, the difference between:

start = time.time()

versus the now obsolete (as of 3.3, time.clock() is deprecated)

start = time.clock()

see this other article on Stackoverflow here:

Python - time.clock() vs. time.time() - accuracy?

If nothing else, this will work good:

start = time.time()

... do something

elapsed = (time.time() - start)

How do I protect javascript files?

Good question with a simple answer: you can't!

Javascript is a client-side programming language, therefore it works on the client's machine, so you can't actually hide anything from the client.
Obfuscating your code is a good solution, but it's not enough, because, although it is hard, someone could decipher your code and "steal" your script.
There are a few ways of making your code hard to be stolen, but as i said nothing is bullet-proof.

Off the top of my head, one idea is to restrict access to your external js files from outside the page you embed your code in. In that case, if you have

<script type="text/javascript" src="myJs.js"></script>

and someone tries to access the myJs.js file in browser, he shouldn't be granted any access to the script source.
For example, if your page is written in php, you can include the script via the include function and let the script decide if it's safe" to return it's source.
In this example, you'll need the external "js" (written in php) file myJs.php :

<?php
    $URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    if ($URL != "my-domain.com/my-page.php")
    die("/\*sry, no acces rights\*/");
?>
// your obfuscated script goes here

that would be included in your main page my-page.php :

<script type="text/javascript">
    <?php include "myJs.php"; ?>;
</script> 

This way, only the browser could see the js file contents.

Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code disappears :

<script id="erasable" type="text/javascript">
    //your code goes here
    document.getElementById('erasable').innerHTML = "";
</script>

These are all just simple hacks that cannot, and I can't stress this enough : cannot, fully protect your js code, but they can sure piss off someone who is trying to "steal" your code.

Update:

I recently came across a very interesting article written by Patrick Weid on how to hide your js code, and he reveals a different approach: you can encode your source code into an image! Sure, that's not bullet proof either, but it's another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to do pixel manipulation on images. And since the canvas pixel is represented by 4 values (rgba), each pixel can have a value in the range of 0-255. That means that you can store a character (actual it's ascii code) in every pixel. The rest of the encoding/decoding is trivial.
Thanks, Patrick!

Convert base class to derived class

That's not possible. but you can use an Object Mapper like AutoMapper

Example:

class A
{
    public int IntProp { get; set; }
}
class B
{
    public int IntProp { get; set; }
    public string StrProp { get; set; }
}

In global.asax or application startup:

AutoMapper.Mapper.CreateMap<A, B>();

Usage:

var b = AutoMapper.Mapper.Map<B>(a);

It's easily configurable via a fluent API.

How do I delete specific characters from a particular String in Java?

Reassign the variable to a substring:

s = s.substring(0, s.length() - 1)

Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.

$_POST Array from html form

<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>


$id = implode(',',$_POST['id']);
echo $id

you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r.

print_r($_POST['id']);

Initializing an Array of Structs in C#

You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };

How can I split a delimited string into an array in PHP?

Code:

$string = "9,[email protected],8";

$array  = explode(",", $string);

print_r($array);

$no = 1;
foreach ($array as $line) {
    echo $no . ". " . $line . PHP_EOL;
    $no++;
};

Online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/pGEAlb" ></iframe>
_x000D_
_x000D_
_x000D_

Where is android studio building my .apk file?

You should Build your app instead of debugging process. Just follow this:

Build -> Build Bundles/APK(s) -> Build APK(s)

enter image description here

Counting lines, words, and characters within a text file using Python

Functions that might be helpful:

  • open("file").read() which reads the contents of the whole file at once
  • 'string'.splitlines() which separates lines from each other (and discards empty lines)

By using len() and those functions you could accomplish what you're doing.

Bootstrap 4 dropdown with search

As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.

Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).

Is there a numpy builtin to reject outliers from a list

Benjamin Bannier's answer yields a pass-through when the median of distances from the median is 0, so I found this modified version a bit more helpful for cases as given in the example below.

def reject_outliers_2(data, m=2.):
    d = np.abs(data - np.median(data))
    mdev = np.median(d)
    s = d / (mdev if mdev else 1.)
    return data[s < m]

Example:

data_points = np.array([10, 10, 10, 17, 10, 10])
print(reject_outliers(data_points))
print(reject_outliers_2(data_points))

Gives:

[[10, 10, 10, 17, 10, 10]]  # 17 is not filtered
[10, 10, 10, 10, 10]  # 17 is filtered (it's distance, 7, is greater than m)

How to completely remove borders from HTML table

For me I needed to do something like this to completely remove the borders from the table and all cells. This does not require modifying the HTML at all, which was helpful in my case.

table, tr, td {
    border: none;
}

Android Studio: Gradle: error: cannot find symbol variable

make sure that the imported R is not from another module. I had moved a class from a module to the main project, and the R was the one from the module.

How do I get column datatype in Oracle with PL-SQL with low privileges?

You can try this.

SELECT *
  FROM (SELECT column_name,
               data_type,
               data_type
               || CASE
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) > 0
                     THEN
                        '(' || data_precision || ',' || data_scale || ')'
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) = 0
                     THEN
                        '(' || data_precision || ')'
                     WHEN data_precision IS NULL AND data_scale IS NOT NULL
                     THEN
                        '(*,' || data_scale || ')'
                     WHEN char_length > 0
                     THEN
                        '(' || char_length
                        || CASE char_used
                              WHEN 'B' THEN ' Byte'
                              WHEN 'C' THEN ' Char'
                              ELSE NULL
                           END
                        || ')'
                  END
               || DECODE (nullable, 'N', ' NOT NULL')
                  DataTypeWithLength
          FROM user_tab_columns
         WHERE table_name = 'CONTRACT')
 WHERE DataTypeWithLength = 'CHAR(1 Byte)';

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

For me, I had to check the google-services.json file and make sure "package_name" was correctly set to the package name of my android app. The auto generated services file had .backend appended to it in my case.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

For impatient, a quick way to disable python unverified HTTPS warning:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

Updated for the shifting:

d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"

You need to require 'date' for this btw.

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

Save multiple sheets to .pdf

In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Here is possibly the fastest way to query a large number of rows with Dapper using a list of IDs. I promise you this is faster than almost any other way you can think of (with the possible exception of using a TVP as given in another answer, and which I haven't tested, but I suspect may be slower because you still have to populate the TVP). It is planets faster than Dapper using IN syntax and universes faster than Entity Framework row by row. And it is even continents faster than passing in a list of VALUES or UNION ALL SELECT items. It can easily be extended to use a multi-column key, just add the extra columns to the DataTable, the temp table, and the join conditions.

public IReadOnlyCollection<Item> GetItemsByItemIds(IEnumerable<int> items) {
   var itemList = new HashSet(items);
   if (itemList.Count == 0) { return Enumerable.Empty<Item>().ToList().AsReadOnly(); }

   var itemDataTable = new DataTable();
   itemDataTable.Columns.Add("ItemId", typeof(int));
   itemList.ForEach(itemid => itemDataTable.Rows.Add(itemid));

   using (SqlConnection conn = GetConnection()) // however you get a connection
   using (var transaction = conn.BeginTransaction()) {
      conn.Execute(
         "CREATE TABLE #Items (ItemId int NOT NULL PRIMARY KEY CLUSTERED);",
         transaction: transaction
      );

      new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, transaction) {
         DestinationTableName = "#Items",
         BulkCopyTimeout = 3600 // ridiculously large
      }
         .WriteToServer(itemDataTable);
      var result = conn
         .Query<Item>(@"
            SELECT i.ItemId, i.ItemName
            FROM #Items x INNER JOIN dbo.Items i ON x.ItemId = i.ItemId
            DROP TABLE #Items;",
            transaction: transaction,
            commandTimeout: 3600
         )
         .ToList()
         .AsReadOnly();
      transaction.Rollback(); // Or commit if you like
      return result;
   }
}

Be aware that you need to learn a little bit about Bulk Inserts. There are options about firing triggers (the default is no), respecting constraints, locking the table, allowing concurrent inserts, and so on.

iOS UIImagePickerController result image orientation after upload

I achieve this by writing below a few lines of code

extension UIImage {

    public func correctlyOrientedImage() -> UIImage {
        guard imageOrientation != .up else { return self }

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: .zero, size: size))
        let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage
    }
}

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

Xcode : Adding a project as a build dependency

Today I faced with the same problem. As the result of the first run I got next error:

Lexical or Preprocessor Issue: 'SDKProjectName*/*SDKProjectName.h' file not found.

But before running, I, obviously, added my SDK into the demo project, just drag&drop .xcodeproj file into my test project's source tree. After that, I moved into Build Phases tab in setting of the main xcodeproj file (of the demo) and added my SDK as target dependency and embed framework into corresponding tabs.

But at the result, I got an error above!

So, the problem was into empty line on the Header Search Paths option. I just wrote "../**" as value for this key and project compiled successfully. So, after that, you can add #include <SDKName/SDKName.h> into any project, which includes this SDK.

ps. My test app was created into root SDK folder.

What's a good way to extend Error in JavaScript?

Crescent Fresh's answer highly-voted answer is misleading. Though his warnings are invalid, there are other limitations that he doesn't address.

First, the reasoning in Crescent's "Caveats:" paragraph doesn't make sense. The explanation implies that coding "a bunch of if (error instanceof MyError) else ..." is somehow burdensome or verbose compared to multiple catch statements. Multiple instanceof statements in a single catch block are just as concise as multiple catch statements-- clean and concise code without any tricks. This is a great way to emulate Java's great throwable-subtype-specific error handling.

WRT "appears the message property of the subclass does not get set", that is not the case if you use a properly constructed Error subclass. To make your own ErrorX Error subclass, just copy the code block beginning with "var MyError =", changing the one word "MyError" to "ErrorX". (If you want to add custom methods to your subclass, follow the sample text).

The real and significant limitation of JavaScript error subclassing is that for JavaScript implementations or debuggers that track and report on stack trace and location-of-instantiation, like FireFox, a location in your own Error subclass implementation will be recorded as the instantiation point of the class, whereas if you used a direct Error, it would be the location where you ran "new Error(...)"). IE users would probably never notice, but users of Fire Bug on FF will see useless file name and line number values reported alongside these Errors, and will have to drill down on the stack trace to element #1 to find the real instantiation location.

How to search a list of tuples in Python

[k for k,v in l if v =='delicia']

here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

And instead of converting it to a dict, we are using llist comprehension.

*Key* in Key,Value in list, where value = **delicia**

How does one check if a table exists in an Android SQLite database?

Try this one:

public boolean isTableExists(String tableName, boolean openDb) {
    if(openDb) {
        if(mDatabase == null || !mDatabase.isOpen()) {
            mDatabase = getReadableDatabase();
        }

        if(!mDatabase.isReadOnly()) {
            mDatabase.close();
            mDatabase = getReadableDatabase();
        }
    }

    String query = "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'";
    try (Cursor cursor = mDatabase.rawQuery(query, null)) {
        if(cursor!=null) {
            if(cursor.getCount()>0) {
                return true;
            }
        }
        return false;
    }
}

How to change plot background color?

The easiest thing is probably to provide the color when you create the plot :

fig1 = plt.figure(facecolor=(1, 1, 1))

or

fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, facecolor=(1, 1, 1))

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

How to save a BufferedImage as a File

You can save a BufferedImage object using write method of the javax.imageio.ImageIO class. The signature of the method is like this:

public static boolean write(RenderedImage im, String formatName, File output) throws IOException

Here im is the RenderedImage to be written, formatName is the String containing the informal name of the format (e.g. png) and output is the file object to be written to. An example usage of the method for PNG file format is shown below:

ImageIO.write(image, "png", file);

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

Calculate the number of business days between two dates?

I used the following code to also take in to account bank holidays:

public class WorkingDays
{
    public List<DateTime> GetHolidays()
    {
        var client = new WebClient();
        var json = client.DownloadString("https://www.gov.uk/bank-holidays.json");
        var js = new JavaScriptSerializer();
        var holidays = js.Deserialize <Dictionary<string, Holidays>>(json);
        return holidays["england-and-wales"].events.Select(d => d.date).ToList();
    }

    public int GetWorkingDays(DateTime from, DateTime to)
    {
        var totalDays = 0;
        var holidays = GetHolidays();
        for (var date = from.AddDays(1); date <= to; date = date.AddDays(1))
        {
            if (date.DayOfWeek != DayOfWeek.Saturday
                && date.DayOfWeek != DayOfWeek.Sunday
                && !holidays.Contains(date))
                totalDays++;
        }

        return totalDays;
    }
}

public class Holidays
{
    public string division { get; set; }
    public List<Event> events { get; set; }
}

public class Event
{
    public DateTime date { get; set; }
    public string notes { get; set; }
    public string title { get; set; }
}

And Unit Tests:

[TestClass]
public class WorkingDays
{
    [TestMethod]
    public void SameDayIsZero()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 12);

        Assert.AreEqual(0, service.GetWorkingDays(from, from));

    }

    [TestMethod]
    public void CalculateDaysInWorkingWeek()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 12);
        var to = new DateTime(2013, 8, 16);

        Assert.AreEqual(4, service.GetWorkingDays(from, to), "Mon - Fri = 4");

        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 13)), "Mon - Tues = 1");
    }

    [TestMethod]
    public void NotIncludeWeekends()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 9);
        var to = new DateTime(2013, 8, 16);

        Assert.AreEqual(5, service.GetWorkingDays(from, to), "Fri - Fri = 5");

        Assert.AreEqual(2, service.GetWorkingDays(from, new DateTime(2013, 8, 13)), "Fri - Tues = 2");
        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 12)), "Fri - Mon = 1");
    }

    [TestMethod]
    public void AccountForHolidays()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 23);

        Assert.AreEqual(0, service.GetWorkingDays(from, new DateTime(2013, 8, 26)), "Fri - Mon = 0");

        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 27)), "Fri - Tues = 1");
    }
}

How can I pass a parameter to a Java Thread?

Parameter passing via the start() and run() methods:

// Tester
public static void main(String... args) throws Exception {
    ThreadType2 t = new ThreadType2(new RunnableType2(){
        public void run(Object object) {
            System.out.println("Parameter="+object);
        }});
    t.start("the parameter");
}

// New class 1 of 2
public class ThreadType2 {
    final private Thread thread;
    private Object objectIn = null;
    ThreadType2(final RunnableType2 runnableType2) {
        thread = new Thread(new Runnable() {
            public void run() {
                runnableType2.run(objectIn);
            }});
    }
    public void start(final Object object) {
        this.objectIn = object;
        thread.start();
    }
    // If you want to do things like setDaemon(true); 
    public Thread getThread() {
        return thread;
    }
}

// New class 2 of 2
public interface RunnableType2 {
    public void run(Object object);
}

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

variable is not declared it may be inaccessible due to its protection level

If I remember correctly, this is the default property for controls.

Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.

Must declare the scalar variable

Just adding what fixed it for me, where misspelling is the suspect as per this MSDN blog...

When splitting SQL strings over multiple lines, check that that you are comma separating your SQL string from your parameters (and not trying to concatenate them!) and not missing any spaces at the end of each split line. Not rocket science but hope I save someone a headache.

For example:

db.TableName.SqlQuery(
    "SELECT Id, Timestamp, User " +
    "FROM dbo.TableName " +
    "WHERE Timestamp >= @from " +
    "AND Timestamp <= @till;" + [USE COMMA NOT CONCATENATE!]
    new SqlParameter("from", from),
    new SqlParameter("till", till)),
    .ToListAsync()
    .Result;

Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(headerFont);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("date_style", style);
        ...
        return styles;
    }

you can also use methods to do repetitive tasks while creating styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

then, in your "main" code, set the style from the styles map you have.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );

View markdown files offline

I found MarkView Google Chrome extension pretty useful, actually it's working like a charm:

MarkView is a Chrome extention for editing and viewing markdown file with an outline view, support multiple table format styles, code block syntax highlight and Github Flavored Markdown.

Features:

  1. Editing and Viewing markdown file in web page style.
  2. Auto reload local file when file is changed (Post-installation: select "Allow access to file URLs" option in chrome://extensions/)
  3. Show outline beside the content in scrollable way
  4. Have buttons for GoTop, ViewSource and GoBottom
  5. Support Github Flavored Markdown table styles and code highlight.
  6. Highlight the code area for programming languages(eg. ```ruby)
  7. Support web pages printing with decent outlook(Chrome->File->Print...)
  8. Responsive: when the window size small than 940px, outline section will automatically hidden; resize bigger than 940px, outline section will display.
  9. MarkView will view all markdown files except those under raw.github.com because that subdomain only displays the source.

More features have been added to MarkView:

  1. WYSIWYG markdown editor
  2. Themes and Code Styling Selection
  3. Support Footnotes1
  4. Instant Slides Presentation
  5. Document Custom Styling

    • Add Theme CSS and Select
    • Add Code Style and Select
    • Write CSS, Save and Run

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

Oracle SQL Developer: Unable to find a JVM

The Oracle SQL developer is not supported by the 64bit JDK. To resolve this issue:

  1. Install a 32bit JDK (x86)
  2. Update your SQL developer config file (It should now point to the new 32bit JDK).
  3. Edit the sqldeveloper.conf, which can be found under {ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf
  4. Make sure SetJavaHome is pointing to your 32bit JDK.

For example:

SetJavaHome C:\Program Files (x86) \Java\jdk1.6.0_13

What is the difference between an abstract function and a virtual function?

The answer has been provided a number of times but the the question about when to use each is a design-time decision. I would see it as good practice to try to bundle common method definitions into distinct interfaces and pull them into classes at appropriate abstraction levels. Dumping a common set of abstract and virtual method definitions into a class renders the class unistantiable when it may be best to define a non-abstract class that implements a set of concise interfaces. As always, it depends on what best suits your applications specific needs.

Align image in center and middle within div

#over {
    display: table-cell; 
    vertical-align: middle; 
    text-align: center;
    height: 100px;
}

Modify height value for your need.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Alter MySQL table to add comments on columns

try:

 ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'  

How do I run a spring boot executable jar in a Production environment?

On Windows OS without Service.

start.bat

@ECHO OFF
call run.bat start

stop.bat:

@ECHO OFF
call run.bat stop

run.bat

@ECHO OFF
IF "%1"=="start" (
    ECHO start myapp
    start "myapp" java -jar -Dspring.profiles.active=staging myapp.jar
) ELSE IF "%1"=="stop" (
    ECHO stop myapp
    TASKKILL /FI "WINDOWTITLE eq myapp"
) ELSE (
    ECHO please, use "run.bat start" or "run.bat stop"
)
pause

Could not find a version that satisfies the requirement tensorflow

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

Reliable way to convert a file to a byte[]

Others have noted that you can use the built-in File.ReadAllBytes. The built-in method is fine, but it's worth noting that the code you post above is fragile for two reasons:

  1. Stream is IDisposable - you should place the FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read) initialization in a using clause to ensure the file is closed. Failure to do this may mean that the stream remains open if a failure occurs, which will mean the file remains locked - and that can cause other problems later on.
  2. fs.Read may read fewer bytes than you request. In general, the .Read method of a Stream instance will read at least one byte, but not necessarily all bytes you ask for. You'll need to write a loop that retries reading until all bytes are read. This page explains this in more detail.

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'
        fout.write(line)

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

mean() warning: argument is not numeric or logical: returning NA

If you just want to know the mean, you can use

summary(results)

It will give you more information than expected.

ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.

Furthermore, If you want to get mean values of each column, you can simply use the method below.

mean(results$columnName, na.rm = TRUE)

That will return mean value. (you have to change 'columnName' to your variable name

How to center icon and text in a android button with width set to "fill parent"

As suggested by Rodja, prior to 4.0 there isn't a direct way to center the text with the drawable. And indeed setting a padding_left value does move the drawable away from the border. Therefore my suggestion is that on runtime you calculate exactly how many pixels from the left border your drawable needs to be and then pass it using setPadding Your calculation may be something like

int paddingLeft = (button.getWidth() - drawableWidth - textWidth) / 2;

The width of your drawable's is fixed and you can look it up and you can also calculate or guess the text width.

Finally, you would need to multiple the padding value by the screen density, which you can do using DisplayMetrics

Error: Argument is not a function, got undefined

Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.

Get value of a string after last slash in JavaScript

light weigh

string.substring(start,end)

where

start = Required. The position where to start the extraction. First character is at index 0`.

end = Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string.

    var string = "var1/var2/var3";

    start   = string.lastIndexOf('/');  //console.log(start); o/p:- 9
    end     = string.length;            //console.log(end);   o/p:- 14

    var string_before_last_slash = string.substring(0, start);
    console.log(string_before_last_slash);//o/p:- var1/var2

    var string_after_last_slash = string.substring(start+1, end);
    console.log(string_after_last_slash);//o/p:- var3

OR

    var string_after_last_slash = string.substring(start+1);
    console.log(string_after_last_slash);//o/p:- var3

READ_EXTERNAL_STORAGE permission for Android

You have to ask for the permission at run time:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);
    dialog.dismiss();
    return;
}

And in the callback below you can access the storage without a problem.

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
        } else {
            // User refused to grant permission.
        }
    }
}

How to bind a List to a ComboBox?

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

For 2) you will need a list of countries first

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

How to call a method daily, at specific time, in C#?

A simple example for one task:

using System;
using System.Timers;

namespace ConsoleApp
{
    internal class Scheduler
    {
        private static readonly DateTime scheduledTime = 
            new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0);
        private static DateTime dateTimeLastRunTask;

        internal static void CheckScheduledTask()
        {
            if (dateTimeLastRunTask.Date < DateTime.Today && scheduledTime.TimeOfDay < DateTime.Now.TimeOfDay)
            {
                Console.WriteLine("Time to run task");
                dateTimeLastRunTask = DateTime.Now;
            }
            else
            {
                Console.WriteLine("not yet time");
            }
        }
    }

    internal class Program
    {
        private static Timer timer;

        static void Main(string[] args)
        {
            timer = new Timer(5000);
            timer.Elapsed += OnTimer;
            timer.Start();
            Console.ReadLine();
        }

        private static void OnTimer(object source, ElapsedEventArgs e)
        {
            Scheduler.CheckScheduledTask();
        }
    }
}

How to set menu to Toolbar in Android

You need to override this code in your Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu, this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

and set your toolbar like this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

rbind error: "names do not match previous names"

rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

names do not match previous names

WCF timeout exception detailed investigation

Did you check the WCF traces? WCF has a tendency to swallow exceptions and only return the last exception, which is the timeout that you're getting, since the end point didn't return anything meaningful.

Trimming text strings in SQL Server 2008

This function trims a string from left and right. Also it removes carriage returns from the string, an action which is not done by the LTRIM and RTRIM

IF OBJECT_ID(N'dbo.TRIM', N'FN') IS NOT NULL
    DROP FUNCTION dbo.TRIM;
GO
CREATE FUNCTION dbo.TRIM (@STR NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)
BEGIN
    RETURN(LTRIM(RTRIM(REPLACE(REPLACE(@STR ,CHAR(10),''),CHAR(13),''))))
END;
GO

Viewing contents of a .jar file

Your IDE should also support this. My IDE (SlickeEdit) calls it a "tag library." Simply add a tag library for the jar file, and you should be able to browse the classes and methods in a hierarchical manner.

How do I use dataReceived event of the SerialPort Port Object in C#?

First off I recommend you use the following constructor instead of the one you currently use:

new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);

Next, you really should remove this code:

// Wait 10 Seconds for data...
for (int i = 0; i < 1000; i++)
{
    Thread.Sleep(10);
    Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console
}

And instead just loop until the user presses a key or something, like so:

namespace serialPortCollection
{   class Program
    {
        static void Main(string[] args)
        {
            SerialPort sp = new SerialPort("COM10", 115200);
            sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler

            sp.Open();
            sp.WriteLine("$"); //Command to start Data Stream

            Console.ReadLine();

            sp.WriteLine("!"); //Stop Data Stream Command
            sp.Close();
        }

       // My Event Handler Method
        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            SerialPort spL = (SerialPort) sender;
            byte[] buf = new byte[spL.BytesToRead];
            Console.WriteLine("DATA RECEIVED!");
            spL.Read(buf, 0, buf.Length);
            foreach (Byte b in buf)
            {
                Console.Write(b.ToString());
            }
            Console.WriteLine();
        }
    }
}

Also, note the revisions to the data received event handler, it should actually print the buffer now.

UPDATE 1


I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34)

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread writeThread = new Thread(new ThreadStart(WriteThread));
            SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One);
            sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler

            sp.Open();
            sp.WriteLine("$"); //Command to start Data Stream

            writeThread.Start();

            Console.ReadLine();

            sp.WriteLine("!"); //Stop Data Stream Command
            sp.Close();
        }

        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            SerialPort spL = (SerialPort) sender;
            byte[] buf = new byte[spL.BytesToRead];
            Console.WriteLine("DATA RECEIVED!");
            spL.Read(buf, 0, buf.Length);
            foreach (Byte b in buf)
            {
                Console.Write(b.ToString() + " ");
            }
            Console.WriteLine();
        }

        private static void WriteThread()
        {
            SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One);
            sp2.Open();
            byte[] buf = new byte[100];
            for (byte i = 0; i < 100; i++)
            {
                buf[i] = i;
            }
            sp2.Write(buf, 0, buf.Length);
            sp2.Close();
        }
    }
}

UPDATE 2


Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding.

I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings.

Some tips on configuring the serial port:

Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device.

new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);

It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here:

http://www.lammertbies.nl/comm/info/RS-232_flow_control.html

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

if you need to add a date-time to your backup file name (Centos7) use the following:

/usr/bin/mysqldump -u USER -pPASSWD DBNAME | gzip > ~/backups/db.$(date +%F.%H%M%S).sql.gz

this will create the file: db.2017-11-17.231537.sql.gz

Finding a branch point with Git?

I've used git rev-list for this sort of thing. For example, (note the 3 dots)

$ git rev-list --boundary branch-a...master | grep "^-" | cut -c2-

will spit out the branch point. Now, it's not perfect; since you've merged master into branch A a couple of times, that'll split out a couple possible branch points (basically, the original branch point and then each point at which you merged master into branch A). However, it should at least narrow down the possibilities.

I've added that command to my aliases in ~/.gitconfig as:

[alias]
    diverges = !sh -c 'git rev-list --boundary $1...$2 | grep "^-" | cut -c2-'

so I can call it as:

$ git diverges branch-a master

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

FtpWebRequest Download File

   public void download(string remoteFile, string localFile)
    {
       private string host = "yourhost";
       private string user = "username";
       private string pass = "passwd";
       private FtpWebRequest ftpRequest = null;
       private FtpWebResponse ftpResponse = null;
       private Stream ftpStream = null;
       private int bufferSize = 2048;

        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpStream = ftpResponse.GetResponseStream();

            FileStream localFileStream = new FileStream(localFile, FileMode.Create);

            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

            try
            {
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
            }

            catch (Exception) {  }

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }

        catch (Exception) {  }
        return;
    }

Refresh Page C# ASP.NET

You shouldn't use:

Page.Response.Redirect(Page.Request.Url.ToString(), true);

because this might cause a runtime error.

A better approach is:

Page.Response.Redirect(Page.Request.Url.ToString(), false);
        Context.ApplicationInstance.CompleteRequest();

Skip over a value in the range function in python

You can use any of these:

# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
    print i

# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
    print i

# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
    print i
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print i

Insert line break inside placeholder attribute of a textarea?

very simple

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

struct in class

It's not clear what you're actually trying to achieve, but here are two alternatives:

class E
{
public:
    struct X
    {
        int v;
    };

    // 1. (a) Instantiate an 'X' within 'E':
    X x;
};

int main()
{
    // 1. (b) Modify the 'x' within an 'E':
    E e;
    e.x.v = 9;

    // 2. Instantiate an 'X' outside 'E':
    E::X x;
    x.v = 10;
}

Convert character to ASCII numeric value in java

If you want the ASCII value of all the characters in a String. You can use this :

String a ="asdasd";
int count =0;
for(int i : a.toCharArray())
    count+=i;

and if you want ASCII of a single character in a String you can go for :

(int)a.charAt(index);

How to install python developer package?

For me none of the packages mentioned above did help.

I finally managed to install lxml after running:

sudo apt-get install python3.5-dev

Get month and year from a datetime in SQL Server 2005

If you mean you want them back as a string, in that format;

SELECT 
  CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) 
FROM customers

Here are the other format options

Entity Framework 6 Code first Default value

Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

for the same property.

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

Check to see the database is up. Log onto the server, set the ORACLE_SID environment variable to your database SID, and run SQL*Plus as a local connection.

How to implement a binary search tree in Python?

The Op's Tree.insert method qualifies for the "Gross Misnomer of the Week" award -- it doesn't insert anything. It creates a node which is not attached to any other node (not that there are any nodes to attach it to) and then the created node is trashed when the method returns.

For the edification of @Hugh Bothwell:

>>> class Foo(object):
...    bar = None
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar
>>> a.bar = 42
>>> b.bar
>>> b.bar = 666
>>> a.bar
42
>>> b.bar
666
>>>

How to log a method's execution time exactly in milliseconds?

Since you want to optimize time moving from one page to another in a UIWebView, does it not mean you really are looking to optimize the Javascript used in loading these pages?

To that end, I'd look at a WebKit profiler like that talked about here:

http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/

Another approach would be to start at a high level, and think how you can design the web pages in question to minimize load times using AJAX style page loading instead of refreshing the whole webview each time.

Removing address bar from browser (to view on Android)

If you've loaded jQuery, you can see if the height of the content is greater than the viewport height. If not, then you can make it that height (or a little less). I ran the following code in WVGA800 mode in the Android emulator, and then ran it on my Samsung Galaxy Tab, and in both cases it hid the addressbar.

$(document).ready(function() {

  if (navigator.userAgent.match(/Android/i)) {
    window.scrollTo(0,0); // reset in case prev not scrolled  
    var nPageH = $(document).height();
    var nViewH = window.outerHeight;
    if (nViewH > nPageH) {
      nViewH -= 250;
      $('BODY').css('height',nViewH + 'px');
    }
    window.scrollTo(0,1);
  }

});

How to change UIPickerView height

As far as I know, it's impossible to shrink the UIPickerView. I also haven't actually seen a shorter one used anywhere. My guess is that it was a custom implementation if they did manage to shrink it.

Arrays.asList() of an array

there are two cause of this exception:

1

Arrays.asList(factors) returns a List<int[]> where factors is an int array

2

you forgot to add the type parameter to:

ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));

with:

ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  

resulting in a compile-time error:

found   : java.util.List<int[]>
required: java.util.List<java.lang.Integer>

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me, I changed class='carousel-item' to class='item' like this

<div class="item">
    <img class="img-responsive" src="..." alt="...">
</div>

Override element.style using CSS

element.style comes from the markup.

<li style="display: none;">

Just remove the style attribute from the HTML.

Precision String Format Specifier In Swift

Also with rounding:

extension Float
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).floatValue
    }
}

extension Double
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).doubleValue
    }
}

x = 0.90695652173913
x.roundTo(".2")
println(x) //0.91

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TestPOC</display-name>

  <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

Where does the slf4j log file get saved?

The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)

-Dlogging.config={file_location}\log4j2.xml 

or this:

-Dlog4j.configurationFile={file_location}\log4j2.xml

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

How to get all elements which name starts with some string?

You can try using jQuery with the Attribute Contains Prefix Selector.

$('[id|=q1_]')

Haven't tested it though.

How can I use a reportviewer control in an asp.net mvc 3 razor view?

It is possible to get an SSRS report to appear on an MVC page without using iFrames or an aspx page.

The bulk of the work is explained here:

http://geekswithblogs.net/stun/archive/2010/02/26/executing-reporting-services-web-service-from-asp-net-mvc-using-wcf-add-service-reference.aspx

The link explains how to create a web service and MVC action method that will allow you to call the reporting service and render result of the web service as an Excel file. With a small change to the code in the example you can render it as HTML.

All you need to do then is use a button to call a javascript function that makes an AJAX call to your MVC action which returns the HTML of the report. When the AJAX call returns with the HTML just replace a div with this HTML.

We use AngularJS so my example below is in that format, but it could be any javascript function

$scope.getReport = function()
{
    $http({
        method: "POST",
        url: "Report/ExportReport",
        data: 
                [
                    { Name: 'DateFrom', Value: $scope.dateFrom },
                    { Name: 'DateTo', Value: $scope.dateTo },
                    { Name: 'LocationsCSV', Value: $scope.locationCSV }
                ]

    })
    .success(function (serverData)
    {
        $("#ReportDiv").html(serverData);
    });

};

And the Action Method - mainly taken from the above link...

    [System.Web.Mvc.HttpPost]
    public FileContentResult ExportReport([FromBody]List<ReportParameterModel> parameters)
    {
         byte[] output;
         string extension, mimeType, encoding;
         string reportName = "/Reports/DummyReport";
         ReportService.Warning[] warnings;
         string[] ids;

     ReportExporter.Export(
            "ReportExecutionServiceSoap" 
            new NetworkCredential("username", "password", "domain"),
            reportName,
            parameters.ToArray(),
            ExportFormat.HTML4,
            out output,
            out extension,
            out mimeType,
            out encoding,
            out warnings,
            out ids
        );

        //-------------------------------------------------------------
        // Set HTTP Response Header to show download dialog popup
        //-------------------------------------------------------------
        Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
        return new FileContentResult(output, mimeType);
    }

So the result is that you get to pass parameters to an SSRS reporting server which returns a report which you render as HTML. Everything appears on the one page. This is the best solution I could find

Split list into smaller lists (split in half)

Here is a common solution, split arr into count part

def split(arr, count):
     return [arr[i::count] for i in range(count)]

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget generally works in this way, but some sites may have problems and it may create too many unnecessary html files. In order to make this work easier and to prevent unnecessary file creation, I am sharing my getwebfolder script, which is the first linux script I wrote for myself. This script downloads all content of a web folder entered as parameter.

When you try to download an open web folder by wget which contains more then one file, wget downloads a file named index.html. This file contains a file list of the web folder. My script converts file names written in index.html file to web addresses and downloads them clearly with wget.

Tested at Ubuntu 18.04 and Kali Linux, It may work at other distros as well.

Usage :

  • extract getwebfolder file from zip file provided below

  • chmod +x getwebfolder (only for first time)

  • ./getwebfolder webfolder_URL

such as ./getwebfolder http://example.com/example_folder/

Download Link

Details on blog

top nav bar blocking top content of the page

Add to your CSS:

body { 
    padding-top: 65px; 
}

From the Bootstrap docs:

The fixed navbar will overlay your other content, unless you add padding to the top of the body.

How to get pip to work behind a proxy server

at least pip3 also works without "=", however, instead of "http" you might need "https"

Final command, which worked for me:

sudo pip3 install --proxy https://{proxy}:{port} {BINARY}

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.

Javascript - Track mouse position

ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example

How to fix Subversion lock error

Subversion supports a command named "Cleanup"; it is used to release the locks on a projectenter image description here

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I could resolve this problem in Kotlin with help of @JacksonProperty annotation. Usage example for above case would be:

import com.fasterxml.jackson.annotation.JsonProperty
...
data class Station(
     @JacksonProperty("repsol_id") val repsol_id: String,
     @JacksonProperty("name") val name: String,
...

How do I extract value from Json

    //import java.util.ArrayList;
    //import org.bson.Document;

    Document root = Document.parse("{\n"
            + "  \"name\": \"Json\",\n"
            + "  \"detail\": {\n"
            + "    \"first_name\": \"Json\",\n"
            + "    \"last_name\": \"Scott\",\n"
            + "    \"age\": \"23\"\n"
            + "  },\n"
            + "  \"status\": \"success\"\n"
            + "}");

    System.out.println(((String) root.get("name")));
    System.out.println(((String) ((Document) root.get("detail")).get("first_name")));
    System.out.println(((String) ((Document) root.get("detail")).get("last_name")));
    System.out.println(((String) ((Document) root.get("detail")).get("age")));
    System.out.println(((String) root.get("status")));

How can you program if you're blind?

I think that this would work well in extreme programming using the pair programming principle. If you're making software for blind people, who better to make it then someone who would literally be in touch with the business requirements, so I don't think it's very far fetched at all.

As for writing code, well unless there was some kind of feedback I think a person may struggle with syntax. Audio feedback may help to a point though.

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

Is there an addHeaderView equivalent for RecyclerView?

I made an implementation based on @hister's one for my personal purposes, but using inheritance.

I hide the implementation details mechanisms (like add 1 to itemCount, subtract 1 from position) in an abstract super class HeadingableRecycleAdapter, by implementing required methods from Adapter like onBindViewHolder, getItemViewType and getItemCount, making that methods final, and providing new methods with hidden logic to client:

  • onAddViewHolder(RecyclerView.ViewHolder holder, int position),
  • onCreateViewHolder(ViewGroup parent),
  • itemCount()

Here are the HeadingableRecycleAdapter class and a client. I left the header layout a bit hard-coded because it fits my needs.

public abstract class HeadingableRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int HEADER_VIEW_TYPE = 0;

    @LayoutRes
    private int headerLayoutResource;
    private String headerTitle;
    private Context context;

    public HeadingableRecycleAdapter(@LayoutRes int headerLayoutResourceId, String headerTitle, Context context) {
        this.headerLayoutResource = headerLayoutResourceId;
        this.headerTitle = headerTitle;
        this.context = context;
    }

    public Context context() {
        return context;
    }

    @Override
    public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == HEADER_VIEW_TYPE) {
            return new HeaderViewHolder(LayoutInflater.from(context).inflate(headerLayoutResource, parent, false));
        }
        return onCreateViewHolder(parent);
    }

    @Override
    public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        if (viewType == HEADER_VIEW_TYPE) {
            HeaderViewHolder vh = (HeaderViewHolder) holder;
            vh.bind(headerTitle);
        } else {
            onAddViewHolder(holder, position - 1);
        }
    }

    @Override
    public final int getItemViewType(int position) {
        return position == 0 ? 0 : 1;
    }

    @Override
    public final int getItemCount() {
        return itemCount() + 1;
    }

    public abstract int itemCount();

    public abstract RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent);

    public abstract void onAddViewHolder(RecyclerView.ViewHolder holder, int position);

}



@PerActivity
public class IngredientsAdapter extends HeadingableRecycleAdapter {
    public static final String TITLE = "Ingredients";
    private List<Ingredient> itemList;


    @Inject
    public IngredientsAdapter(Context context) {
        super(R.layout.layout_generic_recyclerview_cardified_header, TITLE, context);
    }

    public void setItemList(List<Ingredient> itemList) {
        this.itemList = itemList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        return new ViewHolder(LayoutInflater.from(context()).inflate(R.layout.item_ingredient, parent, false));
    }

    @Override
    public void onAddViewHolder(RecyclerView.ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder) holder;
        vh.bind(itemList.get(position));
    }

    @Override
    public int itemCount() {
        return itemList == null ? 0 : itemList.size();
    }

    private String getQuantityFormated(double quantity, String measure) {
        if (quantity == (long) quantity) {
            return String.format(Locale.US, "%s %s", String.valueOf(quantity), measure);
        } else {
            return String.format(Locale.US, "%.1f %s", quantity, measure);
        }
    }


    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.text_ingredient)
        TextView txtIngredient;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void bind(Ingredient ingredient) {
            String ingredientText = ingredient.getIngredient();
            txtIngredient.setText(String.format(Locale.US, "%s %s ", getQuantityFormated(ingredient.getQuantity(),
                    ingredient.getMeasure()), Character.toUpperCase(ingredientText.charAt(0)) +
                    ingredientText
                            .substring(1)));
        }
    }
}

How to convert List to Json in Java

You need an external library for this.

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google GSON is one of such libraries

You can also take a look here for examples on converting Java object collection to JSON string.

Android Animation Alpha

View.setOnTouchListener { v, event ->
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            v.alpha = 0f
            v.invalidate()
        }
        MotionEvent.ACTION_UP -> {
            v.alpha = 1f
            v.invalidate()


        }
    }
    false
}

Changing capitalization of filenames in Git

To bulk git mv files to lowercase on macOS:

for f in *; do git mv "$f" "`echo $f | tr "[:upper:]" "[:lower:]"`"; done

It will lowercase all files in a folder.

Copy multiple files from one directory to another from Linux shell

You can use brace expansion in bash:

cp /home/ankur/folder/{file1,abc,xyz} /path/to/target

What is the proper way to check and uncheck a checkbox in HTML5?

According to HTML5 drafts, the checked attribute is a “boolean attribute”, and “The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” It is the name of the attribute that matters, and suffices. Thus, to make a checkbox initially checked, you use

<input type=checkbox checked>

By default, in the absence of the checked attribute, a checkbox is initially unchecked:

<input type=checkbox>

Keeping things this way keeps them simple, but if you need to conform to XML syntax (i.e. to use HTML5 in XHTML linearization), you cannot use an attribute name alone. Then the allowed (as per HTML5 drafts) values are the empty string and the string checked, case insensitively. Example:

<input type="checkbox" checked="checked" />

How do I disable text selection with CSS or JavaScript?

I'm not sure if you can turn it off, but you can change the colors of it :)

myDiv::selection,
myDiv::-moz-selection,
myDiv::-webkit-selection {
    background:#000;
    color:#fff;
}

Then just match the colors to your "darky" design and see what happens :)

Calculate difference between 2 date / times in Oracle SQL

You can substract dates in Oracle. This will give you the difference in days. Multiply by 24 to get hours, and so on.

SQL> select oldest - creation from my_table;

If your date is stored as character data, you have to convert it to a date type first.

SQL> select 24 * (to_date('2009-07-07 22:00', 'YYYY-MM-DD hh24:mi') 
             - to_date('2009-07-07 19:30', 'YYYY-MM-DD hh24:mi')) diff_hours 
       from dual;

DIFF_HOURS
----------
       2.5

Note:

This answer applies to dates represented by the Oracle data type DATE. Oracle also has a data type TIMESTAMP, which can also represent a date (with time). If you subtract TIMESTAMP values, you get an INTERVAL; to extract numeric values, use the EXTRACT function.

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

How to get parameters from the URL with JSP

About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
    • session: The session object for the client. See Maintaining Client State.
    • request: The request triggering the execution of the JSP page. See Getting Information from Requests.
    • response: The response returned by the JSP page. See Constructing Responses.
  • In addition, several implicit objects are available that allow easy access to the following objects:
    • param: Maps a request parameter name to a single value
    • paramValues: Maps a request parameter name to an array of values
    • header: Maps a request header name to a single value
    • headerValues: Maps a request header name to an array of values
    • cookie: Maps a cookie name to a single cookie
    • initParam: Maps a context initialization parameter name to a single value
  • Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
    • pageScope: Maps page-scoped variable names to their values
    • requestScope: Maps request-scoped variable names to their values
    • sessionScope: Maps session-scoped variable names to their values
    • applicationScope: Maps application-scoped variable names to their values

The interesting parts are in bold :)

So, to answer your question, you should be able to access it like this (using EL):

${param.accountID}

Or, using JSP Scriptlets (not recommended):

<%
    String accountId = request.getParameter("accountID");
%>

Put content in HttpResponseMessage object?

The easiest single-line solution is to use

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };

For serialized JSON content:

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

If you are on unix-like systems.

Starting in MongoDB 4.4, a startup error is generated if the ulimit value for number of open files is under 64000. View the current val

$ ulimit -n

Change value

$ ulimit -n <val>

Clearing coverage highlighting in Eclipse

If you remove the coverage session, also the coverage coloring will disappear. For this, hit Remove Session or Remove All Sessions in the Coverage view's toolbar.

http://eclemma.org/faq.html

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

Single Line Nested For Loops

Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops

for x in range(1, 10, 1):
     for y in range(1,x):
             print y,
        print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Check if value exists in column in VBA

Simplest is to use Match

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
    ' String is in range

In Tensorflow, get the names of all the Tensors in a graph

I'll try to summarize the answers:

To get all nodes in the graph: (type tensorflow.core.framework.node_def_pb2.NodeDef)

all_nodes = [n for n in tf.get_default_graph().as_graph_def().node]

To get all ops in the graph: (type tensorflow.python.framework.ops.Operation)

all_ops = tf.get_default_graph().get_operations()

To get all variables in the graph: (type tensorflow.python.ops.resource_variable_ops.ResourceVariable)

all_vars = tf.global_variables()

To get all tensors in the graph: (type tensorflow.python.framework.ops.Tensor)

all_tensors = [tensor for op in tf.get_default_graph().get_operations() for tensor in op.values()]

To get all placeholders in the graph: (type tensorflow.python.framework.ops.Tensor)

all_placeholders = [placeholder for op in tf.get_default_graph().get_operations() if op.type=='Placeholder' for placeholder in op.values()]

Tensorflow 2

To get the graph in Tensorflow 2, instead of tf.get_default_graph() you need to instantiate a tf.function first and access the graph attribute, for example:

graph = func.get_concrete_function().graph

where func is a tf.function

How to add external fonts to android application

One more point in addition to the above answers. When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}

Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.

Javascript date.getYear() returns 111 in 2011?

From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.

var now = new Date(),
    year = now.getYear() + 1900;

How to disable Django's CSRF validation?

If you want disable it in Global, you can write a custom middleware, like this

from django.utils.deprecation import MiddlewareMixin

class DisableCsrfCheck(MiddlewareMixin):

    def process_request(self, req):
        attr = '_dont_enforce_csrf_checks'
        if not getattr(req, attr, False):
            setattr(req, attr, True)

then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware

Can Selenium interact with an existing browser session?

I got a solution in python, I modified the webdriver class bassed on PersistenBrowser class that I found.

https://github.com/axelPalmerin/personal/commit/fabddb38a39f378aa113b0cb8d33391d5f91dca5

replace the webdriver module /usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py

Ej. to use:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

runDriver = sys.argv[1]
sessionId = sys.argv[2]

def setBrowser():
    if eval(runDriver):
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                     desired_capabilities=DesiredCapabilities.CHROME,
                     )
    else:
        webdriver = w.Remote(command_executor='http://localhost:4444/wd/hub',
                             desired_capabilities=DesiredCapabilities.CHROME,
                             session_id=sessionId)

    url = webdriver.command_executor._url
    session_id = webdriver.session_id
    print url
    print session_id
    return webdriver

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Has a fixed been published? Appears issue originally affected v11/12 due to a "Compiler overhaul" back in 2013. With discussion on related issues in Jira up to end of 2014. http://youtrack.jetbrains.com/issue/IDEA-98425

Also on Jira IDEA-98425 was marked fixed but unverified (on v12.0.3). None of the following work-around helped resolve this "Unable to Resolve Symbol" issue with Version 13.1.1 on Windows

a. Delete .IdealIC13 folder (Then, File \ Invalidate Caches / Restart)

b. From Maven Projects window,

b.1 mvn -U idea:idea –>Executing this maven goal suppose to reload the dependencies. This works prev, but since last FRI, executing this maven goal failed as it tried to recompile the project (Of course it fails as "Unable to resolve Symbols", that's what I am trying to fix by running this command in the first place) mvn -version — shows maven version referenced 3.2.5 and that it's working

b.2 Simply right click project, and Reimport

b.3 File \ Invalidate Caches / Restart

c. Tried both Enable & Disable this setting: File -> Settings -> Maven -> Importing -> "Use maven3 to import project"

d. Settings \ Maven \ Multiproject build fail policy = Fail at end (instead of Default)

Nothing works. What's happenning to IntelliJ support on Maven.

https://youtrack.jetbrains.com/issue/IDEA-99302

From JetBeans release history, https://www.jetbrains.com/company/history.jsp

IntelliJ v14 NOV 2014

IntelliJ v13 DEC 2013

I'd assume v12 fixed (although unverified) would be incorporated in subsequent releases. Any one having similar problems with which IntelliJ version? Please share your experience. IntelliJ maven support seems broken.

Python SQLite: database is locked

I found this worked for my needs. (thread locking) YMMV

conn = sqlite3.connect(database, timeout=10)

https://docs.python.org/3/library/sqlite3.html

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

How to update the constant height constraint of a UIView programmatically?

You can update your constraint with a smooth animation if you want, see the chunk of code below:

heightOrWidthConstraint.constant = 100
UIView.animate(withDuration: animateTime, animations:{
self.view.layoutIfNeeded()
})

Get last 5 characters in a string

str.Substring(str.Length - 5)

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

Calling a JavaScript function named in a variable

This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:

eval('var myfunc = ' + variable);  myfunc(args, ...);

If you don't need to pass in arguments this might be simpler.

eval(variable + '();');

Standard dry-code warning applies.

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Since Java 8, we can achieve this as follows:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

The output will be : "07/25/2017"

convert datetime to date format dd/mm/yyyy

You have to pass the CultureInfo to get the result with slash(/)

DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)

Linq to SQL how to do "where [column] in (list of values)"

 var filterTransNos = (from so in db.SalesOrderDetails
                    where  ItemDescription.Contains(ItemDescription)
                            select new { so.TransNo }).AsEnumerable();    


listreceipt = listreceipt.Where(p => filterTransNos.Any(p2 => p2.TransNo == p.TransNo)).ToList();

How do you create a Swift Date object?

Swift has its own Date type. No need to use NSDate.

Creating a Date and Time in Swift

In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you the current date and time:

let currentDateTime = Date()

For creating other date-times, you can use one of the following methods.

Method 1

If you know the number of seconds before or after the 2001 reference date, you can use that.

let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

Method 2

Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)

Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.

Method 3

The most succinct way (but not necessarily the best) could be to use DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

The Unicode technical standards show other formats that DateFormatter supports.

Notes

See my full answer for how to display the date and time in a readable format. Also read these excellent articles:

Java associative-array

Thinking more about it, I would like to throw out tuples as a more general-purpose way of dealing with this problem. While tuples are not native to Java, I use Javatuples to provide me the same functionality which would exist in other languages. An example of how to deal with the question asked is

Map<Pair<Integer, String>, String> arr = new HashMap<Pair<Integer, String>, String>();
Pair p1 = new Pair(0, "name");
arr.put(p1, "demo");

I like this approach because it can be extended to triples and other higher ordered groupings with api provided classes and methods.

create table in postgreSQL

Replace bigint(20) not null auto_increment by bigserial not null and datetime by timestamp

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

Adding ID's to google map markers

I have a simple Location class that I use to handle all of my marker-related things. I'll paste my code below for you to take a gander at.

The last line(s) is what actually creates the marker objects. It loops through some JSON of my locations, which look something like this:

{"locationID":"98","name":"Bergqvist Järn","note":null,"type":"retail","address":"Smidesvägen 3","zipcode":"69633","city":"Askersund","country":"Sverige","phone":"0583-120 35","fax":null,"email":null,"url":"www.bergqvist-jb.com","lat":"58.891079","lng":"14.917371","contact":null,"rating":"0","distance":"45.666885421019"}

Here is the code:

If you look at the target() method in my Location class, you'll see that I keep references to the infowindow's and can simply open() and close() them because of a reference.

See a live demo: http://ww1.arbesko.com/en/locator/ (type in a Swedish city, like stockholm, and hit enter)

var Location = function() {
    var self = this,
        args = arguments;

    self.init.apply(self, args);
};

Location.prototype = {
    init: function(location, map) {
        var self = this;

        for (f in location) { self[f] = location[f]; }

        self.map = map;
        self.id = self.locationID;

        var ratings = ['bronze', 'silver', 'gold'],
            random = Math.floor(3*Math.random());

        self.rating_class = 'blue';

        // this is the marker point
        self.point = new google.maps.LatLng(parseFloat(self.lat), parseFloat(self.lng));
        locator.bounds.extend(self.point);

        // Create the marker for placement on the map
        self.marker = new google.maps.Marker({
            position: self.point,
            title: self.name,
            icon: new google.maps.MarkerImage('/wp-content/themes/arbesko/img/locator/'+self.rating_class+'SmallMarker.png'),
            shadow: new google.maps.MarkerImage(
                                        '/wp-content/themes/arbesko/img/locator/smallMarkerShadow.png',
                                        new google.maps.Size(52, 18),
                                        new google.maps.Point(0, 0),
                                        new google.maps.Point(19, 14)
                                    )
        });

        google.maps.event.addListener(self.marker, 'click', function() {
            self.target('map');
        });

        google.maps.event.addListener(self.marker, 'mouseover', function() {
            self.sidebarItem().mouseover();
        });

        google.maps.event.addListener(self.marker, 'mouseout', function() {
            self.sidebarItem().mouseout();
        });

        var infocontent = Array(
            '<div class="locationInfo">',
                '<span class="locName br">'+self.name+'</span>',
                '<span class="locAddress br">',
                    self.address+'<br/>'+self.zipcode+' '+self.city+' '+self.country,
                '</span>',
                '<span class="locContact br">'
        );

        if (self.phone) {
            infocontent.push('<span class="item br locPhone">'+self.phone+'</span>');
        }

        if (self.url) {
            infocontent.push('<span class="item br locURL"><a href="http://'+self.url+'">'+self.url+'</a></span>');
        }

        if (self.email) {
            infocontent.push('<span class="item br locEmail"><a href="mailto:'+self.email+'">Email</a></span>');
        }

        // Add in the lat/long
        infocontent.push('</span>');

        infocontent.push('<span class="item br locPosition"><strong>Lat:</strong> '+self.lat+'<br/><strong>Lng:</strong> '+self.lng+'</span>');

        // Create the infowindow for placement on the map, when a marker is clicked
        self.infowindow = new google.maps.InfoWindow({
            content: infocontent.join(""),
            position: self.point,
            pixelOffset: new google.maps.Size(0, -15) // Offset the infowindow by 15px to the top
        });

    },

    // Append the marker to the map
    addToMap: function() {
        var self = this;

        self.marker.setMap(self.map);
    },

    // Creates a sidebar module for the item, connected to the marker, etc..
    sidebarItem: function() {
        var self = this;

        if (self.sidebar) {
            return self.sidebar;
        }

        var li = $('<li/>').attr({ 'class': 'location', 'id': 'location-'+self.id }),
            name = $('<span/>').attr('class', 'locationName').html(self.name).appendTo(li),
            address = $('<span/>').attr('class', 'locationAddress').html(self.address+' <br/> '+self.zipcode+' '+self.city+' '+self.country).appendTo(li);

        li.addClass(self.rating_class);

        li.bind('click', function(event) {
            self.target();
        });

        self.sidebar = li;

        return li;
    },

    // This will "target" the store. Center the map and zoom on it, as well as 
    target: function(type) {
        var self = this;

        if (locator.targeted) {
            locator.targeted.infowindow.close();
        }

        locator.targeted = this;

        if (type != 'map') {
            self.map.panTo(self.point);
            self.map.setZoom(14);
        };

        // Open the infowinfow
        self.infowindow.open(self.map);
    }
};

for (var i=0; i < locations.length; i++) {
    var location = new Location(locations[i], self.map);
    self.locations.push(location);

    // Add the sidebar item
    self.location_ul.append(location.sidebarItem());

    // Add the map!
    location.addToMap();
};

Set padding for UITextField with UITextBorderStyleNone

I was based off Nate's solution, but then i found it that this causes problems when you use the leftView/rightView properties, so its better tune the super's implementation, because it will take the left/right view's into account.

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect ret = [super textRectForBounds:bounds];
    ret.origin.x = ret.origin.x + 5;
    ret.size.width = ret.size.width - 10;
    return ret;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

Get user's current location

An IP gives you an quite unreliable location, you could Ajax the location upon load with JS if it isn't critical to have the location at first. (Also, the user need's to give you it's permission to access it.)

Html5 Geolocation

Get Path from another app (WhatsApp)

It works for me for opening small text file... I didn't try in other file

protected void viewhelper(Intent intent) {
    Uri a = intent.getData();
    if (!a.toString().startsWith("content:")) {
        return;
    }
    //Ok Let's do it
    String content = readUri(a);
    //do something with this content
}

here is the readUri(Uri uri) method

private String readUri(Uri uri) {
    InputStream inputStream = null;
    try {
        inputStream = getContentResolver().openInputStream(uri);
        if (inputStream != null) {
            byte[] buffer = new byte[1024];
            int result;
            String content = "";
            while ((result = inputStream.read(buffer)) != -1) {
                content = content.concat(new String(buffer, 0, result));
            }
            return content;
        }
    } catch (IOException e) {
        Log.e("receiver", "IOException when reading uri", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e("receiver", "IOException when closing stream", e);
            }
        }
    }
    return null;
}

I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.

Manifest file:

    <activity android:name=".MainActivity">
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

You need to add

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*
     *    Your OnCreate
     */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    //VIEW"
    if (Intent.ACTION_VIEW.equals(action) && type != null) {
        viewhelper(intent); // Handle text being sent
    }
  }

Multiline text in JLabel

You can also use a JXLabel from the SwingX library.

JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);

Why is char[] preferred over String for passwords?

The answer has already been given, but I'd like to share an issue that I discovered lately with Java standard libraries. While they take great care now of replacing password strings with char[] everywhere (which of course is a good thing), other security-critical data seems to be overlooked when it comes to clearing it from memory.

I'm thinking of e.g. the PrivateKey class. Consider a scenario where you would load a private RSA key from a PKCS#12 file, using it to perform some operation. Now in this case, sniffing the password alone wouldn't help you much as long as physical access to the key file is properly restricted. As an attacker, you would be much better off if you obtained the key directly instead of the password. The desired information can be leaked manifold, core dumps, a debugger session or swap files are just some examples.

And as it turns out, there is nothing that lets you clear the private information of a PrivateKey from memory, because there's no API that lets you wipe the bytes that form the corresponding information.

This is a bad situation, as this paper describes how this circumstance could be potentially exploited.

The OpenSSL library for example overwrites critical memory sections before private keys are freed. Since Java is garbage-collected, we would need explicit methods to wipe and invalidate private information for Java keys, which are to be applied immediately after using the key.

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

How to get the IP address of the docker host from inside a docker container

On Ubuntu, hostname command can be used with the following options:

  • -i, --ip-address addresses for the host name
  • -I, --all-ip-addresses all addresses for the host

For example:

$ hostname -i
172.17.0.2

To assign to the variable, the following one-liner can be used:

IP=$(hostname -i)

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

How can I make my string property nullable?

string is by default Nullable ,you don't need to do anything to make string Nullable

What's the difference between git reset --mixed, --soft, and --hard?

A short answer in what context the 3 options are used:

To keep the current changes in the code but to rewrite the commit history:

  • soft: You can commit everything at once and create a new commit with a new description (if you use torotise git or any most other GUIs, this is the one to use, as you can still tick which files you want in the commit and make multiple commits that way with different files. In Sourcetree all files would be staged for commit.)
  • mixed: You will have to add the individual files again to the index before you make commits (in Sourcetree all the changed files would be unstaged)

To actually lose your changes in the code as well:

  • hard: you don't just rewrite history but also lose all your changes up to the point you reset

What's the best way to calculate the size of a directory in .NET?

var size = new DirectoryInfo("E:\\").GetDirectorySize();

and here's the code behind this Extension method

public static long GetDirectorySize(this System.IO.DirectoryInfo directoryInfo, bool recursive = true)
{
    var startDirectorySize = default(long);
    if (directoryInfo == null || !directoryInfo.Exists)
        return startDirectorySize; //Return 0 while Directory does not exist.

    //Add size of files in the Current Directory to main size.
    foreach (var fileInfo in directoryInfo.GetFiles())
        System.Threading.Interlocked.Add(ref startDirectorySize, fileInfo.Length);

    if (recursive) //Loop on Sub Direcotries in the Current Directory and Calculate it's files size.
        System.Threading.Tasks.Parallel.ForEach(directoryInfo.GetDirectories(), (subDirectory) =>
    System.Threading.Interlocked.Add(ref startDirectorySize, GetDirectorySize(subDirectory, recursive)));

    return startDirectorySize;  //Return full Size of this Directory.
}

Spring 3 MVC resources and tag <mvc:resources />

This worked for me

In JSP, to view the image

<img src="${pageContext.request.contextPath}/resources/images/slide-are.jpg">

In dispatcher-servlet.xml

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

Remove specific commit

The algorithm that Git uses when calculating diff's to be reverted requires that

  1. the lines being reverted are not modified by any later commits.
  2. that there not be any other "adjacent" commits later in the history.

The definition of "adjacent" is based on the default number of lines from a context diff, which is 3. So if 'myfile' was constructed like this:

$ cat >myfile <<EOF
line 1
junk
junk
junk
junk
line 2
junk
junk
junk
junk
line 3
EOF
$ git add myfile
$ git commit -m "initial check-in"
 1 files changed, 11 insertions(+), 0 deletions(-)
 create mode 100644 myfile

$ perl -p -i -e 's/line 2/this is the second line/;' myfile
$ git commit -am "changed line 2 to second line"
[master d6cbb19] changed line 2
 1 files changed, 1 insertions(+), 1 deletions(-)

$ perl -p -i -e 's/line 3/this is the third line/;' myfile
$ git commit -am "changed line 3 to third line"
[master dd054fe] changed line 3
 1 files changed, 1 insertions(+), 1 deletions(-)

$ git revert d6cbb19
Finished one revert.
[master 2db5c47] Revert "changed line 2"
 1 files changed, 1 insertions(+), 1 deletions(-)

Then it all works as expected.

The second answer was very interesting. There is a feature which has not yet been officially released (though it is available in Git v1.7.2-rc2) called Revert Strategy. You can invoke git like this:

git revert --strategy resolve <commit>

and it should do a better job figuring out what you meant. I do not know what the list of available strategies is, nor do I know the definition of any strategy.

Parse String to Date with Different Format in Java

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

Maven: Failed to retrieve plugin descriptor error

In my case, even my system is not behind proxy, I got same issue. I was able to resolve by typing mvn help:archetype before mvn archetype:generate

How to search for a string in cell array in MATLAB?

I see that everybody missed the most important flaw in your code:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}

should be:

strs = {'HA' 'KU' 'NA' 'MA' 'TATA'} 

or

strs = {'HAKUNA' 'MATATA'}

Now if you stick to using

ind=find(ismember(strs,'KU'))

You'll have no worries :).

Maven: best way of linking custom external JAR to my project?

Change your systemPath.

<dependency>
  <groupId>stuff</groupId>
  <artifactId>library</artifactId>
  <version>1.0</version>
  <systemPath>${project.basedir}/MyLibrary.jar</systemPath>
  <scope>system</scope>
</dependency>

Use css gradient over background image

_x000D_
_x000D_
#multiple-background{_x000D_
 box-sizing: border-box;_x000D_
 width: 123px;_x000D_
 height: 30px;_x000D_
 font-size: 12pt;_x000D_
 border-radius: 7px;  _x000D_
 background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
 background-repeat: no-repeat, repeat;_x000D_
 background-position: 5px center, 0px 0px;_x000D_
    background-size: 18px 18px, 100% 100%;_x000D_
 color: white; _x000D_
 border: 1px solid #e4f6df;_x000D_
 box-shadow: .25px .25px .5px .5px black;_x000D_
 padding: 3px 10px 0px 5px;_x000D_
 text-align: right;_x000D_
 }
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
_x000D_
_x000D_

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

How do I choose the URL for my Spring Boot webapp?

The server.contextPath or server.context-path works if

in pom.xml

  1. packing should be war not jar
  2. Add following dependencies

    <dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Tomcat/TC server -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
     </dependency>
    

    In eclipse, right click on project --> Run as --> Spring Boot App.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Move it to the Trusted Sites zone by either adding it to a Trusted Sites list or local setting. This will move it out of Intranet Zone and will not be rendered in Compat. View.

How do shift operators work in Java?

System.out.println(Integer.toBinaryString(2 << 11)); 

Shifts binary 2(10) by 11 times to the left. Hence: 1000000000000

System.out.println(Integer.toBinaryString(2 << 22)); 

Shifts binary 2(10) by 22 times to the left. Hence : 100000000000000000000000

System.out.println(Integer.toBinaryString(2 << 33)); 

Now, int is of 4 bytes,hence 32 bits. So when you do shift by 33, it's equivalent to shift by 1. Hence : 100

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

how to include js file in php?

I found a different solution that I like:

<script>
    <?php require_once("/path/to/file.js");?>
</script>

Also works with style-tags and .css-files in the same way.

PHP Undefined Index

The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);

How to ignore certain files in Git

  1. Go to .gitignore file and add the entry for the files you want to ignore
  2. Run git rm -r --cached .
  3. Now run git add .

Add column to dataframe with constant value

You can use insert to specify where you want to new column to be. In this case, I use 0 to place the new column at the left.

df.insert(0, 'Name', 'abc')

  Name        Date  Open  High  Low  Close
0  abc  01-01-2015   565   600  400    450

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

WPF MVVM: How to close a window

I just completed a blog post on this very topic. In a nutshell, add an Action property to your ViewModel with get and set accessors. Then define the Action from your View constructor. Finally, invoke your action in the bound command that should close the window.

In the ViewModel:

public Action CloseAction  { get; set;}

and in the View constructor:

private View()
{
    InitializeComponent();
    ViewModel vm = new ViewModel();
    this.DataContext = vm;
    if ( vm.CloseAction == null )
        vm.CloseAction = new Action(this.Close);
}

Finally, in whatever bound command that should close the window, we can simply invoke

CloseAction(); // Calls Close() method of the View

This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.

How do you connect to multiple MySQL databases on a single webpage?

if you are using mysqli and have two db_connection file. like first one is

define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');

$connMitra = new mysqli(HOST, USER, PASS, **DB1**);

second one is

    define('HOST','localhost');
    define('USER','user');
    define('PASS','passs');
    define(**'DB2**','database_name1');

    $connMitra = new mysqli(HOST, USER, PASS, **DB2**);

SO just change the name of parameter pass in mysqli like DB1 and DB2. if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

'was not declared in this scope' error

You need to declare y and c outside the scope of the if/else statement. A variable is only valid inside the scope it is declared (and a scope is marked with { })

#include <iostream> 
using namespace std; 
//Using the Gaussian algorithm 
int dayofweek(int date, int month, int year ){ 
int d=date; 
int y, c;
if (month==1||month==2) 
        {y=((year-1)%100);c=(year-1)/100;} 
else 
        {y=year%100;c=year/100;} 
int m=(month+9)%12+1; 
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); 
return product%7; 
} 

int main(){ 
cout<<dayofweek(19,1,2054); 
return 0; 
} 

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace