Programs & Examples On #Interactive mode

MS Access DB Engine (32-bit) with Office 64-bit

Even tried all suggestions, in my case (Office x64 - Visual Studio 2017), the only way to have both access engines on a Office 64x installation so you can use it on Visual Studio and using a 2016+ version of Office, is to install the 2010 version of the Engine.

First install the x64 from this page

https://www.microsoft.com/en-us/download/details.aspx?id=54920

and then the x86 version from this one

https://www.microsoft.com/en-us/download/details.aspx?id=13255

as from this blog: http://dinesql.blogspot.com/2017/10/microsoft-access-database-engine-2016-Redistributable-Setup-you-cannot-install-the-32-bit-version-You-cannot-install-the-64-bit-version.html

no overload for matches delegate 'system.eventhandler'

You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e.

Understanding INADDR_ANY for socket programming

To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by

my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")

or by

my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);

How do I drop a function if it already exists?

IF EXISTS 
(SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'functionName') 
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))

DROP FUNCTION functionName
GO

How to compare two java objects

1) == evaluates reference equality in this case
2) im not too sure about the equals, but why not simply overriding the compare method and plant it inside MyClass?

How can I get a Unicode character's code?

There is an open source library MgntUtils that has a Utility class StringUnicodeEncoderDecoder. That class provides static methods that convert any String into Unicode sequence vise-versa. Very simple and useful. To convert String you just do:

String codes = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(myString);

For example a String "Hello World" will be converted into

"\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064"

It works with any language. Here is the link to the article that explains all te ditails about the library: MgntUtils. Look for the subtitle "String Unicode converter". The library could be obtained as a Maven artifact or taken from Github (including source code and Javadoc)

Making a WinForms TextBox behave like your browser's address bar

Set the selction when you leave the control. It will be there when you get back. Tab around the form and when you return to the control, all the text will be selected.

If you go in by mouse, then the caret will rightly be placed at the point where you clicked.

private void maskedTextBox1_Leave(object sender, CancelEventArgs e)
    {
        maskedTextBox1.SelectAll();
    }

Failed linking file resources

Look at the error you are getting:

C:\Projects\TimeTable\app\src\main\res\layout-land\activity_main.xml Error:error: resource android:attr/colorSwitchThumbNormal is private.

It means that in your activity_main.xml you are referencing the color "android:colorSwitchThumbNormal", but inside the 'android' namespace that resource is private. What you probably meant to do is try to reference that color from the support version of this attribute, so without the "android:" prefix.

<item name="android:colorSwitchThumbNormal">@color/myColor</item>

Replace with:

<item name="colorSwitchThumbNormal">@color/second</item>

How to get docker-compose to always re-create containers from fresh images?

The only solution that worked for me was this command :

docker-compose build --no-cache

This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.

What is the <leader> in a .vimrc file?

Be aware that when you do press your <leader> key you have only 1000ms (by default) to enter the command following it.

This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader> key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.

If you add set showcmd to your vimrc then you will see your <leader> key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.

The length of the timeout can also be set in your vimrc, see :help timeoutlen for more information.

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Mac OS X doesn't have apt-get. There is a package manager called Homebrew that is used instead.

This command would be:

brew install python

Use Homebrew to install packages that you would otherwise use apt-get for.

The page I linked to has an up-to-date way of installing homebrew, but at present, you can install Homebrew as follows:

Type the following in your Mac OS X terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that, usage of Homebrew is brew install <package>.

One of the prerequisites for Homebrew are the XCode command line tools.

  1. Install XCode from the App Store.
  2. Follow the directions in this Stack Overflow answer to install the XCode Command Line Tools.

Background

A package manager (like apt-get or brew) just gives your system an easy and automated way to install packages or libraries. Different systems use different programs. apt and its derivatives are used on Debian based linux systems. Red Hat-ish Linux systems use rpm (or at least they did many, many, years ago). yum is also a package manager for RedHat based systems.

Alpine based systems use apk.

Warning

As of 25 April 2016, homebrew opts the user in to sending analytics by default. This can be opted out of in two ways:

Setting an environment variable:

  1. Open your favorite environment variable editor.
  2. Set the following: HOMEBREW_NO_ANALYTICS=1 in whereever you keep your environment variables (typically something like ~/.bash_profile)
  3. Close the file, and either restart the terminal or source ~/.bash_profile.

Running the following command:

brew analytics off

the analytics status can then be checked with the command:

brew analytics

Javascript Array of Functions

Using Function.prototype.bind()

var array_of_functions = [
        first_function.bind(null,'a string'),
        second_function.bind(null,'a string'),
        third_function.bind(null,'a string'),
        forth_function.bind(null,'a string')
    ]

ignoring any 'bin' directory on a git project

Adding **/bin/ to the .gitignore file did the trick for me (Note: bin folder wasn't added to index).

Exit/save edit to sudoers file? Putty SSH

The tutorial you saw was telling you how to exit nano editor. By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open.

If you are not using any gui and you just want to leave the shell the command is Ctrl+D.

Regarding tutorial, The Linux Documentation Project would be a good place to start. If you like books I would recommend by far any book you want from O'Reilly. They have nice cd bookshelfs with good compilation for any linux sysadmin, and without much effort you can find many places where those html bookshelfs are available to read online.

How to get difference between two dates in Year/Month/Week/Day?

If you subtract two instances of DateTime, that will return an instance of TimeSpan, which will represent the difference between the two dates.

vertical-align with Bootstrap 3

The below code worked for me:

.vertical-align {
    display: flex;
    align-items: center;
}

IF EXISTS before INSERT, UPDATE, DELETE for optimization

IF EXISTS will basically do a SELECT - the same one that UPDATE would.

As such, it will decrease performance - if there's nothing to update, you did the same amount of work (UPDATE would have queried same lack of rows as your select) and if there's something to update, you juet did an un-needed select.

Are list-comprehensions and functional functions faster than "for loops"?

Adding a twist to Alphii answer, actually the for loop would be second best and about 6 times slower than map

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        a += i**2
    return a

def square_sum3(numbers):
    a = 0
    map(lambda x: a+x**2, numbers)
    return a

def square_sum4(numbers):
    a = 0
    return [a+i**2 for i in numbers]

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])

Main changes have been to eliminate the slow sum calls, as well as the probably unnecessary int() in the last case. Putting the for loop and map in the same terms makes it quite fact, actually. Remember that lambdas are functional concepts and theoretically shouldn't have side effects, but, well, they can have side effects like adding to a. Results in this case with Python 3.6.1, Ubuntu 14.04, Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz

0:00:00.257703 #Reduce
0:00:00.184898 #For loop
0:00:00.031718 #Map
0:00:00.212699 #List comprehension

What is the ultimate postal code and zip regex?

We use the following:

Canada

([A-Z]{1}[0-9]{1}){3}   //We raise to upper first

America

[0-9]{5}                //-or-
[0-9]{5}-[0-9]{4}       //10 digit zip

Other

Accept as is

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

How to push both value and key into PHP array

I wrote a simple function:

function push(&$arr,$new) {
    $arr = array_merge($arr,$new);
}

so that I can "upsert" new element easily:

push($my_array, ['a'=>1,'b'=>2])

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

How do I insert a JPEG image into a python Tkinter window?

import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()

How do I add Git version control (Bitbucket) to an existing source code folder?

You can init a Git directory in an directory containing other files. After that you can add files to the repository and commit there.

Create a project with some code:

$ mkdir my_project
$ cd my_project
$ echo "foobar" > some_file

Then, while inside the project's folder, do an initial commit:

