Programs & Examples On #Tmux

tmux is a terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached.

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

The other answers did not help me as I only had client attached (the previous one that started the session was already detached).

To fix it I followed the answer here (I was not using xterm).

Which simply said:

  1. Detach from tmux session
  2. Run resize linux command
  3. Reattach to tmux session

tmux set -g mouse-mode on doesn't work

this should work:

setw -g mode-mouse on

then resource then config file

tmux source-file ~/.tmux.conf

or kill the server

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

How to terminate a window in tmux?

<Prefix> & for killing a window

<Prefix> x for killing a pane

If there is only one pane (i.e. the window is not split into multiple panes, <Prefix> x would kill the window)

As always iterated, <Prefix> is generally CTRL+b. (I think for beginner questions, we can just say CTRL+b all the time, and not talk about prefix at all, but anyway :) )

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Adding to the thread, there's a new console in town called babun, im running tmux in it without a problem. lets you run bash or the zsh.

click here for github

How to set up tmux so that it starts up with specified windows opened?

You can source different sessions from your .tmux.conf like so:

# initialize sessions
bind S source-file ~/.tmux/session1 
bind s source-file ~/.tmux/session2

And then format the sessions as you require:

#session1
new  -s SessionName -n WindowName Command
neww -n foo/bar foo
splitw -v -p 50 -t 0 bar
selectw -t 1 
selectp -t 0

This would open 2 windows, the second of which would be named foo/bar and would be split vertically in half (50%) with foo running above bar. Focus would be in window 2 (foo/bar), top pane (foo).

You can then start your preferred tmux session (in this case, session1) with PrefixShifts

Printing an array in C++?

// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}

Create Excel file in Java

Changing the extension of a file does not in any way change its contents. The extension is just a label.

If you want to work with Excel spreadsheets using Java, read up on the Apache POI library.

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Thanks a bundle, guys. You are great.

I used Chuff's answer and modified it a little to do what I wanted.

I have 2 worksheets in the same workbook.

On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message

Then I inserted a new blank column next to the phone number

On worksheet 2 I have two columns: phone number, name of person

Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.

Then just copy the formula down the whole column until last sms It worked beautifully.

=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)

Difference between "or" and || in Ruby?

puts false or true --> prints: false

puts false || true --> prints: true

How do I test a single file using Jest?

I just installed Jest as global, ran jest myFileToTest.spec.js, and it worked.

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

How to get query string parameter from MVC Razor markup?

Similar thread

<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

EDIT 01-10-2014: Since this question is so popular this answer has been improved.

The example above will only get the values from RouteData, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:

<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

You can also check RouteValues vs QueryString MVC?

EDIT 03-05-2019: Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query object from Context.Request path. So it would be:

<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>

Please notice I am using StringValues("1") in the statement because Query returns StringValues struct instead of pure string. That's cleanes way for this scenerio which I've found.

How to turn off caching on Firefox?

Have you tried to use CTRL-F5 to update the page?

MySQL Workbench not opening on Windows

In my case, i tried all solutions but nothing worked.

My SO is windows 7 x64, with all the Redistributable Packages (x86,x64 / 2010,2013,2015)

The problem was that i tried to install the x64 workbench, but for some reason did not work (even my SO is x64).

so, the solution was download the x86 installer from : https://downloads.mysql.com/archives/workbench/

Serializing an object to JSON

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

How to find out if a Python object is a string?

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Is it possible to force row level locking in SQL Server?

You can't really force the optimizer to do anything, but you can guide it.

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

See - Controlling SQL Server with Locking and Hints

WebSockets vs. Server-Sent events/EventSource

One thing to note:
I have had issues with websockets and corporate firewalls. (Using HTTPS helps but not always.)

See https://github.com/LearnBoost/socket.io/wiki/Socket.IO-and-firewall-software https://github.com/sockjs/sockjs-client/issues/94

I assume there aren't as many issues with Server-Sent Events. But I don't know.

That said, WebSockets are tons of fun. I have a little web game that uses websockets (via Socket.IO) (http://minibman.com)

C# Reflection: How to get class reference from string?

We can use

Type.GetType()

to get class name and can also create object of it using Activator.CreateInstance(type);

using System;
using System.Reflection;

namespace MyApplication
{
    class Application
    {
        static void Main()
        {
            Type type = Type.GetType("MyApplication.Action");
            if (type == null)
            {
                throw new Exception("Type not found.");
            }
            var instance = Activator.CreateInstance(type);
            //or
            var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
        }
    }

    public class Action
    {
        public string key { get; set; }
        public string Value { get; set; }
    }
}

Uncaught SyntaxError: Unexpected token :

This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.

How to print all session variables currently set?

Not a simple way, no.

Let's say that by "active" you mean "hasn't passed the maximum lifetime" and hasn't been explicitly destroyed and that you're using the default session handler.

  • First, the maximum lifetime is defined as a php.ini config and is defined in terms of the last activity on the session. So the "expiry" mechanism would have to read the content of the sessions to determine the application-defined expiry.
  • Second, you'd have to manually read the sessions directory and read the files, whose format I don't even know they're in.

If you really need this, you must implement some sort of custom session handler. See session_set_save_handler.

Take also in consideration that you'll have no feedback if the user just closes the browser or moves away from your site without explciitly logging out. Depending on much inactivity you consider the threshold to deem a session "inactive", the number of false positives you'll get may be very high.

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

Remove the following hot fixes and updates

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Restart the PC and try to uninstall now. This worked for me without problems.

Commenting code in Notepad++

In your n++ editor, you can go to Setting > Shortcut mapper and find all shortcut information as well as you can edit them :)

How to replace existing value of ArrayList element in Java

You must use

list.remove(indexYouWantToReplace);

first.

Your elements will become like this. [zero, one, three]

then add this

list.add(indexYouWantedToReplace, newElement)

Your elements will become like this. [zero, one, new, three]

Is there a method that calculates a factorial in Java?

Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

Is it possible to run selenium (Firefox) web driver without a GUI?

An optional is to use pyvirtualdisplay like this:

from pyvirtualdisplay import Display

display = Display(visible=0, size=[800, 600])
display.start()

#do selenium job here

display.close()

A shorter version is:

with Display() as display:
    # selenium job here

This is generally a python encapsulate of xvfb, and more convinient somehow.

By the way, although PhantomJS is a headless browser and no window will be open if you use it, it seems that PhantomJS still needs a gui environment to work.

I got Error Code -6 when I use PhantomJS() instead of Firefox() in headless mode (putty-connected console). However everything is ok in desktop environment.

How does one convert a HashMap to a List in Java?

Collection Interface has 3 views

  • keySet
  • values
  • entrySet

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

      Map m=new HashMap();
          m.put(3, "dev2");
          m.put(4, "dev3");

      List<Entry> entryList = new ArrayList<Entry>(m.entrySet());

      for (Entry s : entryList) {
        System.out.println(s);
      }

ArrayList has this constructor.

How to parse XML and count instances of a particular node attribute?

import xml.etree.ElementTree as ET
data = '''<foo>
           <bar>
               <type foobar="1"/>
               <type foobar="2"/>
          </bar>
       </foo>'''
tree = ET.fromstring(data)
lst = tree.findall('bar/type')
for item in lst:
    print item.get('foobar')

This will print the value of the foobar attribute.

AngularJS Uploading An Image With ng-upload

There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

controller

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

Is key-value pair available in Typescript?

The simplest way would be something like:

var indexedArray: {[key: string]: number}

Usage:

var indexedArray: {[key: string]: number} = {
    foo: 2118,
    bar: 2118
}

indexedArray['foo'] = 2118;
indexedArray.foo= 2118;

let foo = indexedArray['myKey'];
let bar = indexedArray.myKey;

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

bootstrap jquery show.bs.modal event won't fire

This happens when code might been executed before and it's not showing up so you can add timeout() for it tp fire.

$(document).on('shown.bs.modal', function (event) {
      setTimeout(function(){
        alert("Hi");
      },1000); 
    });

Thread pooling in C++11

A threadpool with no dependencies outside of STL is entirely possible. I recently wrote a small header-only threadpool library to address the exact same problem. It supports dynamic pool resizing (changing the number of workers at runtime), waiting, stopping, pausing, resuming and so on. I hope you find it useful.

What is object serialization?

Serialization is the process of turning a Java object into byte array and then back into object again with its preserved state. Useful for various things like sending objects over network or caching things to disk.

Read more from this short article which explains programming part of the process quite well and then move over to to Serializable javadoc. You may also be interested in reading this related question.

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

How to redirect to a 404 in Rails?

If you want to handle different 404s in different ways, consider catching them in your controllers. This will allow you to do things like tracking the number of 404s generated by different user groups, have support interact with users to find out what went wrong / what part of the user experience might need tweaking, do A/B testing, etc.

I have here placed the base logic in ApplicationController, but it can also be placed in more specific controllers, to have special logic only for one controller.

The reason I am using an if with ENV['RESCUE_404'], is so I can test the raising of AR::RecordNotFound in isolation. In tests, I can set this ENV var to false, and my rescue_from would not fire. This way I can test the raising separate from the conditional 404 logic.

class ApplicationController < ActionController::Base

  rescue_from ActiveRecord::RecordNotFound, with: :conditional_404_redirect if ENV['RESCUE_404']

private

  def conditional_404_redirect
    track_404(@current_user)
    if @current_user.present?
      redirect_to_user_home          
    else
      redirect_to_front
    end
  end

end

Adding gif image in an ImageView in android

This is what worked for me:

In your build.gradle (project) write mavenCentral() in the buildscript{} and allprojects {}. It should look like this:

buildscript {
    repositories {
        jcenter()
        **mavenCentral()**
    }
//more code ...
}
allprojects {
    repositories {
        jcenter()
        **mavenCentral()**
    }
}

Then, in build.gradle(module) add in dependencies{} this snippet:

compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'

it should look like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    **compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'**
}

Put your .gif image in your drawable folder. Now go to app > res > layout > activity_main.xml and add this snipped for your .gif:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/YOUR_GIF_IMAGE"
    android:background="#000000" //for black background
    />

And you're done :)

Helpful links: https://github.com/koral--/android-gif-drawable

https://www.youtube.com/watch?v=EOFY0cwNjuk

Hope this helps.

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

Keep overflow div scrolled to bottom unless user scrolls up

Here's a solution based on a blog post by Ryan Hunt. It depends on the overflow-anchor CSS property, which pins the scrolling position to an element at the bottom of the scrolled content.

_x000D_
_x000D_
function addMessage() {
  const $message = document.createElement('div');
  $message.className = 'message';
  $message.innerText = `Random number = ${Math.ceil(Math.random() * 1000)}`;
  $messages.insertBefore($message, $anchor);

  // Trigger the scroll pinning when the scroller overflows
  if (!overflowing) {
    overflowing = isOverflowing($scroller);
    $scroller.scrollTop = $scroller.scrollHeight;
  }
}

function isOverflowing($el) {
  return $el.scrollHeight > $el.clientHeight;
}

const $scroller = document.querySelector('.scroller');
const $messages = document.querySelector('.messages');
const $anchor = document.querySelector('.anchor');
let overflowing = false;

setInterval(addMessage, 1000);
_x000D_
.scroller {
  overflow: auto;
  height: 90vh;
  max-height: 11em;
  background: #555;
}

.messages > * {
  overflow-anchor: none;
}

.anchor {
  overflow-anchor: auto;
  height: 1px;
}

.message {
  margin: .3em;
  padding: .5em;
  background: #eee;
}
_x000D_
<section class="scroller">
  <div class="messages">
    <div class="anchor"></div>
  </div>
</section>
_x000D_
_x000D_
_x000D_

Note that overflow-anchor doesn't currently work in Safari.

"pip install json" fails on Ubuntu

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

Readably print out a python dict() sorted by key

An easy way to print the sorted contents of the dictionary, in Python 3:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

The expression dict_example.items() returns tuples, which can then be sorted by sorted():

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

Below is an example to pretty print the sorted contents of a Python dictionary's values.

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

Bootstrap 3 Glyphicons are not working

I work with VS2015, ASP.NET MVC 6 (RC) and also had problems (error messages to the reference, icons not showed) with the gliphicons in production (where it has worked in VS (development)).
The reason seems to be, that the MS cdn page is down (at least right now and from Switzerland): http://www.websitedown.info/ajax.aspnetcdn.com

Therefore (as temporary workaround), I have changed the external reference in _Layout.cshtml (under environment names="Staging,Production") to "internal" reference:
from:

<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css"

to

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"

After doing that, it works again.

cURL equivalent in Node.js?

The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.

This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.

Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

How to know installed Oracle Client is 32 bit or 64 bit?

The following, taken from here, was not mentioned here:

If the Oracle Client is 32 bit, it will contain a "lib" folder; but if it is a 64 bit Oracle Client it will have both "lib" and "lib32" folders.

Also, starting in Oracle 11.2.0.1, the client version for 64-bit and the Oracle client for 32-bit are shipped separately, and there is an $ORACLE_HOME/lib64 directory.

$ORACLE_HOME/lib/ ==> 32 bit $ORACLE_HOME/lib64 ==> 64 bit

Or

$ORACLE_HOME/lib/ ==> 64 bit $ORACLE_HOME/lib32 ==> 32 bit

Waiting for another flutter command to release the startup lock

In Windows :

Press: Ctrl + Alt + Delete

  • In task manager find out your editor such as VS Studio or Android Studio
  • In that Find "dart" and End that Task
  • Then close your editor
  • Open editor again
  • let editor to complete all things, after that run your query that will work

Join between tables in two different databases?

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:

SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.

How to get user name using Windows authentication in asp.net?

It depends on the configuration of the application as well as on IIS as this gentleman in the below link has rightfully explained. Please see his article below

http://richhewlett.com/2011/02/15/getting-a-users-username-in-asp-net/

Google Maps: How to create a custom InfoWindow?

Styling the infowindow is fairly straightforward with vanilla javascript. I used some of the info from this thread when writing this. I also took into account the possible problems with earlier versions of ie (although I have not tested it with them).

var infowindow = new google.maps.InfoWindow({
  content: '<div id="gm_content">'+contentString+'</div>'
});

google.maps.event.addListener(infowindow,'domready',function(){
  var el = document.getElementById('gm_content').parentNode.parentNode.parentNode;
  el.firstChild.setAttribute('class','closeInfoWindow');
  el.firstChild.setAttribute('title','Close Info Window');
  el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
  el.setAttribute('class','infoWindowContainer');
  for(var i=0; i<11; i++){
    el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
    el.style.display = 'none';
  }
});

The code creates the infowindow as usual (no need for plugins, custom overlays or huge code), using a div with an id to hold the content. This gives a hook in the system that we can use to get the correct elements to manipulate with a simple external stylesheet.

There are a couple of extra pieces (that are not strictly needed) which handle things like giving a hook into the div with the close info window image in it.

The final loop hides all the pieces of the pointer arrow. I needed this myself as I wanted to have transparency on the infowindow and the arrow got in the way. Of course, with the hook, changing the code to replace the arrow image with a png of your choice should be fairly simple too.

If you want to change it to jquery (no idea why you would) then that should be fairly simple.

I'm not usually a javascript developer so any thoughts, comments, criticisms welcome :)

How to open select file dialog via js?

For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:

<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