$ git init
$ git add some_file
$ git commit -m "Initial commit"

Then for using Bitbucket or such you add a remote and push up:

$ git remote add some_name user@host:repo
$ git push some_name

You also might then want to configure tracking branches, etc. See git remote set-branches and related commands for that.

How do you change the formatting options in Visual Studio Code?

A solution that works for me (July 2017), is to utilize ESLint. As everybody knows, you can use the linter in multiple ways, globally or locally. I use it locally and with the google style guide. They way I set it up is as follow...

  • cd to your working directory
  • npm init
  • npm install --save-dev eslint
  • node_modules/.bin/eslint --init
  • I use google style and json config file

Now you will have a .eslintrc.json file the root of your working directory. You can open that file and modify as you please utilizing the eslint rules. Next cmd+, to open vscode system preferences. In the search bar type eslint and look for "eslint.autoFixOnSave": false. Copy the setting and pasted in the user settings file and change false to true. Hope this can help someone utilizing vscode.

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

How to amend older Git commit?

In case the OP wants to squash the 2 commits specified into 1, here is an alternate way to do it without rebasing

git checkout HEAD^               # go to the first commit you want squashed
git reset --soft HEAD^           # go to the second one but keep the tree and index the same
git commit --amend -C HEAD@{1}   # use the message from first commit (omit this to change)
git checkout HEAD@{3} -- .       # get the tree from the commit you did not want to touch
git add -A                       # add everything
git commit -C HEAD@{3}           # commit again using the message from that commit

The @{N) syntax is handy to know as it will allow you to reference the history of where your references were. In this case it's HEAD which represents your current commit.

RegEx to parse or validate Base64 data

From the RFC 4648:

Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Execute SQLite script

In order to execute simple queries and return to my shell script, I think this works well:

$ sqlite3 example.db 'SELECT * FROM some_table;'

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

In JSX, the lower-case tag name is considered as html native component. In order to react recognise the function as React component, need to Capitalized the name.

Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.

https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components

The thread has exited with code 0 (0x0) with no unhandled exception

In order to complete BlueM's accepted answer, you can desactivate it here:

Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off

Resize Cross Domain Iframe Height

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.

Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).

window.addEventListener("load", function(){
    if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe 
    send_height_to_parent_function = function(){
        var height = document.getElementsByTagName("html")[0].clientHeight;
        //console.log("Sending height as " + height + "px");
        parent.postMessage({"height" : height }, "*");
    }
    // send message to parent about height updates
    send_height_to_parent_function(); //whenever the page is loaded
    window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
    var observer = new MutationObserver(send_height_to_parent_function);           // whenever DOM changes PT1
    var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
    observer.observe(window.document, config);                                            // PT3 
});

Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.

<script>
window.addEventListener("message", function(e){
    var this_frame = document.getElementById("healthy_behavior_iframe");
    if (this_frame.contentWindow === e.source) {
        this_frame.height = e.data.height + "px";
        this_frame.style.height = e.data.height + "px";
    }
})
</script>

how to permit an array with strong parameters

It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])

Docker: Copying files from Docker container to host

docker cp containerId:source_path destination_path

containerId can be obtained from the command docker ps -a

source path should be absolute. for example, if the application/service directory starts from the app in your docker container the path would be /app/some_directory/file

example : docker cp d86844abc129:/app/server/output/server-test.png C:/Users/someone/Desktop/output

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Why am I getting string does not name a type Error?

Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

The namespace in game.cpp is after the header is included.

How to effectively work with multiple files in Vim

I use multiple buffers that are set hidden in my ~/.vimrc file.

The mini-buffer explorer script is nice too to get a nice compact listing of your buffers. Then :b1 or :b2... to go to the appropriate buffer or use the mini-buffer explorer and tab through the buffers.

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

Redirecting unauthorized controller in ASP.NET MVC

I had the same issue. Rather than figure out the MVC code, I opted for a cheap hack that seems to work. In my Global.asax class:

member x.Application_EndRequest() =
  if x.Response.StatusCode = 401 then 
      let redir = "?redirectUrl=" + Uri.EscapeDataString x.Request.Url.PathAndQuery
      if x.Request.Url.LocalPath.ToLowerInvariant().Contains("admin") then
          x.Response.Redirect("/Login/Admin/" + redir)
      else
          x.Response.Redirect("/Login/Login/" + redir)

How do I run a program with a different working directory from current, from Linux shell?

Similar to David Schmitt's answer, plus Josh's suggestion, but doesn't leave a shell process running:

(cd /c && exec /a/helloworld)

This way is more similar to how you usually run commands on the shell. To see the practical difference, you have to run ps ef from another shell with each solution.

Twitter Bootstrap - full width navbar

You need to push the container down the navbar.

Please find my working fiddle here http://jsfiddle.net/meetravi/aXCMW/1/

<header>

    <h2 class="title">Test</h2>
</header>
<div class="navbar">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>

        </ul>
    </div>
</div>
<div class="container">

</div>

SSL: CERTIFICATE_VERIFY_FAILED with Python3

In my case, I used the ssl module to "workaround" the certification like so:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

Then to read your link content, you can use:

urllib.request.urlopen(urllink)

npm - EPERM: operation not permitted on Windows

I had an outdated version of npm. I ran a series of commands to resolve this issue:

npm cache clean --force

Then:

npm install -g npm@latest --force

Then (once again):

npm cache clean --force

And finally was able to run this (installing Angular project) without the errors I was seeing regarding EPERM:

ng new myProject

Laravel, sync() - how to sync an array and also pass additional pivot fields?

In order to sync multiple models along with custom pivot data, you need this:

$user->roles()->sync([ 
    1 => ['expires' => true],
    2 => ['expires' => false],
    ...
]);

Ie.

sync([
    related_id => ['pivot_field' => value],
    ...
]);

edit

Answering the comment:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);

Converting a String to a List of Words?

To do this properly is quite complex. For your research, it is known as word tokenization. You should look at NLTK if you want to see what others have done, rather than starting from scratch:

>>> import nltk
>>> paragraph = u"Hi, this is my first sentence. And this is my second."
>>> sentences = nltk.sent_tokenize(paragraph)
>>> for sentence in sentences:
...     nltk.word_tokenize(sentence)
[u'Hi', u',', u'this', u'is', u'my', u'first', u'sentence', u'.']
[u'And', u'this', u'is', u'my', u'second', u'.']

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Ctrl-Alt-X is the keyboard shortcut I use, although that may because I have Resharper installed - otherwise Ctrl W, X.

From the menu: View -> Toolbox.

You can easily view/change key bindings using Tools -> Options Environment->Keyboard. It has a convenient UI where you can enter a word, and it shows you what key bindings include that word, including View.Toolbox.

You might want to browse through the online MSDN documentation on getting started with Visual Studio.

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

foreach vs someList.ForEach(){}

I know two obscure-ish things that make them different. Go me!

Firstly, there's the classic bug of making a delegate for each item in the list. If you use the foreach keyword, all your delegates can end up referring to the last item of the list:

    // A list of actions to execute later
    List<Action> actions = new List<Action>();

    // Numbers 0 to 9
    List<int> numbers = Enumerable.Range(0, 10).ToList();

    // Store an action that prints each number (WRONG!)
    foreach (int number in numbers)
        actions.Add(() => Console.WriteLine(number));

    // Run the actions, we actually print 10 copies of "9"
    foreach (Action action in actions)
        action();

    // So try again
    actions.Clear();

    // Store an action that prints each number (RIGHT!)
    numbers.ForEach(number =>
        actions.Add(() => Console.WriteLine(number)));

    // Run the actions
    foreach (Action action in actions)
        action();