Best way to move files between S3 buckets?

For me the following command just worked:

aws s3 mv s3://bucket/data s3://bucket/old_data --recursive

ITSAppUsesNonExemptEncryption export compliance while internal testing?

To select from dropdown please start typing following line:

App Uses Non-Exempt Encryption

How to read file with async/await properly?

You can easily wrap the readFile command with a promise like so:

async function readFile(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          reject(err);
        }
        resolve(data);
      });
    });
  }

then use:

await readFile("path/to/file");

D3.js: How to get the computed width and height for an arbitrary element?

For SVG elements

Using something like selection.node().getBBox() you get values like

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

For HTML elements

Use selection.node().getBoundingClientRect()

Hibernate Auto Increment ID

In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.

I have found that this works...as an example.

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;

For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .

In my case i do an HTML POST with JSON like so...

{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

How do I pass a value from a child back to the parent form?

If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go. My example here would be used if you needed the child to communicate back to the parent while remaining open.

In your parent form, add a public method that the child form will call, such as

public void NotifyMe(string s)
{
    // Do whatever you need to do with the string
}

Next, when you need to launch the child window from the parent, use this code:

using (FormOptions formOptions = new FormOptions())
{
    // passing this in ShowDialog will set the .Owner 
    // property of the child form
    formOptions.ShowDialog(this);
}

In the child form, use this code to pass a value back to the parent:

ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");

The code in this example would be better used for something like a toolbox window which is intended to float above the main form. In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().

A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method). However, this is not automatically a bad thing.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

In my case the above suggestions did not work for me. Mine was little different scenario.

When i tried installing bundler using gem install bundler .. But i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

then i tried using sudo gem install bundler then i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
  You don't have write permissions for the /usr/bin directory.

then i tried with sudo gem install bundler -n /usr/local/bin ( Just /usr/bin dint work in my case ).

And then successfully installed bundler

EDIT: I use MacOS, maybe /usr/bin din't work for me for that reason (https://stackoverflow.com/a/34989655/3786657 comment )

AppStore - App status is ready for sale, but not in app store

You may also need to provide your contact info, bank info, and tax info in this page so it will allow your last release on App Store:

https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/6.0

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

HTML5 Number Input - Always show 2 decimal places

If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:

Javascript:

function limitDecimalPlaces(e, count) {
  if (e.target.value.indexOf('.') == -1) { return; }
  if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
    e.target.value = parseFloat(e.target.value).toFixed(count);
  }
}

HTML:

<input type="number" oninput="limitDecimalPlaces(event, 2)" />

Note that this cannot AFAIK, defend against this chrome bug with the number input.

MySQL Creating tables with Foreign Keys giving errno: 150

What's the current state of your database when you run this script? Is it completely empty? Your SQL runs fine for me when creating a database from scratch, but errno 150 usually has to do with dropping & recreating tables that are part of a foreign key. I'm getting the feeling you're not working with a 100% fresh and new database.

If you're erroring out when "source"-ing your SQL file, you should be able to run the command "SHOW ENGINE INNODB STATUS" from the MySQL prompt immediately after the "source" command to see more detailed error info.

You may want to check out the manual entry too:

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message. If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed.

— MySQL 5.1 reference manual.

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

How can I access and process nested objects, arrays or JSON?

The Underscore js Way

Which is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

Solution:

var data = {
  code: 42,
  items: [{
    id: 1,
    name: 'foo'
  }, {
    id: 2,
    name: 'bar'
  }]
};

var item = _.findWhere(data.items, {
  id: 2
});
if (!_.isUndefined(item)) {
  console.log('NAME =>', item.name);
}

//using find - 

var item = _.find(data.items, function(item) {
  return item.id === 2;
});

if (!_.isUndefined(item)) {
  console.log('NAME =>', item.name);
}

How to break/exit from a each() function in JQuery?

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago.

Returning value from called function in a shell script

If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

if function_name; then
  do something
else
  error condition
fi

A failure occurred while executing com.android.build.gradle.internal.tasks

classpath 'com.android.tools.build:gradle:3.3.2' change class path and it will work

Disable hover effects on mobile browsers

Try this easy 2019 jquery solution, although its been around a while;

  1. add this plugin to head:

    src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"

  2. add this to js:

    $("*").on("touchend", function(e) { $(this).focus(); }); //applies to all elements

  3. some suggested variations to this are:

    $(":input, :checkbox,").on("touchend", function(e) {(this).focus);}); //specify elements
    
    $("*").on("click, touchend", function(e) { $(this).focus(); });  //include click event`
    
    css: body { cursor: pointer; } //touch anywhere to end a focus`
    

Notes

  • place plugin before bootstrap.js, if applicable, to avoid affecting tooltips
  • only tested on iphone XR ios 12.1.12, and ipad 3 ios 9.3.5, using Safari or Chrome.

References:

https://code.jquery.com/ui/

https://api.jquery.com/category/selectors/jquery-selector-extensions/

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

jQuery How do you get an image to fade in on load?

The key is to use $(window).load(function(){} so we know the image is loaded. Hide the image via the css function then fade it in using fadeIn:

$(function() {

  $(window).load(function(){
    $('#logo').css({visibility: 'visible', opacity: 0}).fadeIn(1000);
  });

});

Idea from: http://www.getpeel.com/

How can I provide multiple conditions for data trigger in WPF?

THIS ANSWER IS FOR ANIMATIONS ONLY


If you wanna implement the AND logic, you should use MultiTrigger, here is an example:

Suppose we want to do some actions if the property Text="" (empty string) AND IsKeyboardFocused="False", then your code should look like the following:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
        <MultiTrigger.EnterActions>
            <!-- Your actions here -->
        </MultiTrigger.EnterActions>
</MultiTrigger>

If you wanna implement the OR logic, there are couple of ways, and it depends on what you try to do:

The first option is to use multiple Triggers.
So, suppose you wanna do something if either Text="" OR IsKeyboardFocused="False",
then your code should look something like this:

<Trigger Property="IsEnabled" Value="false">
    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="BorderBrush" TargetName="border" 
            Value="{StaticResource TextBox.MouseOver.Border}"/>
</Trigger>


But the problem in this is what will I do if i wanna do something if either Text ISN'T null OR IsKeyboard="True"? This can be achieved by the second approach:
Recall De Morgan's rule, that says !(!x && !y) = x || y.
So we'll use it to solve the previous problem, by writing a multi trigger that it's triggered when Text="" and IsKeyboard="True", and we'll do our actions in EXIT ACTIONS, like this:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
    <MultiTrigger.ExitActions>
        <!-- Do something here -->
    </MultiTrigger.ExitActions>
</MultiTrigger>

Create a dictionary with list comprehension

You can create a new dict for each pair and merge it with the previous dict:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

Obviously this approaches requires reduce from functools.

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

Switching the order of block elements with CSS

As has already been suggested, Flexbox is the answer - particularly because you only need to support a single modern browser: Mobile Safari.

See: http://jsfiddle.net/thirtydot/hLUHL/

You can remove the -moz- prefixed properties if you like, I just left them in for future readers.

_x000D_
_x000D_
    #blockContainer {_x000D_
        display: -webkit-box;_x000D_
        display: -moz-box;_x000D_
        display: box;_x000D_
        _x000D_
        -webkit-box-orient: vertical;_x000D_
        -moz-box-orient: vertical;_x000D_
        box-orient: vertical;_x000D_
    }_x000D_
    #blockA {_x000D_
        -webkit-box-ordinal-group: 2;_x000D_
        -moz-box-ordinal-group: 2;_x000D_
        box-ordinal-group: 2;_x000D_
    }_x000D_
    #blockB {_x000D_
        -webkit-box-ordinal-group: 3;_x000D_
        -moz-box-ordinal-group: 3;_x000D_
        box-ordinal-group: 3;_x000D_
    }
_x000D_
    <div id="blockContainer">_x000D_
        <div id="blockA">Block A</div>_x000D_
        <div id="blockB">Block B</div>_x000D_
        <div id="blockC">Block C</div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How to get visitor's location (i.e. country) using geolocation?

you can't get city location by ip. here you can get country with jquery:

$.get("http://ip-api.com/json", function(response) {
console.log(response.country);}, "jsonp");

Peak-finding algorithm for Python/SciPy

The function scipy.signal.find_peaks, as its name suggests, is useful for this. But it's important to understand well its parameters width, threshold, distance and above all prominence to get a good peak extraction.

According to my tests and the documentation, the concept of prominence is "the useful concept" to keep the good peaks, and discard the noisy peaks.

What is (topographic) prominence? It is "the minimum height necessary to descend to get from the summit to any higher terrain", as it can be seen here:

enter image description here

The idea is:

The higher the prominence, the more "important" the peak is.

Test:

enter image description here

I used a (noisy) frequency-varying sinusoid on purpose because it shows many difficulties. We can see that the width parameter is not very useful here because if you set a minimum width too high, then it won't be able to track very close peaks in the high frequency part. If you set width too low, you would have many unwanted peaks in the left part of the signal. Same problem with distance. threshold only compares with the direct neighbours, which is not useful here. prominence is the one that gives the best solution. Note that you can combine many of these parameters!

Code:

import numpy as np
import matplotlib.pyplot as plt 
from scipy.signal import find_peaks

x = np.sin(2*np.pi*(2**np.linspace(2,10,1000))*np.arange(1000)/48000) + np.random.normal(0, 1, 1000) * 0.15
peaks, _ = find_peaks(x, distance=20)
peaks2, _ = find_peaks(x, prominence=1)      # BEST!
peaks3, _ = find_peaks(x, width=20)
peaks4, _ = find_peaks(x, threshold=0.4)     # Required vertical distance to its direct neighbouring samples, pretty useless
plt.subplot(2, 2, 1)
plt.plot(peaks, x[peaks], "xr"); plt.plot(x); plt.legend(['distance'])
plt.subplot(2, 2, 2)
plt.plot(peaks2, x[peaks2], "ob"); plt.plot(x); plt.legend(['prominence'])
plt.subplot(2, 2, 3)
plt.plot(peaks3, x[peaks3], "vg"); plt.plot(x); plt.legend(['width'])
plt.subplot(2, 2, 4)
plt.plot(peaks4, x[peaks4], "xk"); plt.plot(x); plt.legend(['threshold'])
plt.show()

String concatenation in Ruby

Here are more ways to do this:

"String1" + "String2"

"#{String1} #{String2}"

String1<<String2

And so on ...

Add regression line equation and R^2 on graph

Here's the most simplest code for everyone

Note: Showing Pearson's Rho and not R^2.

library(ggplot2)
library(ggpubr)

df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
        geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
        geom_point()+
        stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
        stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown

p

One such example with my own dataset

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

I also experienced this cmderror. After trying all the answers on here, I couldn't still figure out the problem, here is what I did:

  1. Cd into the project directory. e.g cd project-dir
  2. I migrated. e.g python manage.py migrate
  3. I created a super user. e.g python manage.py createsuperuser
  4. Enter the desired info like username, password, email etc
  5. You should get a "super user created successfully" response
  6. Now run the server. E.g python manage.py runserver
  7. Click on the URL displayed
  8. The URL on your browser should look like this, 127.0.0.1:8000/Quit
  9. Now edit the URL on your browser to this, 127.0.0.1:8000/admin
  10. You should see an administrative login page
  11. Login with the super user info you created earlier on
  12. You should be logged in to the Django administration
  13. Now click on "view site" at the top of the page
  14. You should see a page which shows "the install worked successfully..... Debug = True"
  15. Voila! your server is up and running

How can I write these variables into one line of code in C#?

 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

How to inject Javascript in WebBrowser control?

Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.

Step 1) Add a COM reference in your project to Microsoft HTML Object Library

Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml

Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>

Step 4) Add a WebBrowser control to your project

Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me

Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:

Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
    Dim head As HtmlElement
    Dim script As HtmlElement
    Dim domElement As IHTMLScriptElement

    head = wb.Document.GetElementsByTagName("head")(0)
    script = wb.Document.CreateElement("script")
    domElement = script.DomElement
    domElement.type = "text/javascript"
    domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
    head.AppendChild(script)
End Sub

Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:

Public Sub Callback_GetVar(ByVal vVar As String)
    Debug.Print(vVar)
End Sub

Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub

Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.

Requested registry access is not allowed

You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-)

How do I split a string on a delimiter in Bash?

If no space, Why not this?

IN="[email protected];[email protected]"
arr=(`echo $IN | tr ';' ' '`)

echo ${arr[0]}
echo ${arr[1]}

How do I hide javascript code in a webpage?

No, it isn't possible.

If you don't give it to the browser, then the browser doesn't have it.

If you do, then it (or an easily followed reference to it) forms part of the source.

Solve error javax.mail.AuthenticationFailedException

By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as

  1. Login to Gmail.
  2. Access the URL as https://www.google.com/settings/security/lesssecureapps
  3. Select "Turn on"

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

How to remove an item from an array in AngularJS scope?

If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:

$scope.remove = function() {
    var oldList = $scope.items;
    $scope.items = [];

    angular.forEach(oldList, function(x) {
        if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
    });
};

The list param is named items. The param x.done indicate if the item will be deleted.

Another references: Another example

Hope help you. Greetings.

Subscripts in plots in R

A subscript and referring to a stored value...

a <- 10
plot(c(0,1), c(0,1), type = 'n', ann = FALSE, xaxt = 'n', yaxt = 'n')
text(0.2, 0.6, cex = 1.5, bquote(paste('S'['f']*' = ', .(a))))

enter image description here

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

How to use 'git pull' from the command line?

Try setting the HOME environment variable in Windows to your home folder (c:\users\username).

( you can confirm that this is the problem by doing echo $HOME in git bash and echo %HOME% in cmd - latter might not be available )

IIS Express Windows Authentication

This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx (even though there is no such file on your site).

Add the following two lines to the appSettingssection of your site's Web.config.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

How do I install a module globally using npm?

I like using a package.json file in the root of your app folder.

Here is one I use

nvm use v0.6.4

http://pastie.org/3232212

npm install

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

Remember.. inherits is case sensitive for C# (not so for vb.net)

Found that out the hard way.

Adjusting and image Size to fit a div (bootstrap)

Simply add the class img-responsive to your img tag, it is applicable in bootstrap 3 onward!

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

CSS Input field text color of inputted text

Change your second style to this:

input, select, textarea{
    color: #ff0000;
}

At the moment, you are telling the form to change the text to black once the focus is off. The above remedies that.

Also, it is a good idea to place the normal state styles ahead of the :focus and :hover styles in your stylesheet. That helps prevent this problem. So

input, select, textarea{
    color: #ff0000;
}

textarea:focus, input:focus {
    color: #ff0000;
}

Getting GET "?" variable in laravel

In laravel 5.3

I want to show the get param in my view

Step 1 : my route

Route::get('my_route/{myvalue}', 'myController@myfunction');

Step 2 : Write a function inside your controller

public function myfunction($myvalue)
{
    return view('get')->with('myvalue', $myvalue);
}

Now you're returning the parameter that you passed to the view

Step 3 : Showing it in my View

Inside my view you i can simply echo it by using

{{ $myvalue }}

So If you have this in your url

http://127.0.0.1/yourproject/refral/[email protected]

Then it will print [email protected] in you view file

hope this helps someone.

How to set the style -webkit-transform dynamically using JavaScript?