The List.ForEach method doesn't have this problem. The current item of the iteration is passed by value as an argument to the outer lambda, and then the inner lambda correctly captures that argument in its own closure. Problem solved.

(Sadly I believe ForEach is a member of List, rather than an extension method, though it's easy to define it yourself so you have this facility on any enumerable type.)

Secondly, the ForEach method approach has a limitation. If you are implementing IEnumerable by using yield return, you can't do a yield return inside the lambda. So looping through the items in a collection in order to yield return things is not possible by this method. You'll have to use the foreach keyword and work around the closure problem by manually making a copy of the current loop value inside the loop.

More here

How to clear the logs properly for a Docker container?

Docker for Mac users, here is the solution:

    1. Find log file path by:

      $ docker inspect | grep log

    1. SSH into the docker machine( suppose the name is default, if not, run docker-machine ls to find out):

      $ docker-machine ssh default

    1. Change to root user(reference):

      $ sudo -i

    1. Delete the log file content:

      $ echo "" > log_file_path_from_step1

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Conditionally change img src based on model data

<ul>
  <li ng-repeat=interface in interfaces>
       <img src='green-checkmark.png' ng-show="interface=='UP'" />
       <img src='big-black-X.png' ng-show="interface=='DOWN'" />
  </li>
</ul>

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

How do I remove time part from JavaScript date?

Split it by space and take first part like below. Hope this will help you.

var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

Select data between a date/time range

A simple way :

select  * from  hockey_stats 
where  game_date >= '2012-03-11' and game_date  <= '2012-05-11'

How to convert current date to epoch timestamp?

if you want UTC try some of the gm functions:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch

Date vs DateTime

There is no Date DataType.

However you can use DateTime.Date to get just the Date.

E.G.

DateTime date = DateTime.Now.Date;

open program minimized via command prompt

For the people which are looking for the opposite (aka fullscreen), it's very simple. Because you just have to replace the settings /min by /max.

Now the program will be open at the "maximized" size ! In the case, perhaps you will need an example : start /max explorer.exe.

jQuery first child of "this"

This can be done with a simple magic like this:

$(":first-child", element).toggleClass("redClass");

Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector

Postgres: SQL to list table foreign keys

 SELECT 
    conrelid::regclass AS table_from,
    conname,
    pg_get_constraintdef(oid) as condef    
    FROM pg_catalog.pg_constraint r

will also work for all constraints. E.g. with pysql: enter image description here

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

This is for someone who tried all the answers and still failed. Extending pierre's answer. If you are using animation, setting up the visibility to GONE or INVISIBLE or invalidate() will never work. Try out the below solution. `

btn2.getAnimation().setAnimationListener(new Animation.AnimationListener() {
     @Override
     public void onAnimationStart(Animation animation) {
     }
     @Override
     public void onAnimationEnd(Animation animation) {
         btn2.setVisibility(View.GONE);
         btn2.clearAnimation();
     }
     @Override
     public void onAnimationRepeat(Animation animation) {
     }
});

`

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Format ints into string of hex

From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:

x= 255 print('the number is {:x}'.format(x))

Output:

the number is ff

Here are the base options

Type
'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

Static method in a generic class?

Java doesn't know what T is until you instantiate a type.

Maybe you can execute static methods by calling Clazz<T>.doit(something) but it sounds like you can't.

The other way to handle things is to put the type parameter in the method itself:

static <U> void doIt(U object)

which doesn't get you the right restriction on U, but it's better than nothing....

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

Get host domain from URL?

Try like this;

Uri.GetLeftPart( UriPartial.Authority )

Defines the parts of a URI for the Uri.GetLeftPart method.


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo

Why does find -exec mv {} ./target/ + not work?

I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t option for mv, so I had to find another solution. However the following command succeeded:

find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;

The secret was to quote the braces. No need for the braces to be at the end of the exec command.

I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.

However, when using the + sign, it seems indeed that it has to be at the end of the exec command.

VBScript How can I Format Date?

Although answer is provided I found simpler solution:

Date:

01/20/2017

By doing replace

CurrentDate = replace(date, "/", "-")

It will output:

01-20-2017

CardView background color always white

app:cardBackgroundColor="#488747"

use this in your card view and you can change a color of your card view

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Javascript code for showing yesterday's date and todays date

Yesterday's date is simply today's date less one, so:

var d = new Date();
d.setDate(d.getDate() - 1);

If today is 1 April, then it is set to 0 April which is converted to 31 March.

Since you also wanted to do some other stuff, here are some functions to do it:

// Check if d is a valid date
// Must be format year-month name-date
// e.g. 2011-MAR-12 or 2011-March-6
// Capitalisation is not important
function validDate(d) {
  var bits = d.split('-');
  var t = stringToDate(d);
  return t.getFullYear() == bits[0] && 
         t.getDate() == bits[2];
}

// Convert string in format above to a date object
function stringToDate(s) {
  var bits = s.split('-');
  var monthNum = monthNameToNumber(bits[1]);
  return new Date(bits[0], monthNum, bits[2]);
}

// Convert month names like mar or march to 
// number, capitalisation not important
// Month number is calendar month - 1.
var monthNameToNumber = (function() {
  var monthNames = (
     'jan feb mar apr may jun jul aug sep oct nov dec ' +
     'january february march april may june july august ' +
     'september october november december'
     ).split(' ');

  return function(month) {
    var i = monthNames.length;
    month = month.toLowerCase(); 

    while (i--) {
      if (monthNames[i] == month) {
        return i % 12;
      }
    }
  }
}());

// Given a date in above format, return
// previous day as a date object
function getYesterday(d) {
  d = stringToDate(d);
  d.setDate(d.getDate() - 1)
  return d;
}

// Given a date object, format
// per format above
var formatDate = (function() {
  var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
  function addZ(n) {
    return n<10? '0'+n : ''+n;
  }
  return function(d) {
    return d.getFullYear() + '-' + 
           months[d.getMonth()] + '-' + 
           addZ(d.getDate());
  }
}());

function doStuff(d) {

  // Is it format year-month-date?
  if (!validDate(d)) {
    alert(d + ' is not a valid date');
    return;
  } else {
    alert(d + ' is a valid date');
  }
  alert(
    'Date in was: ' + d +
    '\nDay before: ' + formatDate(getYesterday(d))
  );
}


doStuff('2011-feb-08');
// Shows 2011-feb-08 is a valid date
//       Date in was: 2011-feb-08
//       Day before: 2011-feb-07

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

Details:

  • %.0f stands for "print a float with 0 decimal places", so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +'%'
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

How do I find out what version of WordPress is running?

Just go to follow link domain.com/wp-admin/about.php

Adding link a href to an element using css

You cannot simply add a link using CSS. CSS is used for styling.

You can style your using CSS.

If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.

You can accomplish that very easily using jQuery.

I have done a sample for you. You can refer that.

URL : http://jsfiddle.net/zyk9w/

$('#link').attr('href','http://www.google.com');

This single line will do the trick.

Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

How to hide output of subprocess in Python 2.7

Redirect the output to DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null")

Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL, 
    stderr=subprocess.STDOUT)

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

How to redirect to Login page when Session is expired in Java web application?

You need to implement the HttpSessionListener interface, server will notify session time outs.

like this;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ApplicationSessionListener implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent event) {
   System.out.println("Session Created");
 }

public void sessionDestroyed(HttpSessionEvent event) {
   //write your logic
   System.out.println("Session Destroyed");
  }
 }

Check this example for better understanding

http://www.myjavarecipes.com/how-to-catch-session-timeouts/

Running CMD command in PowerShell

You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.

If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

Call to undefined method mysqli_stmt::get_result

I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.

Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.

NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm to the command:

gcc test.c -o test -lm

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.

Fastest way to zero out a 2d array in C?

How was your 2D array declared?

If it something like:

int arr[20][30];

You can zero it by doing:

memset(arr, sizeof(int)*20*30);

How to float 3 divs side by side using CSS?

Just give them a width and float: left;, here's an example:

<div style="width: 500px;">
 <div style="float: left; width: 200px;">Left Stuff</div>
 <div style="float: left; width: 100px;">Middle Stuff</div>
 <div style="float: left; width: 200px;">Right Stuff</div>
 <br style="clear: left;" />
</div>

How can I get device ID for Admob

I have a few devices I was testing on, and didn't want to manually get the DeviceID for each one. The answers here to programmatically get the DeviceIDs were not working for me (Missing zeros) which caused real ads to be shown instead of test ads.

I put this in my Application class onCreate, and then exposed deviceId using a getter method so that it can be accessed throughout.

@Override
public void onCreate() {        
    super.onCreate();

    String androidId =  Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    deviceId = MD5(androidId).toUpperCase();        
}  

public static String getDeviceId() {
    return deviceId;
}

private static String deviceId;

And the MD5 method;

public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}

Then using this whenever I create an AdRequest object:

if(BuildConfig.DEBUG) {
     AdRequest adRequest = new AdRequest.Builder()
          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .addTestDevice(Application.getDeviceId())
          .build();
     adView.loadAd(adRequest);
} else {
     AdRequest adRequest = new AdRequest.Builder()
          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .build();
     adView.loadAd(adRequest);
}

How to print Two-Dimensional Array like table

public class FormattedTablePrint {

    public static void printRow(int[] row) {
        for (int i : row) {
            System.out.print(i);
            System.out.print("\t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int twoDm[][]= new int[7][5];
        int i,j,k=1;

        for(i=0;i<7;i++) {
            for(j=0;j<5;j++) {
                twoDm[i][j]=k;
                k++;
            }
        }

        for(int[] row : twoDm) {
            printRow(row);
        }
    }
}

Output

1   2   3   4   5   
6   7   8   9   10  
11  12  13  14  15  
16  17  18  19  20  
21  22  23  24  25  
26  27  28  29  30  
31  32  33  34  35  

Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.

How to obtain the start time and end time of a day?

 //this will work for user in time zone MST with 7 off set or UTC with saving time 

 //I have tried all the above and they fail the only solution is to use some math
 //the trick is to rely on $newdate is time()     //strtotime is corrupt it tries to read to many minds
 //convert to time to use with javascript*1000
 
 $dnol = strtotime('today')*1000;
 $dn = ($newdate*1000)-86400000;
 $dz=$dn/86400000;      //divide into days
 $dz=floor($dz);     //filter off excess time
 $dzt=$dz*86400000;     // put back into days UTC
 $jsDate=$dzt*1+(7*3600000);     // 7 is the off set you can store the 7 in database
 $dzt=$dzt-3600000;      //adjusment for summerTime UTC additional table for these dates will drive you crazy
 //solution get users [time off sets] with browser, up date to data base for user with ajax when they ain't lookin



 <?php
 $t=time();
 echo($t . "<br>");
 echo(date("Y-m-d",$t));
 echo '<BR>'.$dnol;
 echo '<BR>'.$dzt.'<BR>';
 echo(date("Y-m-d",$dzt/1000));      //convert back for php /1000
 echo '<BR>';
 echo(date('Y-m-d h:i:s',$dzt/1000));

 ?>

IIS: Display all sites and bindings in PowerShell

If you just want to list all the sites (ie. to find a binding)

Change the working directory to "C:\Windows\system32\inetsrv"

cd c:\Windows\system32\inetsrv

Next run "appcmd list sites" (plural) and output to a file. e.g c:\IISSiteBindings.txt

appcmd list sites > c:\IISSiteBindings.txt

Now open with notepad from your command prompt.

notepad c:\IISSiteBindings.txt

How to check if a function exists on a SQL database

I tend to use the Information_Schema:

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'FUNCTION' ) 

for functions, and change Routine_Type for stored procedures

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'PROCEDURE' ) 

Find if a String is present in an array

This can be done in java 8 using Stream.

import java.util.stream.Stream;

String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());

How to get selected path and name of the file opened with file dialog?

I think this is the simplest way to get to what you want.

Credit to JMK's answer for the first part, and the hyperlink part was adapted from http://msdn.microsoft.com/en-us/library/office/ff822490(v=office.15).aspx

'Gets the entire path to the file including the filename using the open file dialog
Dim filename As String
filename = Application.GetOpenFilename

'Adds a hyperlink to cell b5 in the currently active sheet
With ActiveSheet
 .Hyperlinks.Add Anchor:=.Range("b5"), _
 Address:=filename, _
 ScreenTip:="The screenTIP", _
 TextToDisplay:=filename
End With

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");

Laravel Password & Password_Confirmation Validation

Try this:

'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6'

How to use greater than operator with date?

In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example

SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';

When do you use Git rebase instead of Git merge?

To complement my own answer mentioned by TSamper,

  • a rebase is quite often a good idea to do before a merge, because the idea is that you integrate in your branch Y the work of the branch B upon which you will merge.
    But again, before merging, you resolve any conflict in your branch (i.e.: "rebase", as in "replay my work in my branch starting from a recent point from the branch B).
    If done correctly, the subsequent merge from your branch to branch B can be fast-forward.

  • a merge directly impacts the destination branch B, which means the merges better be trivial, otherwise that branch B can be long to get back to a stable state (time for you solve all the conflicts)


the point of merging after a rebase?

In the case that I describe, I rebase B onto my branch, just to have the opportunity to replay my work from a more recent point from B, but while staying into my branch.
In this case, a merge is still needed to bring my "replayed" work onto B.

The other scenario (described in Git Ready for instance), is to bring your work directly in B through a rebase (which does conserve all your nice commits, or even give you the opportunity to re-order them through an interactive rebase).
In that case (where you rebase while being in the B branch), you are right: no further merge is needed:

A Git tree at default when we have not merged nor rebased

rebase1

we get by rebasing:

rebase3

That second scenario is all about: how do I get new-feature back into master.

My point, by describing the first rebase scenario, is to remind everyone that a rebase can also be used as a preliminary step to that (that being "get new-feature back into master").
You can use rebase to first bring master "in" the new-feature branch: the rebase will replay new-feature commits from the HEAD master, but still in the new-feature branch, effectively moving your branch starting point from an old master commit to HEAD-master.
That allows you to resolve any conflicts in your branch (meaning, in isolation, while allowing master to continue to evolve in parallel if your conflict resolution stage takes too long).
Then you can switch to master and merge new-feature (or rebase new-feature onto master if you want to preserve commits done in your new-feature branch).

So:

  • "rebase vs. merge" can be viewed as two ways to import a work on, say, master.
  • But "rebase then merge" can be a valid workflow to first resolve conflict in isolation, then bring back your work.

CodeIgniter: How to get Controller, Action, URL information

Last segment of URL will always be the action. Please get like this:

$this->uri->segment('last_segment');

Can't use WAMP , port 80 is used by IIS 7.5

This happens to me once: I uninstalled the IIS, and the port 80 still was used. Well the problem was that also I had the Report Service of the Sql Server 2012 installed, so I stopped that service and the problems solves.

See Stop Or Uninstall IIS for running Wamp Server (Apache) on default port (:80) question for more details.

Hope this helps some body, as it help to me.

getting JRE system library unbound error in build path

This is like user3076252's answer, but you'll be choosing a different set of options:

  • Project > Properties > Java Build Path
  • Select Libraries tab > Alternate JRE > Installed JREs...
  • Click "Search." Unless you know the exact folder name, you should choose a drive to search.

It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.

how to change the dist-folder path in angular-cli after 'ng build'

You can use the CLI too, like:

ng build -prod --output-path=production

# or

ng serve --output-path=devroot

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

You can use the environment variable $HOME for that.

require is not defined? Node.js

Point 1: Add require() function calling line of code only in the app.js file or main.js file.

Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".

Checking for empty result (php, pdo, mysql)

Even though this is an old thread, I thought I would weigh in as I had to deal with this lately.

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today))) 
{
    $db = null ;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I had the same issue too, to solve this, check in References of your project if the version of Newtonsoft.Json was updated (probablly don´t), then remove it and check in your either Web.config or App.config wheter the element dependentAssembly was updated as follows:

<dependentAssembly>
  <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>

After that, rebuild the project again (the dll will be replaced with the correct version)

How to get screen width and height

From service:

Display  display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

Where can I find the default timeout settings for all browsers?

For Google Chrome (Tested on ver. 62)

I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket> connection settings.

I set the headers object on my client-side script with the following options:

/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
    method: 'OPTIONS',
    credentials: "include",
    body: JSON.stringify(data),
    cors: 'cors',
    headers: head, //could be object literal too
    cache: 'default'
 })
 .then(response=>{
    ....
  }).catch(err=>{...});

And on my express server I setup my router as follows:

 router.head('absolute or regex', (request, response, next)=>{
  req.setTimeout(1000*60*5, ()=>{
     console.info("socket timed out");
   });
  console.info("Proceeding down the middleware chain link...\n\n");
  next();
 });

 /*Keep the socket alive by enabling it on the server, with an optional 
  delay on the last packet sent 
 */
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))

WARNING

Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.

I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.

Build fat static library (device + simulator) using Xcode and SDK 4+

I've made this into an Xcode 4 template, in the same vein as Karl's static framework template.

I found that building static frameworks (instead of plain static libraries) was causing random crashes with LLVM, due to an apparent linker bug - so, I guess static libraries are still useful!

How to pass data to view in Laravel?

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

How to host material icons offline?

This may be an easy Solution


Get this repository that is a fork of the original repository Google published.

Install it with bower or npm

bower install material-design-icons-iconfont --save

npm install material-design-icons-iconfont --save

Import the css File on your HTML Page

<style>
  @import url('node_modules/material-design-icons-iconfont/dist/material-design-icons.css');
</style>

or

<link rel="stylesheet" href="node_modules/material-design-icons-iconfont/dist/material-design-icons.css">

Test: Add an icon inside body tag of your HTML File

<i class="material-icons">face</i>

If you see the face icon, you are OK.

If does not work, try add this .. as prefix to node_modules path:

<link rel="stylesheet" href="../node_modules/material-design-icons-iconfont/dist/material-design-icons.css">

jQuery + client-side template = "Syntax error, unrecognized expression"

I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...

app.run(['$templateCache', function($templateCache) {
    var url = "survey-input.html";
    content = angular.element(document.getElementById(url)).html()
    $templateCache.put(url, content);
}]);

How to make <input type="date"> supported on all browsers? Any alternatives?

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}

How to resize Image in Android?

Try:

Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Convert normal Java Array or ArrayList to Json Array in android

If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.

Something along those lines should work.

String mStringArray[] = { "String1", "String2" };

JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));

Beware that code is written offhand so consider it pseudo-code.

Copy all files with a certain extension from all subdirectories

I also had to do this myself. I did it via the --parents argument for cp:

find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;

Is it a bad practice to use an if-statement without curly braces?

My general pattern is that if it fits on one line, I'll do:

if(true) do_something();

If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.

Count items in a folder with PowerShell

You should use Measure-Object to count things. In this case it would look like:

Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;

or if that's too long

Write-Host ( dir c:\MyFolder | mo).Count;

and in PowerShell 4.0 use the measure alias instead of mo

Write-Host (dir c:\MyFolder | measure).Count;

Python str vs unicode types

Your terminal happens to be configured to UTF-8.

The fact that printing a works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a is a value of length two, containing two bytes, hex values C3 and A1, while ua is a unicode value of length one, containing a codepoint U+00E1.

This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len() of a byte string tells you how many bytes were used, not how many characters were encoded.

You can see the difference when you encode the unicode value to different output encodings:

>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'

Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.

Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x.. escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u.... is used instead, with a four-digit hex value.

It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:

How to debug a bash script?

I've used the following methods to debug my script.

set -e makes the script stop immediately if any external program returns a non-zero exit status. This is useful if your script attempts to handle all error cases and where a failure to do so should be trapped.

set -x was mentioned above and is certainly the most useful of all the debugging methods.

set -n might also be useful if you want to check your script for syntax errors.

strace is also useful to see what's going on. Especially useful if you haven't written the script yourself.

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I notice many answers just try to increase the amount of memory given to a script which has its place but more often than not it means that something is being too liberal with memory due to an unforseen amount of volume or size. Obviously if your not the author of a script your at the mercy of the author unless your feeling ambitious :) The PHP docs even say memory issues are due to "poorly written scripts"

It should be mentioned that ini_set('memory_limit', '-1'); (no limit) can cause server instability as 0 bytes free = bad things. Instead, find a reasonable balance by what your script is trying to do and the amount of available memory on a machine.

A better approach: If you are the author of the script (or ambitious) you can debug such memory issues with xdebug. The latest version (2.6.0 - released 2018-01-29) brought back memory profiling that shows you what function calls are consuming large amounts of memory. It exposes issues in the script that are otherwise hard to find. Usually, the inefficiencies are in a loop that isn't expecting the volume it's receiving, but each case will be left as an exercise to the reader :)

The xdebug documentation is helpful, but it boils down to 3 steps:

  1. Install It - Available through apt-get and yum etc
  2. Configure it - xdebug.ini: xdebug.profiler_enable = 1, xdebug.profiler_output_dir = /where/ever/
  3. View the profiles in a tool like QCacheGrind, KCacheGrind

Inserting one list into another list in java?

Citing the official javadoc of List.addAll:

Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator (optional operation).  The behavior of this
operation is undefined if the specified collection is modified while
the operation is in progress.  (Note that this will occur if the
specified collection is this list, and it's nonempty.)

So you will copy the references of the objects in list to anotherList. Any method that does not operate on the referenced objects of anotherList (such as removal, addition, sorting) is local to it, and therefore will not influence list.

console.log timestamps in Chrome?

ES6 solution:

const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)

where timestamp() returns actually formatted timestamp and log add a timestamp and propagates all own arguments to console.log

jQuery click event not working in mobile browsers

A Solution to Touch and Click in jQuery (without jQuery Mobile)

Let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:

<script src=”http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js”></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};
</script>

source

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

How do I create a unique ID in Java?

We can create a unique ID in java by using the UUID and call the method like randomUUID() on UUID.

String uniqueID = UUID.randomUUID().toString();

This will generate the random uniqueID whose return type will be String.

How to mock private method for testing using PowerMock?

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

  1. Change your private method to protected.
  2. In your test class extend the class
  3. override the previously-private method to return whatever constant you want

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

Random color generator

For decent randomness.

Random color

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0).slice(-6)}`

Random alpha, random color.

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0)}`

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Tensorflow 2.0 Compatible Answer: Detailed Explanations have been provided above, about "Valid" and "Same" Padding.

However, I will specify different Pooling Functions and their respective Commands in Tensorflow 2.x (>= 2.0), for the benefit of the community.

Functions in 1.x:

tf.nn.max_pool

tf.keras.layers.MaxPool2D

Average Pooling => None in tf.nn, tf.keras.layers.AveragePooling2D

Functions in 2.x:

tf.nn.max_pool if used in 2.x and tf.compat.v1.nn.max_pool_v2 or tf.compat.v2.nn.max_pool, if migrated from 1.x to 2.x.

tf.keras.layers.MaxPool2D if used in 2.x and

tf.compat.v1.keras.layers.MaxPool2D or tf.compat.v1.keras.layers.MaxPooling2D or tf.compat.v2.keras.layers.MaxPool2D or tf.compat.v2.keras.layers.MaxPooling2D, if migrated from 1.x to 2.x.

Average Pooling => tf.nn.avg_pool2d or tf.keras.layers.AveragePooling2D if used in TF 2.x and

tf.compat.v1.nn.avg_pool_v2 or tf.compat.v2.nn.avg_pool or tf.compat.v1.keras.layers.AveragePooling2D or tf.compat.v1.keras.layers.AvgPool2D or tf.compat.v2.keras.layers.AveragePooling2D or tf.compat.v2.keras.layers.AvgPool2D , if migrated from 1.x to 2.x.

For more information about Migration from Tensorflow 1.x to 2.x, please refer to this Migration Guide.

Steps to send a https request to a rest service in Node js

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

Finding the last index of an array

say your array is called arr

do

arr[arr.Length - 1]

Calculating time difference in Milliseconds

No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis(). That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.

To measure how long something takes, consider using System.nanoTime instead. The important point here isn't that the precision is greater, but that the resolution will be greater... but only when used to measure the time between two calls. It must not be used as a "wall clock".

Note that even System.nanoTime just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:

public class Test {
    public static void main(String[] args) throws Exception {

        long[] differences = new long[5];
        long previous = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            long current;
            while ((current = System.nanoTime()) == previous) {
                // Do nothing...
            }
            differences[i] = current - previous;
            previous = current;            
        }

        for (long difference : differences) {
            System.out.println(difference);
        }
    }
}

On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)

Keyboard shortcuts in WPF

One way is to add your shortcut keys to the commands themselves them as InputGestures. Commands are implemented as RoutedCommands.

This enables the shortcut keys to work even if they're not hooked up to any controls. And since menu items understand keyboard gestures, they'll automatically display your shortcut key in the menu items text, if you hook that command up to your menu item.

  1. Create static attribute to hold a command (preferably as a property in a static class you create for commands - but for a simple example, just using a static attribute in window.cs):

     public static RoutedCommand MyCommand = new RoutedCommand();
    
  2. Add the shortcut key(s) that should invoke method:

     MyCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
    
  3. Create a command binding that points to your method to call on execute. Put these in the command bindings for the UI element under which it should work for (e.g., the window) and the method:

     <Window.CommandBindings>
         <CommandBinding Command="{x:Static local:MyWindow.MyCommand}" Executed="MyCommandExecuted"/>
     </Window.CommandBindings>
    
     private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e) { ... }
    

Function to calculate R2 (R-squared) in R

It is not something obvious, but the caret package has a function postResample() that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are

  • RMSE
  • Rsquared
  • mean absolute error (MAE)

and have to be accessed from the vector like this

library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]

However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.

caret also has an R2() method, although it's hard to find in the documentation.

The way to implement the normal coefficient of determination equation is:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss

Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.

What is the difference between Cygwin and MinGW?

   MinGW (or MinGW-w64)               Cygwin
   --------------------               ------

   Your program written        Your program written
    for Unix and Linux          for Unix and Linux

             |                           |
             |                           |
             V                           V

    Heavy modifications       Almost no modifications

             |                           |
             |                           |
             V                           V

        Compilation                 Compilation
Program compiled with Cygwin ---> Compatibility layer ---> Windows API

Program compiled with MinGW (or MingGW-w64) -------------> Windows API

How to check for null in Twig?

Without any assumptions the answer is:

{% if var is null %}

But this will be true only if var is exactly NULL, and not any other value that evaluates to false (such as zero, empty string and empty array). Besides, it will cause an error if var is not defined. A safer way would be:

{% if var is not defined or var is null %}

which can be shortened to:

{% if var|default is null %}

If you don't provide an argument to the default filter, it assumes NULL (sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):

{% if var|default is empty %}

How to call an element in a numpy array?

Just use square brackets instead:

print arr[1,1]

Linq select objects in list where exists IN (A,B,C)

var statuses = new[] { "A", "B", "C" };

var filteredOrders = from order in orders.Order
                             where statuses.Contains(order.StatusCode)
                             select order;

Binding Combobox Using Dictionary as the Datasource

Use -->

comboBox1.DataSource = colors.ToList();

Unless the dictionary is converted to list, combo-box can't recognize its members.

Mapping two integers to one, in a unique and deterministic way

f(a, b) = s(a+b) + a, where s(n) = n*(n+1)/2

  • This is a function -- it is deterministic.
  • It is also injective -- f maps different values for different (a,b) pairs. You can prove this using the fact: s(a+b+1)-s(a+b) = a+b+1 < a.
  • It returns quite small values -- good if your are going to use it for array indexing, as the array does not have to be big.
  • It is cache-friendly -- if two (a, b) pairs are close to each other, then f maps numbers to them which are close to each other (compared to other methods).

I did not understand what You mean by:

should always yield an integer on either the positive or the negative side of integers

How can I write (greater than), (less than) characters in this forum?

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

To prevent this, make sure every BEGIN TRANSACTION has COMMIT

The following will say successful but will leave uncommitted transactions:

BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT

Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.

Catch browser's "zoom" event in JavaScript

The resize event works on modern browsers by attaching the event on window, and then reading values of thebody, or other element with for example (.getBoundingClientRect()).

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events.

_x000D_
_x000D_
window.addEventListener("resize", getSizes, false)_x000D_
        _x000D_
function getSizes(){_x000D_
  let body = document.body_x000D_
  console.log(body.clientWidth +"px x "+ body.clientHeight + "px")_x000D_
}
_x000D_
_x000D_
_x000D_

An other alternative: the ResizeObserver API

Depending your layout, you can watch for resizing on a particular element.

This works well on «responsive» layouts, because the container box get resized when zooming.

_x000D_
_x000D_
function watchBoxchange(e){_x000D_
 // console.log(e[0].contentBoxSize.inlineSize+" "+e[0].contentBoxSize.blockSize)_x000D_
 info.textContent = e[0].contentBoxSize.inlineSize+" * "+e[0].contentBoxSize.blockSize + "px"_x000D_
}_x000D_
_x000D_
new ResizeObserver(watchBoxchange).observe(fluid)
_x000D_
#fluid {_x000D_
  width: 200px;_x000D_
  height:100px;_x000D_
  overflow: auto;_x000D_
  resize: both;_x000D_
  border: 3px black solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  font-size: 8vh_x000D_
}
_x000D_
<div id="fluid">_x000D_
   <info id="info"></info> _x000D_
</div>
_x000D_
_x000D_
_x000D_


Be careful to not overload javascript tasks from user gestures events. Use requestAnimationFrame whenever you needs redraws.

String to HashMap JAVA

USING JAVA 8:

Map<String, String> headerMap = Arrays.stream(header.split(","))
                    .map(s -> s.split(":"))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden('name', 'value') creates a hidden tag with name = 'name' and value = 'value'.

Html.HiddenFor(x => x.nameProp) creates a hidden tag with a name = 'nameProp' and value = x.nameProp.

At face value these appear to do similar things, with one just more convenient than the other. But its actual value is for model binding. When MVC tries to associate the html to the model, it needs to have the name of the property, and for Html.Hidden, we chose 'name', and not 'nameProp', and thus the binding wouldn't work. You'd have to have a custom binding object, or get the values from the form data. If you are redisplaying the page, you'd have to set the model to the values again.

So you can use Html.Hidden, but if you get the name wrong, or if you change the property name in the model, the auto binding will fail when you submit the form. But by using a type checked expression, you'll get code completion, and when you change the property name, you will get a compile time error. And then you are guaranteed to have the correct name in the form.

One of the better features of MVC.

Check if at least two out of three booleans are true

The most obvious set of improvements are:

// There is no point in an else if you already returned.
boolean atLeastTwo(boolean a, boolean b, boolean c) {
    if ((a && b) || (b && c) || (a && c)) {
        return true;
    }
    return false;
}

and then

// There is no point in an if(true) return true otherwise return false.
boolean atLeastTwo(boolean a, boolean b, boolean c) {
    return ((a && b) || (b && c) || (a && c));
}

But those improvements are minor.

How to split one string into multiple strings separated by at least one space in bash shell?

I like the conversion to an array, to be able to access individual elements:

sentence="this is a story"
stringarray=($sentence)

now you can access individual elements directly (it starts with 0):

echo ${stringarray[0]}

or convert back to string in order to loop:

for i in "${stringarray[@]}"
do
  :
  # do whatever on $i
done

Of course looping through the string directly was answered before, but that answer had the the disadvantage to not keep track of the individual elements for later use:

for i in $sentence
do
  :
  # do whatever on $i
done

See also Bash Array Reference.

Best way to save a trained model in PyTorch?

It depends on what you want to do.

Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm and Dropout layers that by default are in train mode on construction:

torch.save(model.state_dict(), filepath)

#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()

Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:

state = {
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}
torch.save(state, filepath)

To resume training you would do things like: state = torch.load(filepath), and then, to restore the state of each individual object, something like this:

model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])

Since you are resuming training, DO NOT call model.eval() once you restore the states when loading.

Case # 3: Model to be used by someone else with no access to your code: In Tensorflow you can create a .pb file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve. The equivalent way to do this in Pytorch would be:

torch.save(model, filepath)

# Then later:
model = torch.load(filepath)

This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.

HttpGet with HTTPS : SSLPeerUnverifiedException

This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

How do I restore a dump file from mysqldump?

Run the command to enter into the DB

 # mysql -u root -p 

Enter the password for the user Then Create a New DB

mysql> create database MynewDB;
mysql> exit

And make exit.Afetr that.Run this Command

# mysql -u root -p  MynewDB < MynewDB.sql

Then enter into the db and type

mysql> show databases;
mysql> use MynewDB;
mysql> show tables;
mysql> exit

Thats it ........ Your dump will be restored from one DB to another DB

Or else there is an Alternate way for dump restore

# mysql -u root -p 

Then enter into the db and type

mysql> create database MynewDB;
mysql> show databases;
mysql> use MynewDB;
mysql> source MynewDB.sql;
mysql> show tables;
mysql> exit

SQL search multiple values in same field

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.

Unicode character as bullet for list-item in CSS

To add a star use the Unicode character 22C6.

I added a space to make a little gap between the li and the star. The code for space is A0.

li:before {
    content: '\22C6\A0';
}

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

Use Python's json module, or simplejson if you don't have python 2.6 or higher.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

You should look for the MSI setup logs in the temp directory of your system. They will contain detailed inforamtion about why the setup failed. I had a similar installation problem with Visual Studio 2008 which I was able to resolve by studying the logs.

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

How to use switch statement inside a React component?

I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.

Here is my solution:

Definitions:

const Switch = props => {
    const { test, children = null } = props;
    return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}

const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;

Case.propTypes = {
    casevalue: PropTypes.string.isRequired,
    children: PropTypes.node.isRequired,
}

const Default = ({ children }) => children || <h1>NO_RESULT</h1>;

const SwitchCase = ({ test, cases = [], defaultValue = null }) => {

    const defaultVal = defaultValue
        && React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
        || <Default key='default-key' casevalue={`${test}`} />;

    return (
        <Switch test={`${test}`} >
            {
                cases.map((cas, i) => {
                    const { props = {} } = cas || {};
                    const { casevalue = false, ...rest } = props || {};

                    return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
                })
                .concat(defaultVal)
            }
        </Switch>
    );
}

Usage:

<SwitchCase
  cases={[
    <div casevalue={`${false}`}>#1</div>,
    <div casevalue={`${true}`}>#2</div>,
    <div casevalue={`${false}`}>#3</div>,
  ]}
  defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
  test={`${true}`}
/>

Implement touch using Python?

Why not try this?:

import os

def touch(fname):
    try:
        os.utime(fname, None)
    except OSError:
        open(fname, 'a').close()

I believe this eliminates any race condition that matters. If the file does not exist then an exception will be thrown.

The only possible race condition here is if the file is created before open() is called but after os.utime(). But this does not matter because in this case the modification time will be as expected since it must have happened during the call to touch().

Interfaces — What's the point?

Consider the case where you don't control or own the base classes.

Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.

Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.

For instance you might want a common way to handle theming, or a common way to handle localization.

In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.

Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.

But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".

Enter interfaces.

Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.

You would create "YourButton", descend from Button, and add support for all the interfaces you need.

This would allow you to write code like the following:

foreach (Control ctrl in Controls)
{
    if (ctrl is IMyThemableControl)
        ((IMyThemableControl)ctrl).SetTheme(newTheme);
}

This would not be possible without interfaces, instead you would have to write code like this:

foreach (Control ctrl in Controls)
{
    if (ctrl is MyThemableButton)
        ((MyThemableButton)ctrl).SetTheme(newTheme);
    else if (ctrl is MyThemableTextBox)
        ((MyThemableTextBox)ctrl).SetTheme(newTheme);
    else if (ctrl is MyThemableGridView)
        ((MyThemableGridView)ctrl).SetTheme(newTheme);
    else ....
}

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

Angularjs - Pass argument to directive

You can pass arguments to your custom directive as you do with the builtin Angular-directives - by specifying an attribute on the directive-element:

angular.element(document.getElementById('wrapper'))
       .append('<directive-name title="title2"></directive-name>');

What you need to do is define the scope (including the argument(s)/parameter(s)) in the factory function of your directive. In below example the directive takes a title-parameter. You can then use it, for example in the template, using the regular Angular-way: {{title}}

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

Depending on how/what you want to bind, you have different options:

  • = is two-way binding
  • @ simply reads the value (one-way binding)
  • & is used to bind functions

In some cases you may want use an "external" name which differs from the "internal" name. With external I mean the attribute name on the directive-element and with internal I mean the name of the variable which is used within the directive's scope.

For example if we look at above directive, you might not want to specify another, additional attribute for the title, even though you internally want to work with a title-property. Instead you want to use your directive as follows:

<directive-name="title2"></directive-name>

This can be achieved by specifying a name behind the above mentioned option in the scope definition:

scope: {
    title: '@directiveName'
}

Please also note following things:

  • The HTML5-specification says that custom attributes (this is basically what is all over the place in Angular applications) should be prefixed with data-. Angular supports this by stripping the data--prefix from any attributes. So in above example you could specify the attribute on the element (data-title="title2") and internally everything would be the same.
  • Attributes on elements are always in the form of <div data-my-attribute="..." /> while in code (e.g. properties on scope object) they are in the form of myAttribute. I lost lots of time before I realized this.
  • For another approach to exchanging/sharing data between different Angular components (controllers, directives), you might want to have a look at services or directive controllers.
  • You can find more information on the Angular homepage (directives)

How do I set the eclipse.ini -vm option?

I'd like to share this little hack:

A click on the Eclipse's icon indicated a problem with the JRE. So, I put this command in the destination field of the icon's properties:

C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw

Thinking that the "'" would solve the problem with the space in the path. That did not function. Then, I tried this command:

C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw

with success

What is Unicode, UTF-8, UTF-16?

Unicode is a standard which maps the characters in all languages to a particular numeric value called Code Points. The reason it does this is that it allows different encodings to be possible using the same set of code points.

UTF-8 and UTF-16 are two such encodings. They take code points as input and encodes them using some well-defined formula to produce the encoded string.

Choosing a particular encoding depends upon your requirements. Different encodings have different memory requirements and depending upon the characters that you will be dealing with, you should choose the encoding which uses the least sequences of bytes to encode those characters.

For more in-depth details about Unicode, UTF-8 and UTF-16, you can check out this article,

What every programmer should know about Unicode

Android refresh current activity

public void onClick (View v){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

How do I sort a dictionary by value?

Use ValueSortedDict from dicts:

from dicts.sorteddict import ValueSortedDict
d = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_dict = ValueSortedDict(d)
print sorted_dict.items() 

[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

JavaScript - Use variable in string match

for me anyways, it helps to see it used. just made this using the "re" example:

var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');  
for(i=0;i<storage_keys.length;i++) { 
    if(storage_keys[i].match(re)) {
        console.log(storage_keys[i]);
        var partnum = storage_keys[i].split('-')[2];
    }
}

Android - Using Custom Font

Update answer: Android 8.0 (API level 26) introduces a new feature, Fonts in XML. just use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26.

see this link


Old answer

There are two ways to customize fonts :

!!! my custom font in assets/fonts/iran_sans.ttf



Way 1 : Refrection Typeface.class ||| best way

call FontsOverride.setDefaultFont() in class extends Application, This code will cause all software fonts to be changed, even Toasts fonts

AppController.java

public class AppController extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //Initial Font
        FontsOverride.setDefaultFont(getApplicationContext(), "MONOSPACE", "fonts/iran_sans.ttf");

    }
}

FontsOverride.java

public class FontsOverride {

    public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    private static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}



Way 2: use setTypeface

for special view just call setTypeface() to change font.

CTextView.java

public class CTextView extends TextView {

    public CTextView(Context context) {
        super(context);
        init(context,null);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    public void init(Context context, @Nullable AttributeSet attrs) {

        if (isInEditMode())
            return;

        // use setTypeface for change font this view
        setTypeface(FontUtils.getTypeface("fonts/iran_sans.ttf"));

    }
}

FontUtils.java

public class FontUtils {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<>();

    public static Typeface getTypeface(String fontName) {
        Typeface tf = fontCache.get(fontName);
        if (tf == null) {
            try {
                tf = Typeface.createFromAsset(AppController.getInstance().getApplicationContext().getAssets(), fontName);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }

}

How do you add an in-app purchase to an iOS application?

I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.

In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.

To summarize:

1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.

These SKProducts should be used to populate your store UI which the user can use to buy a specific product.

2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.

3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:

SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction

4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:

paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError

Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.

Here is another one I created to explain certain things that only text could describe in better manner.

Why can't I duplicate a slice with `copy()`?

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

Read remote file with node.js (http.get)

You can do something like this, without using any external libraries.

const fs = require("fs");
const https = require("https");

const file = fs.createWriteStream("data.txt");

https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {
    console.log("done");
  });
});

Converting Select results into Insert script - SQL Server

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

What are major differences between C# and Java?

Comparing Java 7 and C# 3

(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)

Not all of your summary is correct:

  • In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
  • There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)

Beyond that (and what's in your summary already):

  • Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
  • C# doesn't have checked exceptions
  • Java doesn't allow the creation of user-defined value types
  • Java doesn't have operator and conversion overloading
  • Java doesn't have iterator blocks for simple implemetation of iterators
  • Java doesn't have anything like LINQ
  • Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
  • Java doesn't have expression trees
  • C# doesn't have anonymous inner classes
  • C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
  • Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
  • Java doesn't have any equivalent to the C# 3.0 anonymous types
  • Java doesn't have implicitly typed local variables
  • Java doesn't have extension methods
  • Java doesn't have object and collection initializer expressions
  • The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
  • The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
  • Java doesn't have properties as part of the language; they're a convention of get/set/is methods
  • Java doesn't have the equivalent of "unsafe" code
  • Interop is easier in C# (and .NET in general) than Java's JNI
  • Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
  • Java has no preprocessor directives (#define, #if etc in C#).
  • Java has no equivalent of C#'s ref and out for passing parameters by reference
  • Java has no equivalent of partial types
  • C# interfaces cannot declare fields
  • Java has no unsigned integer types
  • Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
  • Java has no equivalent of nullable value types
  • Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.

This is not exhaustive, but it covers everything I can think of off-hand.

HTML5 validation when the input type is not "submit"

2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.

The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

Updated solution snippet:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.reportValidity()) {
    f.submit();
  }
}

Mockito - NullpointerException when stubbing Method

Another common gotcha is that the method signature is accidentally declared as 'final'.

This one catches out a lot of people who work on codebases which are subjected to Checkstyle and have internalised the need to mark members as final.

i.e. in the OP's example:

object.method()

Make sure that method() is not declared as final:

public final Object method() {
}

Mockito cannot mock a final method and this will come up as a wrapped NPE:

Suppressed: org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

Buried deep in the error message is the following:

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

What is the difference between aggregation, composition and dependency?

One object may contain another as a part of its attribute.

  1. document contains sentences which contain words.
  2. Computer system has a hard disk, ram, processor etc.

So containment need not be physical. e.g., computer system has a warranty.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

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

Switch on Enum in Java

Article on Programming.Guide: Switch on enum


enum MyEnum { CONST_ONE, CONST_TWO }

class Test {
        public static void main(String[] args) {
            MyEnum e = MyEnum.CONST_ONE;

            switch (e) {
                case CONST_ONE: System.out.println(1); break;
                case CONST_TWO: System.out.println(2); break;
            }
        }
    }

Switches for strings are implemented in Java 7.

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How can I display an image from a file in Jupyter Notebook?

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

Changing the action of a form with JavaScript/jQuery

just to add a detail to what Tamlyn wrote, instead of
$('form').get(0).setAttribute('action', 'baz'); //this works

$('form')[0].setAttribute('action', 'baz');
works equally well

Build Android Studio app via command line

Official Documentation is here:

To build a debug APK, open a command line and navigate to the root of your project directory. To initiate a debug build, invoke the assembleDebug task:

gradlew assembleDebug

This creates an APK named module_name-debug.apk in project_name/module_name/build/outputs/apk/.

Count immediate child div elements using jQuery

Try this for immediate child elements of type div

$("#foo > div")[0].children.length

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

How to pass boolean parameter value in pipeline to downstream jobs?

Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:

if (myBoolean == "true")

How to remove last n characters from every element in the R vector

Similar to @Matthew_Plourde using gsub

However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:

cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"    ""    ""

Difference is, {0,3} quantifier indicates 0 to 3 matches, whereas {3} requires exactly 3 matches otherwise no match is found in which case gsub returns the original, unmodified string.

N.B. using {,3} would be equivalent to {0,3}, I simply prefer the latter notation.

See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html