The JavaScript style names are WebkitTransformOrigin and WebkitTransform

element.style.webkitTransform = "rotate(-2deg)";

Check the DOM extension reference for WebKit here.

'Use of Unresolved Identifier' in Swift

'Use of Unresolved Identifier' in Swift my also happen when you forgot to import a library. For example I have the error: enter image description here

In which I forgot the UIKit

import UIKit

Proper use of 'yield return'

This is kinda besides the point, but since the question is tagged best-practices I'll go ahead and throw in my two cents. For this type of thing I greatly prefer to make it into a property:

public static IEnumerable<Product> AllProducts
{
    get {
        using (AdventureWorksEntities db = new AdventureWorksEntities()) {
            var products = from product in db.Product
                           select product;

            return products;
        }
    }
}

Sure, it's a little more boiler-plate, but the code that uses this will look much cleaner:

prices = Whatever.AllProducts.Select (product => product.price);

vs

prices = Whatever.GetAllProducts().Select (product => product.price);

Note: I wouldn't do this for any methods that may take a while to do their work.

What is setContentView(R.layout.main)?

Why setContentView() in Android Had Been So Popular Till Now?

setContentView(int layoutid) - method of activity class. It shows layout on screen.

R.layout.main - is an integer number implemented in nested layout class of R.java class file.

At the run time device will pick up their layout based on the id given in setcontentview() method.

Use .htaccess to redirect HTTP to HTTPs

Redirect from http to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

This will work for sure!

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I would suggest 3 things:

  1. First try clearing browser's cache
  2. Try to assign username & password statically into config.inc.php
  3. Once you've done with installation, delete the config.inc.php file under "phpmyadmin" folder

The last one worked for me.

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

Call child component method from parent class - Angular

I think most easy way is using Subject. In bellow example code the child will be notified each time 'tellChild' is called.

Parent.component.ts

import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
    changingValue: Subject<boolean> = new Subject();
    tellChild(){
    this.changingValue.next(true);
  }
}

Parent.component.html

<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
  this.changing.subscribe(v => { 
     console.log('value is changing', v);
  });
}

Working sample on Stackblitz

JSON Naming Convention (snake_case, camelCase or PascalCase)

I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.

Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml

Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

If you run into this error in an IDE like Eclipse or IntelliJ, you may have one or more debug windows open and paused on a break-point. Terminate them.

VC++ fatal error LNK1168: cannot open filename.exe for writing

In my case, cleaning and rebuilding the project resolved the problem.

How do you truncate all tables in a database using TSQL?

It is a little late but it might help someone. I created a procedure sometimes back which does the following using T-SQL:

  1. Store all constraints in a Temporary table
  2. Drop All Constraints
  3. Truncate all tables with exception of some tables, which does not need truncation
  4. Recreate all Constraints.

I have listed it on my blog here

Can HTTP POST be limitless?

Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

How to use regex in XPath "contains" function

XPath 1.0 doesn't handle regex natively, you could try something like

//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]

(as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))] could be used to perform the same check your original regex does, if you need to check for middle digits as well)

In XPath 2.0, try

//*[matches(@id, 'sometext\d+_text')]

Linux Script to check if process is running and act on the result

If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{ $1=""; print $0}')
    ;;
esac

It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

Just an FYI

Angularjs - ng-cloak/ng-show elements blink

For what it's worth, I had a similar issue ng-cloak not working. It may be worth checking your app/site with cache enabled to reuse source files to see if that helps.

With my run-in with flickering, I was testing with DevTools open and cache disabled. Leaving the panel closed with caching enabled fixed my issue.

Showing an image from an array of images - Javascript

<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}

Is it safe to clean docker/overlay2/

I had this issue... It was the log that was huge. Logs are here :

/var/lib/docker/containers/<container id>/<container id>-json.log

You can manage this in the run command line or in the compose file. See there : Configure logging drivers

I personally added these 3 lines to my docker-compose.yml file :

my_container:
  logging:
    options:
      max-size: 10m

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

List all kafka topics

To read messages you should use:

kafka-console-consumer.sh --bootstrap-server kafka1:9092,kafka2:9092,kafka3:9092 --topic messages --from-beginning

--bootstrap-server is required attribute. You can use only single kafka1:9020 node.

caching JavaScript files

In your Apache .htaccess file:

#Create filter to match files you want to cache 
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>

I wrote about it here also:

http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

This situation occured if there are object in repository, which creates by current transaction.

Simple scenario:

  1. checkout some directory two times, as DIR1 and DIR2
  2. make 'svn mkdir test' in both
  3. make commit from DIR1
  4. try to make commit DIR2 (without svn up), SVN shall return this error

Same thing when adding same files from two working copies.

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

How to change an input button image using CSS?

I think the following is the best solution:

css:

.edit-button {
    background-image: url(edit.png);
    background-size: 100%;
    background-repeat:no-repeat;
    width: 24px;
    height: 24px;
}

html:

<input class="edit-button" type="image" src="transparent.png" />

pandas: filter rows of DataFrame with operator chaining

You can also leverage the numpy library for logical operations. Its pretty fast.

df[np.logical_and(df['A'] == 1 ,df['B'] == 6)]

addClass and removeClass in jQuery - not removing class

I think you're almost there. The thing is, your $(this) in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this) with $(this).closest(".clickable") . And don't forget the e.stopPropagation() as Guilherme is suggesting. that should be something like:

$( document ).ready(function() {   
    $(document).on("click", ".close_button", function () { 
        alert ("oi");
        e.stopPropagation()
        $(this).closest(".clickable").addClass("spot");
        $(this).closest(".clickable").removeClass("grown");
    });  


    $(document).on("click", ".clickable", function () {
        if ($(this).hasClass("spot")){
            $(this).addClass("grown");
            $(this).removeClass("spot");
        }
    });
});

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

How to convert a PNG image to a SVG?

I'm assuming that you wish to write software to do this. To do it naively you would just find lines and set the vectors. To do it intelligently, you attempt to fit shapes onto the drawing (model fitting). Additionally, you should attempt to ascertain bitmaped regions (regions you can't model through shames or applying textures. I would not recommend going this route as that it will take quite a bit of time and require a bit of graphics and computer vision knowledge. However, the output will much and scale much better than your original output.

async for loop in node.js

You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.

I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:

var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){ 
  search(config[key].query, function(err, result) { // <----- I added an err here
    if (err) return next(err)  // <---- don't keep going if there was an error

    var json = JSON.stringify({
      "result": result
    });
    results[key] = {
      "result": result
    }
    next()    /* <---- critical piece.  This is how the forEach knows to continue to
                       the next loop.  Must be called inside search's callback so that
                       it doesn't loop prematurely.*/
  })
}, function(err) {
  console.log('iterating done');
}); 

I hope that helps!

Compile to stand alone exe for C# app in Visual Studio 2010

You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.

If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).

laravel 5 : Class 'input' not found

In larvel => 6 Version:

Input no longer exists In larvel 6,7,8 Version. Use Request instead of Input.

Based on the Laravel docs, since version 6.x Input has been removed.

The Input Facade

Likelihood Of Impact: Medium

The Input facade, which was primarily a duplicate of the Request facade, has been removed. If you are using the Input::get method, you should now call the Request::input method. All other calls to the Input facade may simply be updated to use the Request facade.

use Illuminate\Support\Facades\Request;
..
..
..
 public function functionName(Request $request)
    {
        $searchInput = $request->q;
}

Java get month string from integer

This has already been mentioned, but here is a way to place the code within a method:

    public static String getMonthName(int monthIndex) {
         return new DateFormatSymbols().getMonths()[monthIndex].toString();
    }

or if you wanted to create a better error than an ArrayIndexOutOfBoundsException:

    public static String getMonthName(int monthIndex) {
        //since this is zero based, 11 = December
        if (monthIndex < 0 || monthIndex > 11 ) {
            throw new IllegalArgumentException(monthIndex + " is not a valid month index.");
        }
        return new DateFormatSymbols().getMonths()[monthIndex].toString();
    }

How to update an object in a List<> in C#

var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";

How to write multiple line string using Bash with variables?

The syntax (<<<) and the command used (echo) is wrong.

Correct would be:

#!/bin/bash

kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

cat /etc/myconfig.conf

This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash.

"Could not find a valid gem in any repository" (rubygame and others)

Make sure you type the command from the "App" Directory

Could not reserve enough space for object heap

Error :

For the error, "error occurred during initialization of vm could not reserve enough space for object heap jboss"

Root Cause :

  • Improper/insufficient memory allocation to our JVM as mentioned below.

  • e.g. JAVA_OPTS="-Xms1303m -Xmx1303m -XX:MaxPermSize=256m" in jboss-eap-6.2\bin\standalone.conf or "JAVA_OPTS=-Xms1G -Xmx1G -XX:MaxPermSize=256M" in jboss-eap-6.2\bin\standalone.conf.bat which is nothing but JVM memory allocation pool parameters.

Resolution :

  • Increase the heap size. To increase the heap size,
  • goto -> jboss-eap-6.2\bin\standalone.conf.bat or jboss-eap-6.2\bin\standalone.conf
  • change ->JAVA_OPTS="-Xms256m -Xmx512m -XX:MaxPermSize=256m" where -Xms is Minimum heap size and -Xmx is Maximum heap size.
  • Usually its not recommanded to have same size for min and max.

  • If you are running your application from eclipse,

  • Double click on the server
  • select 'open launch configuration' you will be redirected to the window 'Edit launch configuration properties'.
  • In this windown goto the tab '(x)=Arguments'.
  • In VM Arguments, define your heap size as mentioned below
  • "-Dprogram.name=JBossTools: JBoss EAP 6.1+ Runtime Server" -server -Xms256m -Xmx512m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true

Append integer to beginning of list in Python

Alternative:

>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

[NOTE]:

collections.deque is faster than Python pure list in a loop Relevant-Post.

Same Navigation Drawer in different Activities

I do it in Kotlin like this:

open class BaseAppCompatActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

protected lateinit var drawerLayout: DrawerLayout
protected lateinit var navigationView: NavigationView
@Inject
lateinit var loginService: LoginService

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.d("BaseAppCompatActivity", "onCreate()")
    App.getComponent().inject(this)
    drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout

    val toolbar = findViewById(R.id.toolbar) as Toolbar
    setSupportActionBar(toolbar)

    navigationView = findViewById(R.id.nav_view) as NavigationView
    navigationView.setNavigationItemSelectedListener(this)

    val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)

    drawerLayout.addDrawerListener(toggle)
    toggle.syncState()
    toggle.isDrawerIndicatorEnabled = true

    val navigationViewHeaderView = navigationView.getHeaderView(0)
    navigationViewHeaderView.login_txt.text = SharedKey.username
}
private inline fun <reified T: Activity> launch():Boolean{
    if(this is T) return closeDrawer()
    val intent = Intent(applicationContext, T::class.java)
    startActivity(intent)
    finish()
    return true
}

private fun closeDrawer(): Boolean {
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
    val id = item.itemId

    when (id) {
        R.id.action_tasks -> {
            return launch<TasksActivity>()
        }
        R.id.action_contacts -> {
            return launch<ContactActivity>()
        }
        R.id.action_logout -> {
            createExitDialog(loginService, this)
        }
    }
    return false
}
}

Activities for drawer must inherit this BaseAppCompatActivity, call super.onCreate after content is set (actually, can be moved to some init method) and have corresponding elements for ids in their layout

how to add or embed CKEditor in php page

no need to require the ckeditor.php, because CKEditor will not processed by PHP...

you need just following the _samples directory and see what they do.

just need to include ckeditor.js by html tag, and do some configuration in javascript.

How to get all of the immediate subdirectories in Python

import glob
import os

def child_dirs(path):
     cd = os.getcwd()        # save the current working directory
     os.chdir(path)          # change directory 
     dirs = glob.glob("*/")  # get all the subdirectories
     os.chdir(cd)            # change directory to the script original location
     return dirs

The child_dirs function takes a path a directory and returns a list of the immediate subdirectories in it.

dir
 |
  -- dir_1
  -- dir_2

child_dirs('dir') -> ['dir_1', 'dir_2']

Adding a column to a data.frame

If I understand the question correctly, you want to detect when the h_no doesn't increase and then increment the class. (I'm going to walk through how I solved this problem, there is a self-contained function at the end.)

Working

We only care about the h_no column for the moment, so we can extract that from the data frame:

> h_no <- data$h_no

We want to detect when h_no doesn't go up, which we can do by working out when the difference between successive elements is either negative or zero. R provides the diff function which gives us the vector of differences:

> d.h_no <- diff(h_no)
> d.h_no
 [1]  1  1  1 -3  1  1  1  1  1  1 -6  1  1  1

Once we have that, it is a simple matter to find the ones that are non-positive:

> nonpos <- d.h_no <= 0
> nonpos
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[13] FALSE FALSE

In R, TRUE and FALSE are basically the same as 1 and 0, so if we get the cumulative sum of nonpos, it will increase by 1 in (almost) the appropriate spots. The cumsum function (which is basically the opposite of diff) can do this.

> cumsum(nonpos)
 [1] 0 0 0 1 1 1 1 1 1 1 2 2 2 2

But, there are two problems: the numbers are one too small; and, we are missing the first element (there should be four in the first class).

The first problem is simply solved: 1+cumsum(nonpos). And the second just requires adding a 1 to the front of the vector, since the first element is always in class 1:

 > classes <- c(1, 1 + cumsum(nonpos))
 > classes
  [1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3

Now, we can attach it back onto our data frame with cbind (by using the class= syntax, we can give the column the class heading):

 > data_w_classes <- cbind(data, class=classes)

And data_w_classes now contains the result.

Final result

We can compress the lines together and wrap it all up into a function to make it easier to use:

classify <- function(data) {
   cbind(data, class=c(1, 1 + cumsum(diff(data$h_no) <= 0)))
}

Or, since it makes sense for the class to be a factor:

classify <- function(data) {
   cbind(data, class=factor(c(1, 1 + cumsum(diff(data$h_no) <= 0))))
}

You use either function like:

> classified <- classify(data) # doesn't overwrite data
> data <- classify(data) # data now has the "class" column

(This method of solving this problem is good because it avoids explicit iteration, which is generally recommend for R, and avoids generating lots of intermediate vectors and list etc. And also it's kinda neat how it can be written on one line :) )

How do I correctly clone a JavaScript object?

The problem with copying an object that, eventually, may point at itself, can be solved with a simple check. Add this check, every time there is a copy action. It may be slow, but it should work.

I use a toType() function to return the object type, explicitly. I also have my own copyObj() function, which is rather similar in logic, which answers all three Object(), Array(), and Date() cases.

I run it in NodeJS.

NOT TESTED, YET.

// Returns true, if one of the parent's children is the target.
// This is useful, for avoiding copyObj() through an infinite loop!
function isChild(target, parent) {
  if (toType(parent) == '[object Object]') {
    for (var name in parent) {
      var curProperty = parent[name];

      // Direct child.
      if (curProperty = target) return true;

      // Check if target is a child of this property, and so on, recursively.
      if (toType(curProperty) == '[object Object]' || toType(curProperty) == '[object Array]') {
        if (isChild(target, curProperty)) return true;
      }
    }
  } else if (toType(parent) == '[object Array]') {
    for (var i=0; i < parent.length; i++) {
      var curItem = parent[i];

      // Direct child.
      if (curItem = target) return true;

      // Check if target is a child of this property, and so on, recursively.
      if (toType(curItem) == '[object Object]' || toType(curItem) == '[object Array]') {
        if (isChild(target, curItem)) return true;
      }
    }
  }

  return false;     // Not the target.
}

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

You can use codecs.

import codecs
with open("test.txt",'r') as filehandle:
    content = filehandle.read()
if content[:3] == codecs.BOM_UTF8:
    content = content[3:]
print content.decode("utf-8")

Return empty cell from formula in Excel

What I used was a small hack. I used T(1), which returned an empty cell. T is a function in excel that returns its argument if its a string and an empty cell otherwise. So, what you can do is:

=IF(condition,T(1),value)

How can I merge two MySQL tables?

Not as complicated as it sounds.... Just leave the duplicate primary key out of your query.... this works for me !

INSERT INTO
  Content(
    `status`,
    content_category,
    content_type,
    content_id,
    user_id,
    title,
    description,
    content_file,
    content_url,
    tags,
    create_date,
    edit_date,
    runs
  )
SELECT `status`,
  content_category,
  content_type,
  content_id,
  user_id,
  title,
  description,
  content_file,
  content_url,
  tags,
  create_date,
  edit_date,
  runs
FROM
  Content_Images

How do I get the current date and time in PHP?

You can use this format also:

$date = date("d-m-Y");

Or

$date = date("Y-m-d H:i:s");

Swift how to sort array of custom objects by property value

In Swift 3.0

images.sort(by: { (first: imageFile, second: imageFile) -> Bool in
    first. fileID < second. fileID
})

Python: BeautifulSoup - get an attribute value based on the name attribute

6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:

<span property="addressLocality">Ayr</span>

I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.

How I managed to do it eventually:

>>> from bs4 import BeautifulSoup as bs

>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}

As it's a dict, you can then also use keys and 'values'

>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']

Hopefully it helps someone else!

Counting the number of option tags in a select tag in jQuery

In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

Get max and min value from array in JavaScript

use this and it works on both the static arrays and dynamically generated arrays.

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

I had the issue when I use trying to find max value from code below

$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
            newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
        });

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
            newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
        }

        getMaxValue = Math.max.apply(Math, array);

I was getting 'NAN' when I use

    var max_value = Math.max(12, 21, 23, 2323, 23);

with my code

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

The simplest way I can think of for creating list/array within range

Array.from(Array(max-min+1), (_, index) => index+min)

How to simulate POST request?

Dont forget to add user agent since some server will block request if there's no server agent..(you would get Forbidden resource response) example :

curl -X POST -A 'Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' -d "field=acaca&name=afadxx" https://example.com

Test for multiple cases in a switch, like an OR (||)

You have to switch it!

switch (true) {
    case ( (pageid === "listing-page") || (pageid === ("home-page") ):
        alert("hello");
        break;
    case (pageid === "details-page"):
        alert("goodbye");
        break;
}

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

Split array into two parts without for loop in java

copyOfRange

This does what you want without you having to create a new array as it returns a new array.

int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);

What do the crossed style properties in Google Chrome devtools mean?

On a side note. If you are using @media queries (such as @media screen (max-width:500px)) pay particular attention to applying @media query AFTER you are done with normal styles. Because @media query will be crossed out (even though it is more specific) if followed by css that manipulates the same elements. Example:

@media (max-width:750px){
#buy-box {width: 300px;}
}

#buy-box{
width:500px;
}

** width will be 500px and 300px will be crossed out in Developer Tools. **

#buy-box{
width:500px;
}

@media (max-width:750px){
#buy-box {width: 300px;}
}

** width will be 300px and 500px will be crossed out **

Case insensitive 'Contains(string)'

Just to build on the answer here, you can create a string extension method to make this a little more user-friendly:

    public static bool ContainsIgnoreCase(this string paragraph, string word)
    {
        return CultureInfo.CurrentCulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
    }

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Still an issue.

Using parameters like "..css?something=random-value" changes nothing in my customer-support experience. Only name changes works.

Another take on the file renaming. I use URL Rewrite in IIS. Sometimes Helicon's Isapi Rewrite.

Add new rule.

+ Name: lame-chrome-fix.
+ Pattern: styles/(\w+)_(\d+)
+ Rewrite URL: /{R:1}.css

Note: I reserve the use of undercase to separate the name from the random number. Could be anything else.

Example:

<link href="/styles/template_<% 
Response.Write( System.DateTime.UtcNow.ToString("ddmmyyhhmmss")); %>" 
type="text/css" />

(No styles folder it's just a name part of the pattern)

Output code as:

<link href="/styles/template_285316115328" 
rel="stylesheet" type="text/css">

Redirect as:

(R:1 = template)

/template.css

Only the explanation is long.

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

How to convert color code into media.brush?

In code, you need to explicitly create a Brush instance:

Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))

Reversing a String with Recursion in Java

public class ReverseString{

private static  String reverse(String text, String reverseStr){
    if(text == null || text.length() == 0){
        return reverseStr;
    }
    return reverse(text.substring(1), text.charAt(0)+reverseStr);
}
public static void main(String [] args){
    System.out.println(reverse("hello", "")); //output is "olleh"
}

}

How can I stop python.exe from closing immediately after I get an output?

In windows, if Python is installed into the default directory (For me it is):

cd C:\Python27

You then proceed to type

"python.exe "[FULLPATH]\[name].py" 

to run your Python script in Command Prompt

New warnings in iOS 9: "all bitcode will be dropped"

To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9

Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/

How can I see the raw SQL queries Django is running?

Though you can do it with with the code supplied, I find that using the debug toolbar app is a great tool to show queries. You can download it from github here.

This gives you the option to show all the queries ran on a given page along with the time to query took. It also sums up the number of queries on a page along with total time for a quick review. This is a great tool, when you want to look at what the Django ORM does behind the scenes. It also have a lot of other nice features, that you can use if you like.

Why does 'git commit' not save my changes?

You should do:

git commit . -m "save arezzo files"

How to present UIActionSheet iOS Swift?

Code for adding alerts to actionsheet in swift4

   *That means when we click actionsheet values(like edit/ delete..so on) it shows 
   an alert option that is set with Yes or No option*


   class ViewController: UIViewController
   {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func action_sheet1(_ sender: Any) {




    let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)

    action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Approve button")



        let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


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

        }))




    action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Edit button")

        let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


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

        }))




    action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
        print("User click Delete button")



        let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


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

        }))





    action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
         print("User click cancel button")


        let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


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

        }))



        self.present(action_sheet1, animated: true, completion: {
        print("completion block")
    })
}


}

jQuery click function doesn't work after ajax call?

The problem is that .click only works for elements already on the page. You have to use something like on if you are wiring up future elements

$("#LangTable").on("click",".deletelanguage", function(){
  alert("success");
});

Deleting DataFrame row in Pandas based on column value

If you want to delete rows based on multiple values of the column, you could use:

df[(df.line_race != 0) & (df.line_race != 10)]

To drop all rows with values 0 and 10 for line_race.

Creating a div element in jQuery

I hope that helps code. :) (I use)

function generateParameterForm(fieldName, promptText, valueType) {
    //<div class="form-group">
    //<label for="yyy" class="control-label">XXX</label>
    //<input type="text" class="form-control" id="yyy" name="yyy"/>
    //</div>

    // Add new div tag
    var form = $("<div/>").addClass("form-group");

    // Add label for prompt text
    var label = $("<label/>").attr("for", fieldName).addClass("control-label").text(promptText);

    // Add text field
    var input = $("<input/>").attr("type", "text").addClass("form-control").addClass(valueType).attr("id", fieldName).attr("name", fieldName);

    // lbl and inp => form
    $(form).append(label).append(input);

    return $(form);
}

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

The same may be achieved with the stringi package:

library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap"   "b" 

Get parent directory of running script

Fugly, but this will do it:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

Getting all types in a namespace via reflection

Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

The simplest workaround I found is to backup the table and view the script. To do this

  1. Right click your database and choose Tasks > Generate Scripts...
  2. "Introduction" page click Next
  3. "Choose Objects" page
    1. Choose the Select specific database objects and select your table.
    2. Click Next
  4. "Set Scripting Options" page
    1. Set the output type to Save scripts to a specific location
    2. Select Save to file and fill in the related options
    3. Click the Advanced button
    4. Set General > Types of data to script to Data only or Schema and Data and click ok
    5. Click Next
  5. "Summary Page" click next
  6. Your sql script should be generated based on the options you set in 4.2. Open this file up and view your data.

Convert `List<string>` to comma-separated string

static void Main(string[] args)
{
   List<string> listStrings = new List<string>(){ "C#", "Asp.Net", "SQL Server", "PHP", "Angular"};
   string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
   Console.Write(CommaSeparateString);
   Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
{
   return String.Join(",", listStrings);  
}

Convert a list of string to comma separated string C#.

int object is not iterable?

One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()

num = int(input('Enter a number: ')
nums_sum = 0

while num:
    num, reminder = divmod(num, 10)
    nums_sum += reminder

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You could also disable the cascade delete convention in global scope of your application by doing this:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

Error: fix the version conflict (google-services plugin)

All google services should be of same version, try matching every versions.

Correct one is :

  implementation 'com.google.firebase:firebase-auth:11.6.0'
  implementation 'com.google.firebase:firebase-database:11.6.0'

Incorrect Config is :

 implementation 'com.google.firebase:firebase-auth:11.6.0'
 implementation 'com.google.firebase:firebase-database:11.8.0'

How to store Node.js deployment settings/configuration files?

Here is a neat approach inspired by this article. It does not require any additional packages except the ubiquitous lodash package. Moreover, it lets you manage nested defaults with environment-specific overwrites.

First, create a config folder in the package root path that looks like this

package
  |_config
      |_ index.js
      |_ defaults.json
      |_ development.json
      |_ test.json
      |_ production.json

here is the index.js file

const _ = require("lodash");
const defaults = require("./defaults.json");
const envConf = require("./" + (process.env.NODE_ENV || "development") + ".json" );
module.exports = _.defaultsDeep(envConf, defaults);

Now let's assume we have a defaults.json like so

{
  "confKey1": "value1",
  "confKey2": {
    "confKey3": "value3",
    "confKey4": "value4"
  }
}

and development.json like so

{
  "confKey2": {
    "confKey3": "value10",
  }
}

if you do config = require('./config') here is what you will get

{
  "confKey1": "value1",
  "confKey2": {
    "confKey3": "value10",
    "confKey4": "value4"
  }
}

Notice that you get all the default values except for those defined in environment-specific files. So you can manage a config hierarchy. Using defaultsDeep makes sure that you can even have nested defaults.

How to start Spyder IDE on Windows

If you are using Anaconda execute the following commands and your life will be saved!

conda update qt pyqt
conda update spyder

How to assign name for a screen?

To create a new screen with the name foo, use

screen -S foo

Then to reattach it, run

screen -r foo  # or use -x, as in
screen -x foo  # for "Multi display mode" (see the man page)

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

Dropping connected users in Oracle database

I had the same problem, Oracle config in default affects letter register. In exact my Scheme_Name was written all Capital letters. You can see your Scheme_Name on "Other Users" tab, if you are using Oracle S

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

TempData keep() vs peek()

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

With Peek you get the value without marking it for deletion with a single call, see msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

You have 2 good questions about how TempData works here and here

Hope it helps!

How can I add some small utility functions to my AngularJS application?

EDIT 7/1/15:

I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.

Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:

https://docs.angularjs.org/guide/module#module-loading-dependencies

AngularJS dependency injection of value inside of module.config

I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.

EDIT 2/3/14:

After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).

That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.

What I would do now is:

app.js:

var MyNamespace = MyNamespace || {};

 MyNamespace.helpers = {
   isNotString: function(str) {
     return (typeof str !== "string");
   }
 };

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', function($scope) {
    $scope.helpers = MyNamespace.helpers;
  });

Then in your partial you can use:

<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>

Old answer below:

It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.

If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:

$scope.doSomething = ServiceName.functionName;

Then in your partial you can use:

<button data-ng-click="doSomething()">Do Something</button>

Here's a way you might keep this all organized and free from too much hassle:

Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:

app.js:

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);  

services.js:

 /* Generic Services */                                                                                                                                                                                                    
 angular.module('app.services', [])                                                                                                                                                                        
   .factory("genericServices", function() {                                                                                                                                                   
     return {                                                                                                                                                                                                              
       doSomething: function() {   
         //Do something here
       },
       doSomethingElse: function() {
         //Do something else here
       }
    });

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
    $scope.genericServices = genericServices;
  });

Then in your partial you can use:

<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>

That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.

Compare two DataFrames and output their differences side-by-side

This answer simply extends @Andy Hayden's, making it resilient to when numeric fields are nan, and wrapping it up into a function.

import pandas as pd
import numpy as np


def diff_pd(df1, df2):
    """Identify differences between two pandas DataFrames"""
    assert (df1.columns == df2.columns).all(), \
        "DataFrame column names are different"
    if any(df1.dtypes != df2.dtypes):
        "Data Types are different, trying to convert"
        df2 = df2.astype(df1.dtypes)
    if df1.equals(df2):
        return None
    else:
        # need to account for np.nan != np.nan returning True
        diff_mask = (df1 != df2) & ~(df1.isnull() & df2.isnull())
        ne_stacked = diff_mask.stack()
        changed = ne_stacked[ne_stacked]
        changed.index.names = ['id', 'col']
        difference_locations = np.where(diff_mask)
        changed_from = df1.values[difference_locations]
        changed_to = df2.values[difference_locations]
        return pd.DataFrame({'from': changed_from, 'to': changed_to},
                            index=changed.index)

So with your data (slightly edited to have a NaN in the score column):

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

DF1 = StringIO("""id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 "He was late to class"
112  Nick   1.11                     False                "Graduated"
113  Zoe    NaN                     True                  " "
""")
DF2 = StringIO("""id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 "He was late to class"
112  Nick   1.21                     False                "Graduated"
113  Zoe    NaN                     False                "On vacation" """)
df1 = pd.read_table(DF1, sep='\s+', index_col='id')
df2 = pd.read_table(DF2, sep='\s+', index_col='id')
diff_pd(df1, df2)

Output:

                from           to
id  col                          
112 score       1.11         1.21
113 isEnrolled  True        False
    Comment           On vacation

Convert Python program to C/C++ code?

Just came across this new tool in hacker news.

From their page - "Nuitka is a good replacement for the Python interpreter and compiles every construct that CPython 2.6, 2.7, 3.2 and 3.3 offer. It translates the Python into a C++ program that then uses "libpython" to execute in the same way as CPython does, in a very compatible way."

Can I add a custom attribute to an HTML tag?

You can amend your !DOCTYPE declaration (i.e. DTD) to allow it, so that the [XML] document will still be valid:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

#IMPLIED means it is an optional attribute, or you could use #REQUIRED, etc.

More information is in DTD - Attributes.

Difference between "on-heap" and "off-heap"

Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.

Then of course the next tier lower is hard-drive space itself.

I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

Read text file into string array (and write)

You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

package main

import (
    "os"
    "bufio"
    "bytes"
    "fmt"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == os.EOF {
        err = nil
    }
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
}

Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr