Programs & Examples On #Expand

Expand and collapse with angular js

The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content.

You can pass $event with ng-click (ng-dblclick, and ng- mouse events), then you can determine which element caused the event:

<a ng-click="doSomething($event)">do something</a>

Controller:

$scope.doSomething = function(ev) {
    var element = ev.srcElement ? ev.srcElement : ev.target;
    console.log(element, angular.element(element))
    ...
}

See also http://angular-ui.github.com/bootstrap/#/accordion

RecyclerView expand/collapse items

Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1:position;
        TransitionManager.beginDelayedTransition(recyclerView);
        notifyDataSetChanged();
    }
});
  • Where details is my view that will be displayed on touch (call details in your case. Default Visibility.GONE).
  • mExpandedPosition is an int variable initialized to -1

And for the cool effects that you wanted, use these as your list_item attributes:

android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"

where comment_background is:

<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">

<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>

and comment_selection is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true">
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="@dimen/z_card"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>

<item>
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="0dp"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>

Show/Hide Table Rows using Javascript classes

AngularJS directives ng-show, ng-hide allows to display and hide a row:

   <tr ng-show="rw.isExpanded">
   </tr>

A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.

Apache POI Excel - how to configure columns to be expanded?

Its very simple, use this one line code dataSheet.autoSizeColumn(0)

or give the number of column in bracket dataSheet.autoSizeColumn(cell number )

/exclude in xcopy just for a file type

Change *.cs to .cs in the excludefileslist.txt

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

Image style height and width not taken in outlook mails

Can confirm that leaving px out from width and height did the trick for Outlook

<img src="image.png" style="height: 55px;width:139px;border:0;" height="55" width="139">

How to concat string + i?

according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)

What does @media screen and (max-width: 1024px) mean in CSS?

It means if the screen size is 1024 then only apply below CSS rules.

VMWare Player vs VMWare Workstation

re: VMware Workstation support for physical disks vs virtual disks.

I run Player with the VM Disk files on their own dedicated fast hard drive, independent from the OS hard drive. This allows both the OS and Player to simultaneously independently read/write to their own drives, the performance difference is noticeable, and a second WD Black or Raptor or SSD is cheap. Placing the VM disk file on a second drive also works with Microsoft Virtual PC.

C++ class forward declaration

Use forward declaration when possible.

Suppose you want to define a new class B that uses objects of class A.

  1. B only uses references or pointers to A. Use forward declaration then you don't need to include <A.h>. This will in turn speed a little bit the compilation.

    class A ;
    
    class B 
    {
      private:
        A* fPtrA ;
      public:
        void mymethod(const& A) const ;
    } ;
    
  2. B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include <A.h>

    #include <A.h>
    
    class B : public A 
    {
    };
    
    class C 
    {
      private:
        A fA ;
      public:
        void mymethod(A par) ;   
    }
    

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

How to resolve ORA 00936 Missing Expression Error?

update INC.PROV_CSP_DEMO_ADDR_TEMP pd 
set pd.practice_name = (
    select PRSQ_COMMENT FROM INC.CMC_PRSQ_SITE_QA PRSQ
    WHERE PRSQ.PRSQ_MCTR_ITEM = 'PRNM' 
    AND PRSQ.PRAD_ID = pd.provider_id
    AND PRSQ.PRAD_TYPE = pd.prov_addr_type
    AND ROWNUM = 1
)

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

It's worth pointing out that if you have multiple Gmail accounts, you may want to use the URL approach because you can customize which account to compose from.

e.g.

https://mail.google.com/mail/u/0/#inbox?compose=new   
https://mail.google.com/mail/u/1/#inbox?compose=new

Or if you know the email address you are sending from, replace the numeric index with the email address:

https://mail.google.com/mail/u/[email protected]/#inbox?compose=new

Uncaught TypeError: undefined is not a function while using jQuery UI

This is about the HTML parse mechanism.

The HTML parser will parse the HTML content from top to bottom. In your script logic,

jQuery('#datetimepicker')

will return an empty instance because the element has not loaded yet.

You can use

$(function(){ your code here });

or

$(document).ready(function(){ your code here });

to parse HTML element firstly, and then do your own script logics.

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How to get a microtime in Node.js?

now('milli'); //  120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; //  120335360904333

Known that now is :

const now = (unit) => {
  
  const hrTime = process.hrtime();
  
  switch (unit) {
    
    case 'milli':
      return hrTime[0] * 1000 + hrTime[1] / 1000000;
      
    case 'micro':
      return hrTime[0] * 1000000 + hrTime[1] / 1000;
      
    case 'nano':
    default:
      return hrTime[0] * 1000000000 + hrTime[1];
  }
  
};

Ruby on Rails: how to render a string as HTML?

@str = "<span class=\"classname\">hello</span>" If in my view I do

<%raw @str %> The HTML source code is <span class=\"classname\">hello</span> where what I really want is <span class="classname">hello</span> (without the backslashes that were escaping the double >quotes). What's the best way to "unescape" those double quotes?

Solution: use double quotes inside of single quotes (or single inside of double) to avoid escaping with a backslash.

@str = '<span class="classname">hello</span>'
<%raw @str %>

Redraw datatables after using ajax to refresh the table content?

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

How to find and restore a deleted file in a Git repository

You could always git revert your commit which deleted the file. (This assumes that the deletion was the only change in the commit.)

> git log
commit 2994bda49cd97ce49099953fc3f76f7d3c35d1d3
Author: Dave <[email protected]>
Date:   Thu May 9 11:11:06 2019 -0700

    deleted readme.md

And if you've continued work, and realized later that you didn't want to commit that deletion commit, you could revert it using:

> git revert 2994bd

Now git log shows:

> git log
Author: Dave <[email protected]>
Date:   Thu May 9 11:17:41 2019 -0700

    Revert "deleted readme"

    This reverts commit 2994bda49cd97ce49099953fc3f76f7d3c35d1d3.

And readme.md has been restored into the repository.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

Android ImageView Animation

I have found out, that if you use the .getWidth/2 etc... that it won't work you need to get the number of pixels the image is and divide it by 2 yourself and then just type in the number for the last 2 arguments.

so say your image was a 120 pixel by 120 pixel square, ur x and y would equal 60 pixels. so in your code, you would right:

RotateAnimation anim = new RotateAnimation(0f, 350f, 60f, 60f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

and now your image will pivot round its center.

How can I view an old version of a file with Git?

If you like GUIs, you can use gitk:

  1. start gitk with:

    gitk /path/to/file
    
  2. Choose the revision in the top part of the screen, e.g. by description or date. By default, the lower part of the screen shows the diff for that revision, (corresponding to the "patch" radio button).

  3. To see the file for the selected revision:

    • Click on the "tree" radio button. This will show the root of the file tree at that revision.
    • Drill down to your file.

Using local makefile for CLion instead of CMake

Newest version has better support literally for any generated Makefiles, through the compiledb

Three steps:

  1. install compiledb

    pip install compiledb
    
  2. run a dry make

    compiledb -n make 
    

    (do the autogen, configure if needed)

  3. there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3

Orignal post: Working with Makefiles in CLion using Compilation DB

android get real path by Uri.getPath()

Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI() and ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path.

Laravel use same form for create and edit

For example, your controller, retrive data and put the view

class ClassExampleController extends Controller
{

    public function index()
    {   

        $test = Test::first(1);

        return view('view-form',[
            'field' => $test,
        ]);
    }
}

Add default value in the same form, create and edit, is very simple

<!-- view-form file -->
<form action="{{ 
    isset($field) ? 
    @route('field.updated', $field->id) : 
    @route('field.store')
}}">
    <!-- Input case -->
    <input name="name_input" class="form-control" 
    value="{{ isset($field->name) ? $field->name : '' }}">
</form>

And, you remember add csrf_field, in case a POST method requesting. Therefore, repeat input, and select element, compare each option

<select name="x_select">
@foreach($field as $subfield)

    @if ($subfield == $field->name)
        <option val="i" checked>
    @else
        <option val="i" >
    @endif

@endforeach
</select>

The server principal is not able to access the database under the current security context in SQL Server MS 2012

On SQL 2017 - Database A has synonyms to Database B. User can connect to database A and has exec rights to an sp (on A) that refers to the synonyms that point to B. User was set up with connect access B. Only when granting CONNECT to the public group to database B did the sp on A work. I don't recall this working this way on 2012 as granting connect to the user only seemed to work.

Copy or rsync command

if you are using cp doesn't save existing files when copying folders of the same name. Lets say you have this folders:

/myFolder
  someTextFile.txt

/someOtherFolder
  /myFolder
    wellHelloThere.txt

Then you copy one over the other:

cp /someOtherFolder/myFolder /myFolder

result:

/myFolder
  wellHelloThere.txt

This is at least what happens on macOS and I wanted to preserve the diff files so I used rsync.

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

Assign static IP to Docker container

Easy with Docker version 1.10.1, build 9e83765.

First you need to create your own docker network (mynet123)

docker network create --subnet=172.18.0.0/16 mynet123

then, simply run the image (I'll take ubuntu as example)

docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash

then in ubuntu shell

ip addr

Additionally you could use

  • --hostname to specify a hostname
  • --add-host to add more entries to /etc/hosts

Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

If you are using the Chrome Driver you can set the capabilities

    var capabilities = new DesiredCapabilities();

    var switches = new List<string>
                       {
                           "--start-maximized"
                       };

    capabilities.SetCapability("chrome.switches", switches);

    new ChromeDriver(chromedriver_path, capabilities);

How to get page content using cURL?

this is how:

   /**
     * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
     * array containing the HTTP server response header fields and content.
     */
    function get_web_page( $url )
    {
        $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

        $options = array(

            CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
            CURLOPT_POST           =>false,        //set to GET
            CURLOPT_USERAGENT      => $user_agent, //set user agent
            CURLOPT_COOKIEFILE     =>"cookie.txt", //set cookie file
            CURLOPT_COOKIEJAR      =>"cookie.txt", //set cookie jar
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }

Example

//Read a web page and check for errors:

$result = get_web_page( $url );

if ( $result['errno'] != 0 )
    ... error: bad url, timeout, redirect loop ...

if ( $result['http_code'] != 200 )
    ... error: no page, no permissions, no service ...

$page = $result['content'];

Why do we use web.xml?

Servlet to be accessible from a browser, then must tell the servlet container what servlets to deploy, and what URL's to map the servlets to. This is done in the web.xml file of your Java web application.

use web.xml in servlet

<servlet>
    <description></description>
    <display-name>servlet class name</display-name>
    <servlet-name>servlet class name</servlet-name>
    <servlet-class>servlet package name/servlet class name</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servlet class name</servlet-name>
    <url-pattern>/servlet class name</url-pattern>
</servlet-mapping>

manly use web.xml for servlet mapping.

How to set JAVA_HOME for multiple Tomcat instances?

One thing that you could do would be to modify the catalina.sh (Unix based) or the catalina.bat (windows based).

Within each of the scripts you can set certain variables which only processes created under the shell will inherit. So for catalina.sh, use the following line:

export JAVA_HOME="intented java home"

And for windows use

set JAVA_HOME="intented java home"

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

Best way to structure a tkinter application?

I advocate an object oriented approach. This is the template that I start out with:

# Use Tkinter for python 2, tkinter for python 3
import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        <create the rest of your GUI here>

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

The important things to notice are:

  • I don't use a wildcard import. I import the package as "tk", which requires that I prefix all commands with tk.. This prevents global namespace pollution, plus it makes the code completely obvious when you are using Tkinter classes, ttk classes, or some of your own.

  • The main application is a class. This gives you a private namespace for all of your callbacks and private functions, and just generally makes it easier to organize your code. In a procedural style you have to code top-down, defining functions before using them, etc. With this method you don't since you don't actually create the main window until the very last step. I prefer inheriting from tk.Frame just because I typically start by creating a frame, but it is by no means necessary.

If your app has additional toplevel windows, I recommend making each of those a separate class, inheriting from tk.Toplevel. This gives you all of the same advantages mentioned above -- the windows are atomic, they have their own namespace, and the code is well organized. Plus, it makes it easy to put each into its own module once the code starts to get large.

Finally, you might want to consider using classes for every major portion of your interface. For example, if you're creating an app with a toolbar, a navigation pane, a statusbar, and a main area, you could make each one of those classes. This makes your main code quite small and easy to understand:

class Navbar(tk.Frame): ...
class Toolbar(tk.Frame): ...
class Statusbar(tk.Frame): ...
class Main(tk.Frame): ...

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.statusbar = Statusbar(self, ...)
        self.toolbar = Toolbar(self, ...)
        self.navbar = Navbar(self, ...)
        self.main = Main(self, ...)

        self.statusbar.pack(side="bottom", fill="x")
        self.toolbar.pack(side="top", fill="x")
        self.navbar.pack(side="left", fill="y")
        self.main.pack(side="right", fill="both", expand=True)

Since all of those instances share a common parent, the parent effectively becomes the "controller" part of a model-view-controller architecture. So, for example, the main window could place something on the statusbar by calling self.parent.statusbar.set("Hello, world"). This allows you to define a simple interface between the components, helping to keep coupling to a minimun.

Convert AM/PM time to 24 hours format?

int hour = your hour value;
int min = your minute value;
String ampm = your am/pm value;

hour = ampm == "AM" ? hour : (hour % 12) + 12; //convert 12-hour time to 24-hour

var dateTime = new DateTime(0,0,0, hour, min, 0);
var timeString = dateTime.ToString("HH:mm");

WPF Button with Image

This should do the job, no?

<Button Content="Test">
    <Button.Background>
        <ImageBrush ImageSource="folder/file.PNG"/>
    </Button.Background>
</Button>

MySQL vs MongoDB 1000 reads

man,,, the answer is that you're basically testing PHP and not a database.

don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.

   foreach ($cursor as $obj)
    {
        //echo $obj["thread_title"] . "<br><Br>";
    }

while the other chunk is spend yacking up a bunch of rand numbers.

function get_15_random_numbers()
{
    $numbers = array();
    for($i=1;$i<=15;$i++)
    {
        $numbers[] = mt_rand(1, 20000000) ;

    }
    return $numbers;
}

then theres a major difference b/w implode and in.

and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.

$m = new Mongo();

vs

$db = new AQLDatabase();

so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.

urghhh.

Using Python String Formatting with Lists

Here is a one liner. A little improvised answer using format with print() to iterate a list.

How about this (python 3.x):

sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))

Read the docs here on using format().

Why does the C preprocessor interpret the word "linux" as the constant "1"?

In the Old Days (pre-ANSI), predefining symbols such as unix and vax was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&R), and C code of any complexity was typically a complex maze of #ifdefs to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like unix and assumed that programmers would simply avoid using those names for their own purposes.

The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.

As a result, any compiler that predefines unix or linux is non-conforming, since it will fail to compile perfectly legal code that uses something like int linux = 5;.

As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:

gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
gcc -std=c99 -pedantic
gcc -std=c11 -pedantic

See the gcc manual for more details.

gcc will be phasing out these definitions in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether __linux__ is defined (assuming you're using gcc or a compiler that's compatible with it). See the GNU C preprocessor manual for more information.

A largely irrelevant aside: the "Best One Liner" winner of the 1987 International Obfuscated C Code Contest, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined unix macro:

main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}

It prints "unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.

Getting list of pixel values from PIL

If you have numpy installed you can try:

data = numpy.asarray(im)

(I say "try" here, because it's unclear why getdata() isn't working for you, and I don't know whether asarray uses getdata, but it's worth a test.)

BeautifulSoup Grab Visible Webpage Text

Try this:

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request


def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return u" ".join(t.strip() for t in visible_texts)

html = urllib.request.urlopen('http://www.nytimes.com/2009/12/21/us/21storm.html').read()
print(text_from_html(html))

Using DateTime in a SqlParameter for Stored Procedure, format error

If you use Microsoft.ApplicationBlocks.Data it'll make calling your sprocs a single line

SqlHelper.ExecuteNonQuery(ConnectionString, "SprocName", DOB)

Oh and I think casperOne is correct...if you want to ensure the correct datetime over multiple timezones then simply convert the value to UTC before you send the value to SQL Server

SqlHelper.ExecuteNonQuery(ConnectionString, "SprocName", DOB.ToUniversalTime())

Make a VStack fill the width of the screen in SwiftUI

You can do it by using GeometryReader

GeometryReader

Code:

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
               Text("Turtle Rock").frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading).background(Color.red)
            }
        }
    }
}

Your output like:

enter image description here

Generating Fibonacci Sequence

Fibonacci (one-liner)

function fibonacci(n) {
  return (n <= 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

Fibonacci (recursive)

_x000D_
_x000D_
function fibonacci(number) {_x000D_
  // n <= 1_x000D_
  if (number <= 0) {_x000D_
    return n;_x000D_
  } else {_x000D_
    // f(n) = f(n-1) + f(n-2)_x000D_
    return fibonacci(number - 1) + fibonacci(number - 2);_x000D_
  }_x000D_
};_x000D_
_x000D_
console.log('f(14) = ' + fibonacci(14)); // 377
_x000D_
_x000D_
_x000D_

Fibonacci (iterative)

_x000D_
_x000D_
 function fibonacci(number) {_x000D_
  // n < 2_x000D_
  if (number <= 0) {_x000D_
    return number ;_x000D_
  } else {_x000D_
    var n = 2; // n = 2_x000D_
    var fn_1 = 0; // f(n-2), if n=2_x000D_
    var fn_2 = 1; // f(n-1), if n=2   _x000D_
_x000D_
    // n >= 2_x000D_
    while (n <= number) {_x000D_
      var aa = fn_2; // f(n-1)_x000D_
      var fn = fn_1 + fn_2; // f(n)_x000D_
_x000D_
      // Preparation for next loop_x000D_
      fn_1 = aa;_x000D_
      fn_2 = fn;_x000D_
_x000D_
      n++;_x000D_
    }_x000D_
_x000D_
    return fn_2;_x000D_
  }_x000D_
};_x000D_
_x000D_
console.log('f(14) = ' + fibonacci(14)); // 377
_x000D_
_x000D_
_x000D_

Fibonacci (with Tail Call Optimization)

_x000D_
_x000D_
function fibonacci(number) {_x000D_
  if (number <= 1) {_x000D_
    return number;_x000D_
  }_x000D_
_x000D_
  function recursion(length, originalLength, previous, next) {_x000D_
    if (length === originalLength)_x000D_
      return previous + next;_x000D_
_x000D_
    return recursion(length + 1, originalLength, next, previous + next);_x000D_
  }_x000D_
_x000D_
  return recursion(1, number - 1, 0, 1);_x000D_
}_x000D_
_x000D_
console.log(`f(14) = ${fibonacci(14)}`); // 377
_x000D_
_x000D_
_x000D_

When should I use nil and NULL in Objective-C?

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray. So if you need to represent a "nil", you can use [NSNull null].

Android statusbar icons color

Yes it's possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml

<item name="android:windowLightStatusBar">true</item>

enter image description here

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

import 'rxjs/add/operator/map';

will resolve your problem

I tested it in angular 5.2.0 and rxjs 5.5.2

Arrays.asList() of an array

You are trying to cast int[] to Integer[], this is not possible.

You can use commons-lang's ArrayUtils to convert the ints to Integers before getting the List from the array:

public int getTheNumber(int[] factors) {
    Integer[] integers = ArrayUtils.toObject(factors);
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(integers));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}    

How to disable mouse scroll wheel scaling with Google Maps API

Keep it simple! Original Google maps variable, none of the extra stuff.

 var mapOptions = {
     zoom: 16,
     center: myLatlng,
     scrollwheel: false

}

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

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

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'

Make sure that you have added ojdbc14.jar into your library.

For oracle 11g, usie ojdbc6.jar.

$(this).attr("id") not working

You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();

(function($) {
    $.extend($.fn, {
        showHideOther: function() {
            $.each(this, function() {
                var Id = $(this).attr('id');
                alert(Id);

                ...

                return this;
            });
        }
    });
})(jQuery);

Not that it answers your question... Just food for thought.

Printing out a linked list using toString

As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

How to remove extension from string (only real extension!)

Try to use this one. it will surely remove the file extension.

$filename = "image.jpg";
$e = explode(".", $filename);
foreach($e as $key=>$d)
{
if($d!=end($e)
{

$new_d[]=$d; 
}

 }
 echo implode("-",$new_t);  // result would be just the 'image'

How to force IE10 to render page in IE9 document mode

You should be able to do it using the X-UA meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

However, if you find yourself having to do this, you're probably doing something wrong and should take a look at what you're doing and see if you can do it a different/better way.

Can my enums have friendly names?

One problem with this trick is that description attribute cannot be localized. I do like a technique by Sacha Barber where he creates his own version of Description attribute which would pick up values from the corresponding resource manager.

http://www.codeproject.com/KB/WPF/FriendlyEnums.aspx

Although the article is around a problem that's generally faced by WPF developers when binding to enums, you can jump directly to the part where he creates the LocalizableDescriptionAttribute.

show more/Less text with just HTML and JavaScript

This should resolve your problem:

function toggleSeeMore() {
    if(document.getElementById("textarea").style.display == 'none') {
        document.getElementById("textarea").style.display = 'block';
        document.getElementById("seeMore").innerHTML = 'See less';
    }
    else {
        document.getElementById("textarea").style.display = 'none';
        document.getElementById("seeMore").innerHTML = 'See more';        
    }
}

The complete working example is here: http://jsfiddle.net/akhikhl/zLA5K/

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

This may not be the best way for MVC ( https://stackoverflow.com/a/9461386/5869805 )

Below is how you render a view in Application_Error and write it to http response. You do not need to use redirect. This will prevent a second request to server, so the link in browser's address bar will stay same. This may be good or bad, it depends on what you want.

Global.asax.cs

protected void Application_Error()
{
    var exception = Server.GetLastError();
    // TODO do whatever you want with exception, such as logging, set errorMessage, etc.
    var errorMessage = "SOME FRIENDLY MESSAGE";

    // TODO: UPDATE BELOW FOUR PARAMETERS ACCORDING TO YOUR ERROR HANDLING ACTION
    var errorArea = "AREA";
    var errorController = "CONTROLLER";
    var errorAction = "ACTION";
    var pathToViewFile = $"~/Areas/{errorArea}/Views/{errorController}/{errorAction}.cshtml"; // THIS SHOULD BE THE PATH IN FILESYSTEM RELATIVE TO WHERE YOUR CSPROJ FILE IS!

    var requestControllerName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["controller"]);
    var requestActionName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["action"]);

    var controller = new BaseController(); // REPLACE THIS WITH YOUR BASE CONTROLLER CLASS
    var routeData = new RouteData { DataTokens = { { "area", errorArea } }, Values = { { "controller", errorController }, {"action", errorAction} } };
    var controllerContext = new ControllerContext(new HttpContextWrapper(HttpContext.Current), routeData, controller);
    controller.ControllerContext = controllerContext;

    var sw = new StringWriter();
    var razorView = new RazorView(controller.ControllerContext, pathToViewFile, "", false, null);
    var model = new ViewDataDictionary(new HandleErrorInfo(exception, requestControllerName, requestActionName));
    var viewContext = new ViewContext(controller.ControllerContext, razorView, model, new TempDataDictionary(), sw);
    viewContext.ViewBag.ErrorMessage = errorMessage;
    //TODO: add to ViewBag what you need
    razorView.Render(viewContext, sw);
    HttpContext.Current.Response.Write(sw);
    Server.ClearError();
    HttpContext.Current.Response.End(); // No more processing needed (ex: by default controller/action routing), flush the response out and raise EndRequest event.
}

View

@model HandleErrorInfo
@{
    ViewBag.Title = "Error";
    // TODO: SET YOUR LAYOUT
}
<div class="">
    ViewBag.ErrorMessage
</div>
@if(Model != null && HttpContext.Current.IsDebuggingEnabled)
{
    <div class="" style="background:khaki">
        <p>
            <b>Exception:</b> @Model.Exception.Message <br/>
            <b>Controller:</b> @Model.ControllerName <br/>
            <b>Action:</b> @Model.ActionName <br/>
        </p>
        <div>
            <pre>
                @Model.Exception.StackTrace
            </pre>
        </div>
    </div>
}

How to remove a file from the index in git?

This should unstage a <file> for you (without removing or otherwise modifying the file):

git reset <file>

How to get a user's time zone?

Swift 4, 4.2 & 5

var timeZone : String = String()

override func viewDidLoad() {
    super.viewDidLoad()
    timeZone = getCurrentTimeZone()
    print(timeZone)
}

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let items = (localTimeZoneAbbreviation / 3600)
        return "\(items)"
}

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

Failed to find 'ANDROID_HOME' environment variable

This solved my problem. Add below to your system path

PATH_TO_android\platforms

PATH_TO_android\platform-tools

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

CodeIgniter 500 Internal Server Error

remove comment in httpd.conf (apache configuration file):

LoadModule rewrite_module modules/mod_rewrite.so 

SQL MAX of multiple columns?

Problem: choose the minimum rate value given to an entity Requirements: Agency rates can be null

[MinRateValue] = 
CASE 
   WHEN ISNULL(FitchRating.RatingValue, 100) < = ISNULL(MoodyRating.RatingValue, 99) 
   AND  ISNULL(FitchRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue, 99) 
   THEN FitchgAgency.RatingAgencyName

   WHEN ISNULL(MoodyRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue , 99)
   THEN MoodyAgency.RatingAgencyName

   ELSE ISNULL(StandardPoorsRating.RatingValue, 'N/A') 
END 

Inspired by this answer from Nat

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

Matching a space in regex

You can also use the \b for a word boundary. For the name I would use something like this:

[^\b]+\b[^\b]+(\b|$)

EDIT Modifying this to be a regex in Perl example

if( $fullname =~ /([^\b]+)\b[^\b]+([^\b]+)(\b|$)/ ) {
 $first_name = $1;
 $last_name = $2;
}

EDIT AGAIN Based on what you want:

$new_tag = preg_replace("/[\s\t]/","",$tag);

Converting an array to a function arguments list

A very readable example from another post on similar topic:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, args);

And here a link to the original post that I personally liked for its readability

How to use pip on windows behind an authenticating proxy

Try to encode backslash between domain and user

pip --proxy https://domain%5Cuser:password@proxy:port install -r requirements.txt

Cannot find Dumpbin.exe

By default, it's not in your PATH. You need to use the "Visual Studio 2005 Command Prompt". Alternatively, you can run the vsvars32 batch file, which will set up your environment correctly.

Conveniently, the path to this is stored in the VS80COMNTOOLS environment variable.

How to give the background-image path in CSS?

Your css is here: Project/Web/Support/Styles/file.css

1 time ../ means Project/Web/Support and 2 times ../ i.e. ../../ means Project/Web

Try:

background-image: url('../../images/image.png');

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Here is the solutions that worked for me:

  1. open index.php from the htdocs folder
  2. inside replace the word dashboard with your database name.
  3. restart the server

This should resolve the issue :-)

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

output:

2008-12-04 01:50:17

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later, not during the event, because $.getJSON is asynchronous.

You have two options:

  1. Do something else, rather than window.open.

  2. Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to:

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback
    });
    

    ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false:

    $.ajax({
        url:      "redirect/" + pageId,
        async:    false,
        dataType: "json",
        data:     {},
        success:  function(status) {
            if (status == null) {
                alert("Error in verifying the status.");
            } else if(!status) {
                $("#agreement").dialog("open");
            } else {
                window.open(redirectionURL);
            }
        }
    });
    

    Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.

    Here's an example of code that fails the test because of the asynchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version doesn't work, because the window.open is
      // not during the event processing
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.getJSON("http://jsbin.com/uriyip", function() {
          window.open("http://jsbin.com/ubiqev");
        });
      });
    });
    

    And here's an example that does work, using a synchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version does work, because the window.open is
      // during the event processing. But it uses a synchronous
      // ajax call, locking up the browser UI while the call is
      // in progress.
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.ajax({
          url:      "http://jsbin.com/uriyip",
          async:    false,
          dataType: "json",
          success:  function() {
            window.open("http://jsbin.com/ubiqev");
          }
        });
      });
    });
    

How to get the employees with their managers

(SELECT ename FROM EMP WHERE empno = mgr)

There are no records in EMP that meet this criteria.

You need to self-join to get this relation.

SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;

EDIT:

The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:

> select * from emp;

 empno | ename |    job    | deptno | mgr  
-------+-------+-----------+--------+------
  7839 | king  | president |     10 |     
  7698 | blake | manager   |     30 | 7839
(2 rows)

> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;

 employee | empno | manager | empno 
----------+-------+---------+-------
 king     |  7839 |         |      
 blake    |  7698 | king    |  7839
(2 rows)

The difference is that an outer join returns all the rows. An inner join will produce the following:

> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;

 ename | empno | manager | mgr  
-------+-------+---------+------
 blake |  7698 | king    | 7839
(1 row)

What is the difference between an int and a long in C++?

As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.

The C89 standard states that UINT_MAX should be at least 2^16-1, USHRT_MAX 2^16-1 and ULONG_MAX 2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (CHAR_BIT). C++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values. You should however not derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case CHAR_BIT must be at least 32. Just remember that "byte" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

How to replace NA values in a table for selected columns

Not sure if this is more concise, but this function will also find and allow replacement of NAs (or any value you like) in selected columns of a data.table:

update.mat <- function(dt, cols, criteria) {
  require(data.table)
  x <- as.data.frame(which(criteria==TRUE, arr.ind = TRUE))
  y <- as.matrix(subset(x, x$col %in% which((names(dt) %in% cols), arr.ind = TRUE)))
  y
}

To apply it:

y[update.mat(y, c("a", "b"), is.na(y))] <- 0

The function creates a matrix of the selected columns and rows (cell coordinates) that meet the input criteria (in this case is.na == TRUE).

Multiple cases in switch statement

With C#9 came the Relational Pattern Matching. This allows us to do:

switch (value)
{
    case 1 or 2 or 3:
      // Do stuff
      break;
    case 4 or 5 or 6:
      // Do stuff
      break;
    default:
        // Do stuff
        break;
}

In deep tutorial of Relational Patter in C#9

Pattern-matching changes for C# 9.0

Relational patterns permit the programmer to express that an input value must satisfy a relational constraint when compared to a constant value

How to put a Scanner input into an array... for example a couple of numbers

import java.util.Scanner;
public class sort {

  public static void main(String args[])
    {
        int i,n,t;          

        Scanner sc=new Scanner(System.in);

        System.out.print("Enter the size of array");

        n=sc.nextInt();

        int a[] = new int[n];

        System.out.println("Enter elements in array");

        for(i=0;i<n;i++)
        {
            a[i]=sc.nextInt();
        }
        t=a[1];

        for(i=0;i<n;i++)
        {
            if(a[i]>t)

                t=a[i];
        }
        System.out.println("Greates integer is" +t);
    }
}

HTML5 - mp4 video does not play in IE9

Dan has one of the best answers up there and I'd suggest you use html5test.com on your target browsers to see the video formats that are supported.

As stated above, no single format works and what I use is MP4 encoded to H.264, WebM, and a flash fallback. This let's me show video on the following:

Win 7 - IE9, Chrome, Firefox, Safari, Opera

Win XP - IE7, IE8, Chrome, Firefox, Safari, Opera

MacBook OS X - Chrome, Firefox, Safari, Opera

iPad 2, iPad 3

Linux - Android 2.3, Android 3

<video width="980" height="540" controls>
        <source src="images/placeholdername.mp4" type="video/mp4" />
        <source src="images/placeholdername.webm" type="video/webm" />
        <embed src="images/placeholdername.mp4" type="application/x-shockwave-flash" width="980" height="570" allowscriptaccess="always" allowfullscreen="true" autoplay="false"></embed>  <!--IE 8 - add 25-30 pixels to vid height to allow QT player controls-->    
    </video>

Note: The .mp4 video should be coded in h264 basic profile, so that it plays on all mobile devices.

Update: added autoplay="false" to the Flash fallback. This prevents the MP4 from starting to play right away when the page loads on IE8, it will start to play once the play button is pushed.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

If you're on Mac, restarting the DNS responder fixed the issue for me.

sudo killall -HUP mDNSResponder

Xcode Error: "The app ID cannot be registered to your development team."

Changing Bundle Identifier worked for me.

  1. Go to Signing & Capabilities tab
  2. Change my Bundle Identifier. "MyApp" > "MyCompanyName.MyApp"
  3. Enter and wait a seconds for generating Signing Certificate

If it still doesn't work, try again with these steps before:

  1. Remove your Provisioning Profiles: cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm * (in my case)
  2. Clearn your project
  3. ...

How to get autocomplete in jupyter notebook without using tab?

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.

How can I undo git reset --hard HEAD~1?

In most cases, yes.

Depending on the state your repository was in when you ran the command, the effects of git reset --hard can range from trivial to undo, to basically impossible.

Below I have listed a range of different possible scenarios, and how you might recover from them.

All my changes were committed, but now the commits are gone!

This situation usually occurs when you run git reset with an argument, as in git reset --hard HEAD~. Don't worry, this is easy to recover from!

If you just ran git reset and haven't done anything else since, you can get back to where you were with this one-liner:

git reset --hard @{1}

This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).

If, however, you have made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run git reflog <branchname> to see a list of all recent changes made to your branch (including resets). That list will look something like this:

7c169bd master@{0}: reset: moving to HEAD~
3ae5027 master@{1}: commit: Changed file2
7c169bd master@{2}: commit: Some change
5eb37ca master@{3}: commit (initial): Initial commit

Find the operation in this list that you want to "undo". In the example above, it would be the first line, the one that says "reset: moving to HEAD~". Then copy the representation of the commit before (below) that operation. In our case, that would be master@{1} (or 3ae5027, they both represent the same commit), and run git reset --hard <commit> to reset your current branch back to that commit.

I staged my changes with git add, but never committed. Now my changes are gone!

This is a bit trickier to recover from. git does have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using git fsck.

For details on this, see Undo git reset --hard with uncommitted files in the staging area.

I had changes to files in my working directory that I never staged with git add, and never committed. Now my changes are gone!

Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the documentation for git reset:

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

It's possible that you might be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

Regex: match word that ends with "Id"

Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:

\w+Id\b

1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

See the 9 line of your code,it may be an error; it should be:

mail.smtp.user 

not

mail.stmp.user;

bootstrap popover not showing on top of all elements

Many years later, but like me, others may search for this. All updates taking into consideration, all this can be solved with correct initialization options, in JavaScript.

$('.tip').tooltip({
    boundary: 'viewport',
    placement: 'top',
    container:'body',
    sanitize: true,
    appendToBody: true
});

Those settings solved all may issues. I had tooltips flickering, showing corectly only for half of the items on page, jumping from top to left continously, all kinds of wierdness. But with those settings everything is solved. Hope it help anyone looking.

how to customize `show processlist` in mysql?

...We don't have a newer version of MySQL yet, so I was able to do this (works only on UNIX):

 host=maindb

 echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Locked

The above will query for all locked sessions, and return the information and SQL that is involved.

...So- assuming you wanted to query for sessions that were sleeping:

  host=maindb

  echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Sleep

Or, assuming you needed to provide additional connection parameters for MySQL:

  host=maindb

  user=me

  password=mycoolpassword 

  echo "show full processlist\G" | mysql -h$host -u$user -p$password | grep -B 6 -A 1 Locked

With a couple of tweaks, I'm sure a shell script could be easily created to query the processlist the way you want it.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Difference between FetchType LAZY and EAGER in Java Persistence API?

LAZY: It fetches the child entities lazily i.e at the time of fetching parent entity it just fetches proxy(created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.

EAGER: it fetches the child entities along with parent.

For better understanding go to Jboss documentation or you can use hibernate.show_sql=true for your app and check the queries issued by the hibernate.

Is there a portable way to get the current username in Python?

To me using os module looks the best for portability: Works best on both Linux and Windows.

import os

# Gives user's home directory
userhome = os.path.expanduser('~')          

print "User's home Dir: " + userhome

# Gives username by splitting path based on OS
print "username: " + os.path.split(userhome)[-1]           

Output:

Windows:

User's home Dir: C:\Users\myuser

username: myuser

Linux:

User's home Dir: /root

username: root

No need of installing any modules or extensions.

What is a Windows Handle?

A HANDLE in Win32 programming is a token that represents a resource that is managed by the Windows kernel. A handle can be to a window, a file, etc.

Handles are simply a way of identifying a particulate resource that you want to work with using the Win32 APIs.

So for instance, if you want to create a Window, and show it on the screen you could do the following:

// Create the window
HWND hwnd = CreateWindow(...); 
if (!hwnd)
   return; // hwnd not created

// Show the window.
ShowWindow(hwnd, SW_SHOW);

In the above example HWND means "a handle to a window".

If you are used to an object oriented language you can think of a HANDLE as an instance of a class with no methods who's state is only modifiable by other functions. In this case the ShowWindow function modifies the state of the Window HANDLE.

See Handles and Data Types for more information.

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

How to remove default chrome style for select Input?

use simple code for remove default browser style for outline

input { outline: none; }

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

get the value of input type file , and alert if empty

There should be

$('.send_upload')

but not $('.upload')

dyld: Library not loaded: @rpath/libswiftCore.dylib

I think it's a bug when certificates are generated directly from Xcode. To resolve (at least in Xcode 6.1 / 6A1052d):

  1. go to the Apple Developer website where certificates are managed: https://developer.apple.com/account/ios/certificate/certificateList.action
  2. select your certificate(s) (which should show "Managed by Xcode" under "Status") and "Revoke" it
  3. follow instructions here to manually generate a new certificate: https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html#//apple_ref/doc/uid/TP40012582-CH31-SW32
  4. go to Xcode > Preferences > Accounts > [your Apple ID] > double-click your team name > hit refresh button to update certificates and provisioning profiles

Importing a Maven project into Eclipse from Git

Direct answer: Go to Files>>Import>>Git>>Project From Git (you should have GIT installed on Eclips)

How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

Is there any way to change input type="date" format?

Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.

The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.

You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:

 <date-input date="{{date}}" timezone="[[timezone]]"></date-input>

or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)

Standards-compliant, no hacks.

Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It's 2018, so chances are it'll surely cover most of your users.

Hope it helps!

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Well this worked for me

rvm pkg install openssl
rvm reinstall 1.9.2 --with-openssl-dir=$rvm_path/usr

Something is wrong with openssl implementation of my ubuntu 12.04

How do I run a shell script without using "sh" or "bash" commands?

You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)

ex: sudo install quickcommit.sh /usr/local/bin/quickcommit enter password

now can run without .sh and in any directory

Using Java to pull data from a webpage?

Since Java 11 the most convenient way it to use java.net.http.HttpClient from the standard library.

Example:

HttpRequest request = HttpRequest.newBuilder(new URI(
    "https://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"))
  .timeout(Duration.of(10, SECONDS))
  .GET()
  .build();

HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, BodyHandlers.ofString());

if (response.statusCode() != 200) {
  throw new RuntimeException(
    "Invalid response: " + response.statusCode() + ", request: " + response);
}

System.out.println(response.body());

jQuery to retrieve and set selected option value of html select element

Suppose you have created a Drop Down list using SELECT tag like as follows,

<select id="Country">

Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..

var result= $("#Country option:selected").text();

it will work fine.

Window.open and pass parameters by post method

You could simply use target="_blank" on the form.

<form action="action.php" method="post" target="_blank">
    <input type="hidden" name="something" value="some value">
</form>

Add hidden inputs in the way you prefer, and then simply submit the form with JS.

Github Push Error: RPC failed; result=22, HTTP code = 413

https clone of gists fails (ssh works, see below):

12:00 jean@laptop:~/tmp$ GIT_CURL_VERBOSE=1 git clone https://gist.github.com/123456.git username
Initialized empty Git repository in /home/jean/tmp/username/.git/
* Couldn't find host gist.github.com in the .netrc file; using defaults
* About to connect() to gist.github.com port 443 (#0)
*   Trying 192.30.252.142... * Connected to gist.github.com (192.30.252.142) port 443 (#0)
* found 141 certificates in /etc/ssl/certs/ca-certificates.crt
*        server certificate verification OK
*        common name: *.github.com (matched)
*        server certificate expiration date OK
*        server certificate activation date OK
*        certificate public key: RSA
*        certificate version: #3
*        subject: C=US,ST=California,L=San Francisco,O=GitHub\, Inc.,CN=*.github.com
*        start date: Mon, 30 Apr 2012 00:00:00 GMT
*        expire date: Wed, 09 Jul 2014 12:00:00 GMT
*        issuer: C=US,O=DigiCert Inc,OU=www.digicert.com,CN=DigiCert High Assurance CA-3
*        compression: NULL
*        cipher: ARCFOUR-128
*        MAC: SHA1
> GET /123456.git/info/refs?service=git-upload-pack HTTP/1.1
User-Agent: git/1.7.1
Host: gist.github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 301 Moved Permanently
< Server: GitHub.com
< Date: Fri, 01 Nov 2013 05:00:51 GMT
< Content-Type: text/html
< Content-Length: 178
< Location: https://gist.github.com/gist/123456.git/info/refs?service=git-upload-pack
< Vary: Accept-Encoding
<
* Ignoring the response-body
* Expire cleared
* Connection #0 to host gist.github.com left intact
* Issue another request to this URL: 'https://gist.github.com/gist/123456.git/info/refs?service=git-upload-pack'
* Couldn't find host gist.github.com in the .netrc file; using defaults
* Re-using existing connection! (#0) with host gist.github.com
* Connected to gist.github.com (192.30.252.142) port 443 (#0)
> GET /gist/123456.git/info/refs?service=git-upload-pack HTTP/1.1
User-Agent: git/1.7.1
Host: gist.github.com
Accept: */*
Pragma: no-cache

< HTTP/1.1 200 OK
< Server: GitHub.com
< Date: Fri, 01 Nov 2013 05:00:52 GMT
< Content-Type: application/x-git-upload-pack-advertisement
< Transfer-Encoding: chunked
< Expires: Fri, 01 Jan 1980 00:00:00 GMT
< Pragma: no-cache
< Cache-Control: no-cache, max-age=0, must-revalidate
< Vary: Accept-Encoding
<
* Connection #0 to host gist.github.com left intact
* Couldn't find host gist.github.com in the .netrc file; using defaults
* About to connect() to gist.github.com port 443 (#0)
*   Trying 192.30.252.142... * connected
* Connected to gist.github.com (192.30.252.142) port 443 (#0)
* found 141 certificates in /etc/ssl/certs/ca-certificates.crt
* SSL re-using session ID
*        server certificate verification OK
*        common name: *.github.com (matched)
*        server certificate expiration date OK
*        server certificate activation date OK
*        certificate public key: RSA
*        certificate version: #3
*        subject: C=US,ST=California,L=San Francisco,O=GitHub\, Inc.,CN=*.github.com
*        start date: Mon, 30 Apr 2012 00:00:00 GMT
*        expire date: Wed, 09 Jul 2014 12:00:00 GMT
*        issuer: C=US,O=DigiCert Inc,OU=www.digicert.com,CN=DigiCert High Assurance CA-3
*        compression: NULL
*        cipher: ARCFOUR-128
*        MAC: SHA1
> POST /123456.git/git-upload-pack HTTP/1.1
User-Agent: git/1.7.1
Host: gist.github.com
Accept-Encoding: deflate, gzip
Content-Type: application/x-git-upload-pack-request
Accept: application/x-git-upload-pack-result
Content-Length: 116

< HTTP/1.1 301 Moved Permanently
< Server: GitHub.com
< Date: Fri, 01 Nov 2013 05:00:53 GMT
< Content-Type: text/html
< Content-Length: 178
< Location: https://gist.github.com/gist/123456.git/git-upload-pack
< Vary: Accept-Encoding
<
* Ignoring the response-body
* Connection #0 to host gist.github.com left intact
* Issue another request to this URL: 'https://gist.github.com/gist/123456.git/git-upload-pack'
* Violate RFC 2616/10.3.2 and switch from POST to GET
* Couldn't find host gist.github.com in the .netrc file; using defaults
* Re-using existing connection! (#0) with host gist.github.com
* Connected to gist.github.com (192.30.252.142) port 443 (#0)
> GET /gist/123456.git/git-upload-pack HTTP/1.1
User-Agent: git/1.7.1
Host: gist.github.com
Accept-Encoding: deflate, gzip
Content-Type: application/x-git-upload-pack-request
Accept: application/x-git-upload-pack-result

* The requested URL returned error: 400
* Closing connection #0
error: RPC failed; result=22, HTTP code = 400

This works: git clone [email protected]:123456.git

ADB.exe is obsolete and has serious performance problems

I faced the same issue, and I tried following things, which didn't work:

  1. Deleting the existing AVD and creating a new one.

  2. Uninstall latest-existing and older versions (if you have) of SDK-Tools and SDK-Build-Tools and installing new ones.

What worked for me was uninstalling and re-installing latest PLATFORM-TOOLS, where adb actually resides.

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

Angular + Material - How to refresh a data source (mat-table)

After reading Material Table not updating post data update #11638 Bug Report I found the best (read, the easiest solution) was as suggested by the final commentor 'shhdharmen' with a suggestion to use an EventEmitter.

This involves a few simple changes to the generated datasource class

ie) add a new private variable to your datasource class

import { EventEmitter } from '@angular/core';
...
private tableDataUpdated = new EventEmitter<any>();

and where I push new data to the internal array (this.data), I emit an event.

public addRow(row:myRowInterface) {
    this.data.push(row);
    this.tableDataUpdated.emit();
}

and finally, change the 'dataMutation' array in the 'connect' method - as follows

const dataMutations = [
    this.tableDataUpdated,
    this.paginator.page,
    this.sort.sortChange
];

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

You need to close all your connexions for example: If you make an INSERT INTO statement you need to close the statement and your connexion in this way:

statement.close();
Connexion.close():

And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:

resultset.close();
statement.close();
Connexion.close();

I did this and it worked

Why is there no xrange function in Python3?

Python 3's range type works just like Python 2's xrange. I'm not sure why you're seeing a slowdown, since the iterator returned by your xrange function is exactly what you'd get if you iterated over range directly.

I'm not able to reproduce the slowdown on my system. Here's how I tested:

Python 2, with xrange:

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
18.631936646865853

Python 3, with range is a tiny bit faster:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
17.31399508687869

I recently learned that Python 3's range type has some other neat features, such as support for slicing: range(10,100,2)[5:25:5] is range(20, 60, 10)!

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Why are static variables considered evil?

Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.

I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;

Scroll to a specific Element Using html

If you use Jquery you can add this to your javascript:

$('.smooth-goto').on('click', function() {  
    $('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
    return false;
});

Also, don't forget to add this class to your a tag too like this:

<a href="#id-of-element" class="smooth-goto">Text</a>

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

Difference between HashMap, LinkedHashMap and TreeMap

  • HashMap:

    • Order not maintains
    • Faster than LinkedHashMap
    • Used for store heap of objects
  • LinkedHashMap:

    • LinkedHashMap insertion order will be maintained
    • Slower than HashMap and faster than TreeMap
    • If you want to maintain an insertion order use this.
  • TreeMap:

    • TreeMap is a tree-based mapping
    • TreeMap will follow the natural ordering of key
    • Slower than HashMap and LinkedHashMap
    • Use TreeMap when you need to maintain natural(default) ordering

Why does "return list.sort()" return None, not the list?

list.sort sorts the list in place, i.e. it doesn't return a new list. Just write

newList.sort()
return newList

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

Here is my combined solution for various PHP versions.

In my company we are working with different servers with various PHP versions, so I had to find solution working for all.

$phpVersion = substr(phpversion(), 0, 3)*1;

if($phpVersion >= 5.4) {
  $encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
  $encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}

Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.

How to check if a float value is a whole number

We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.

This function will return a boolean, True or False, depending on whether n is a whole number.

def is_whole(n):
    return n % 1 == 0

How to get the type of T from a member of a generic class or method?

I use this extension method to accomplish something similar:

public static string GetFriendlyTypeName(this Type t)
{
    var typeName = t.Name.StripStartingWith("`");
    var genericArgs = t.GetGenericArguments();
    if (genericArgs.Length > 0)
    {
        typeName += "<";
        foreach (var genericArg in genericArgs)
        {
            typeName += genericArg.GetFriendlyTypeName() + ", ";
        }
        typeName = typeName.TrimEnd(',', ' ') + ">";
    }
    return typeName;
}

public static string StripStartingWith(this string s, string stripAfter)
{
    if (s == null)
    {
        return null;
    }
    var indexOf = s.IndexOf(stripAfter, StringComparison.Ordinal);
    if (indexOf > -1)
    {
        return s.Substring(0, indexOf);
    }
    return s;
}

You use it like this:

[TestMethod]
public void GetFriendlyTypeName_ShouldHandleReallyComplexTypes()
{
    typeof(Dictionary<string, Dictionary<string, object>>).GetFriendlyTypeName()
        .ShouldEqual("Dictionary<String, Dictionary<String, Object>>");
}

This isn't quite what you're looking for, but it's helpful in demonstrating the techniques involved.

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

Can I extend a class using more than 1 class in PHP?

If you want to check if a function is public see this topic : https://stackoverflow.com/a/4160928/2226755

And use call_user_func_array(...) method for many or not arguments.

Like this :

class B {
    public function method_from_b($s) {
        echo $s;
    }
}

class C {
    public function method_from_c($l, $l1, $l2) {
        echo $l.$l1.$l2;
    }
}

class A extends B {
    private $c;

    public function __construct() {
        $this->c = new C;
    }

    public function __call($method, $args) {
        if (method_exists($this->c, $method)) {
            $reflection = new ReflectionMethod($this->c, $method);
            if (!$reflection->isPublic()) {
                throw new RuntimeException("Call to not public method ".get_class($this)."::$method()");
            }

            return call_user_func_array(array($this->c, $method), $args);
        } else {
            throw new RuntimeException("Call to undefined method ".get_class($this)."::$method()");
        }
    }
}


$a = new A;
$a->method_from_b("abc");
$a->method_from_c("d", "e", "f");

How is the default submit button on an HTML form determined?

HTML 4 does not make it explicit. The current HTML5 working draft specifies that the first submit button must be the default:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

How to show a confirm message before delete?

Using jQuery:

$(".delete-link").on("click", null, function(){
        return confirm("Are you sure?");
    });

How to write loop in a Makefile?

If you're using GNU make, you could try

NUMBERS = 1 2 3 4
doit:
        $(foreach var,$(NUMBERS),./a.out $(var);)

which will generate and execute

./a.out 1; ./a.out 2; ./a.out 3; ./a.out 4;

Disabling Controls in Bootstrap

Remember for jQuery 1.6+ you should use the .prop() function.

$("input").prop('disabled', true);

$("input").prop('disabled', false);

Simplest code for array intersection in javascript

This is probably the simplest one, besides list1.filter(n => list2.includes(n))

_x000D_
_x000D_
var list1 = ['bread', 'ice cream', 'cereals', 'strawberry', 'chocolate']_x000D_
var list2 = ['bread', 'cherry', 'ice cream', 'oats']_x000D_
_x000D_
function check_common(list1, list2){_x000D_
 _x000D_
 list3 = []_x000D_
 for (let i=0; i<list1.length; i++){_x000D_
  _x000D_
  for (let j=0; j<list2.length; j++){ _x000D_
   if (list1[i] === list2[j]){_x000D_
    list3.push(list1[i]);    _x000D_
   }  _x000D_
  }_x000D_
  _x000D_
 }_x000D_
 return list3_x000D_
 _x000D_
}_x000D_
_x000D_
check_common(list1, list2) // ["bread", "ice cream"]
_x000D_
_x000D_
_x000D_

How to remove item from array by value?

A one-liner will do it,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

What it does (from the doc link)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

Angular 2 Checkbox Two Way Data Binding

I have done a custom component tried two way binding

Mycomponent: <input type="checkbox" [(ngModel)]="model" >

_model:  boolean;   

@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();

@Input('checked')
set model(checked: boolean) {

  this._model = checked;
  this.checked.emit(this._model);
  console.log('@Input(setmodel'+checked);
}

get model() {
  return this._model;
}

strange thing is this works

<mycheckbox  [checked]="isChecked" (checked)="isChecked = $event">

while this wont

<mycheckbox  [(checked)]="isChecked">

Install a .NET windows service without InstallUtil.exe

Take a look at the InstallHelper method of the ManagedInstaller class. You can install a service using:

string[] args;
ManagedInstallerClass.InstallHelper(args);

This is exactly what InstallUtil does. The arguments are the same as for InstallUtil.

The benefits of this method are that it involves no messing in the registry, and it uses the same mechanism as InstallUtil.

CSS3 Transform Skew One Side

I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.

http://jsfiddle.net/zwXaf/2/

HTML

<ul>
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>

CSS

/* reset */
ul, li, a {
    margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
    display: inline-block;
    text-align: center;
}
/* appearance styling */
ul {
    /* hacks to make one side slant only */
    overflow: hidden;
    background: linear-gradient(to right, red, white, white, red);
}
li {
    background-color: red;
     transform:skewX(-20deg);
    -ms-transform:skewX(-20deg);
    -webkit-transform:skewX(-20deg);
}
li a {
    padding: 3px 6px 3px 6px;
    color: #ffffff;
    text-decoration: none;
    width: 80px;
     transform:skewX(20deg);
    -ms-transform:skewX(20deg);
    -webkit-transform:skewX(20deg);
}

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

If you need extract the text without the brackets, you can use bash awk

echo " [hola mundo] " | awk -F'[][]' '{print $2}'

result:

hola mundo

How do ACID and database transactions work?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.

  • Atomicity :
  • Consistency
  • Isolation
  • Durability

Fitting a density curve to a histogram in R

Such thing is easy with ggplot2

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

or to mimic the result from Dirk's solution

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

Variables not showing while debugging in Eclipse

For me the solution of the problem was to configure xdebug properly. I added in the php.ini this lines of code :

zend_extension = "C:\xampp\php\ext\php_xdebug.dll"

xdebug.remote_enable = 1

xdebug.show_local_vars = 1

The important part I was missing : xdebug.remote_enable = 1

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

For those using JaVers, given an audited entity class, you may want to ignore the properties causing the LazyInitializationException exception (e.g. by using the @DiffIgnore annotation).

This tells the framework to ignore those properties when calculating the object differences, so it won't try to read from the DB the related objects outside the transaction scope (thus causing the exception).

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I agree with Aamir that the submission arrow.m from Erik Johnson on the MathWorks File Exchange is a very nice option. You can use it to illustrate the different methods of vector addition like so:

  • Tip-to-tail method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; a; o];        %# Starting points for arrows
    arrowEnds = [a; c; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    
  • Parallelogram method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; o; o];        %# Starting points for arrows
    arrowEnds = [a; b; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    hold on;
    lineX = [a(1) b(1); c(1) c(1)];  %# X data for lines
    lineY = [a(2) b(2); c(2) c(2)];  %# Y data for lines
    lineZ = [a(3) b(3); c(3) c(3)];  %# Z data for lines
    line(lineX,lineY,lineZ,'Color','k','LineStyle',':');  %# Plot lines
    

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

How do I create executable Java program?

On the command line, navigate to the root directory of the Java files you wish to make executable.

Use this command:

jar -cvf [name of jar file] [name of directory with Java files]

This will create a directory called META-INF in the jar archive. In this META-INF there is a file called MANIFEST.MF, open this file in a text editor and add the following line:

Main-Class: [fully qualified name of your main class]

then use this command:

java -jar [name of jar file]

and your program will run :)

What are the best practices for using a GUID as a primary key, specifically regarding performance?

This link says it better than I could and helped in my decision making. I usually opt for an int as a primary key, unless I have a specific need not to and I also let SQL server auto-generate/maintain this field unless I have some specific reason not to. In reality, performance concerns need to be determined based on your specific app. There are many factors at play here including but not limited to expected db size, proper indexing, efficient querying, and more. Although people may disagree, I think in many scenarios you will not notice a difference with either option and you should choose what is more appropriate for your app and what allows you to develop easier, quicker, and more effectively (If you never complete the app what difference does the rest make :).

https://web.archive.org/web/20120812080710/http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html

P.S. I'm not sure why you would use a Composite PK or what benefit you believe that would give you.

Comparing floating point number to zero

You are correct with your observation.

If x == 0.0, then abs(x) * epsilon is zero and you're testing whether abs(y) <= 0.0.

If y == 0.0 then you're testing abs(x) <= abs(x) * epsilon which means either epsilon >= 1 (it isn't) or x == 0.0.

So either is_equal(val, 0.0) or is_equal(0.0, val) would be pointless, and you could just say val == 0.0. If you want to only accept exactly +0.0 and -0.0.

The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".

PHP ternary operator vs null coalescing operator

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

You can also do this, and the first defined (set and not null) value will be returned:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

How to do constructor chaining in C#

Are you asking about this?

  public class VariantDate {
    public int day;
    public int month;
    public int year;

    public VariantDate(int day) : this(day, 1) {}

    public VariantDate(int day, int month) : this(day, month,1900){}

    public VariantDate(int day, int month, int year){
    this.day=day;
    this.month=month;
    this.year=year;
    }

}

Auto refresh code in HTML using meta tags

It looks like you probably pasted this (or used a word processor like MS Word) using a kind of double-quotes that are not recognized by the browser. Please check that your code uses actual double-quotes like this one ", which is different from the following character:

Replace the meta tag with this one and try again:

<meta http-equiv="refresh" content="5" >

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

"for loop" with two variables?

For your use case, it may be easier to utilize a while loop.

t1 = [137, 42]
t2 = ["Hello", "world"]

i = 0
j = 0
while i < len(t1) and j < len(t2):
    print t1[i], t2[j]
    i += 1
    j += 1

# 137 Hello
# 42 world

As a caveat, this approach will truncate to the length of your shortest list.

Can anyone explain me StandardScaler?

Following is a simple working example to explain how standarization calculation works. The theory part is already well explained in other answers.

>>>import numpy as np
>>>data = [[6, 2], [4, 2], [6, 4], [8, 2]]
>>>a = np.array(data)

>>>np.std(a, axis=0)
array([1.41421356, 0.8660254 ])

>>>np.mean(a, axis=0)
array([6. , 2.5])

>>>from sklearn.preprocessing import StandardScaler
>>>scaler = StandardScaler()
>>>scaler.fit(data)
>>>print(scaler.mean_)

#Xchanged = (X-µ)/s  WHERE s is Standard Deviation and µ is mean
>>>z=scaler.transform(data)
>>>z

Calculation

As you can see in the output, mean is [6. , 2.5] and std deviation is [1.41421356, 0.8660254 ]

Data is (0,1) position is 2 Standardization = (2 - 2.5)/0.8660254 = -0.57735027

Data in (1,0) position is 4 Standardization = (4-6)/1.41421356 = -1.414

Result After Standardization

enter image description here

Check Mean and Std Deviation After Standardization

enter image description here

Note: -2.77555756e-17 is very close to 0.

References

  1. Compare the effect of different scalers on data with outliers

  2. What's the difference between Normalization and Standardization?

  3. Mean of data scaled with sklearn StandardScaler is not zero

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

Increasing the maximum number of TCP/IP connections in Linux

Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.

On the client side: Increase the ephermal port range, and decrease the tcp_fin_timeout

To find out the default values:

sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout

The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout defines the minimum time these sockets will stay in TIME_WAIT state (unusable after being used once). Usual system defaults are:

  • net.ipv4.ip_local_port_range = 32768 61000
  • net.ipv4.tcp_fin_timeout = 60

This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470 sockets per second. If you are not happy with that, you could begin with increasing the port_range. Setting the range to 15000 61000 is pretty common these days. You could further increase the availability by decreasing the fin_timeout. Suppose you do both, you should see over 1500 outbound connections per second, more readily.

To change the values:

sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30

The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."

Default Sysctl values on a typical Linux box for tcp_tw_recycle & tcp_tw_reuse would be

net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0

These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait cycle. I recommend setting:

sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1 

This allows fast cycling of sockets in time_wait state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle has been removed from Linux 4.12.

On the Server Side: The net.core.somaxconn value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.

sysctl net.core.somaxconn=1024

txqueuelen parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.

ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local

Similarly bump up the values for net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog. Their default values are 1000 and 1024 respectively.

sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048

Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.

Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

Passing environment-dependent variables in webpack

You can directly use the EnvironmentPlugin available in webpack to have access to any environment variable during the transpilation.

You just have to declare the plugin in your webpack.config.js file:

var webpack = require('webpack');

module.exports = {
    /* ... */
    plugins = [
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ]
};

Note that you must declare explicitly the name of the environment variables you want to use.

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

Write values in app.config file

If you are using App.Config to store values in <add Key="" Value="" /> or CustomSections section use ConfigurationManager class, else use XMLDocument class.

For example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="server" value="192.168.0.1\xxx"/>
    <add key="database" value="DataXXX"/>
    <add key="username" value="userX"/>
    <add key="password" value="passX"/>
  </appSettings>
</configuration>

You could use the code posted on CodeProject

How do I convert csv file to rdd

Firstly I must say that it's much much simpler if you put your headers in separate files - this is the convention in big data.

Anyway Daniel's answer is pretty good, but it has an inefficiency and a bug, so I'm going to post my own. The inefficiency is that you don't need to check every record to see if it's the header, you just need to check the first record for each partition. The bug is that by using .split(",") you could get an exception thrown or get the wrong column when entries are the empty string and occur at the start or end of the record - to correct that you need to use .split(",", -1). So here is the full code:

val header =
  scala.io.Source.fromInputStream(
    hadoop.fs.FileSystem.get(new java.net.URI(filename), sc.hadoopConfiguration)
    .open(new hadoop.fs.Path(path)))
  .getLines.head

val columnIndex = header.split(",").indexOf(columnName)

sc.textFile(path).mapPartitions(iterator => {
  val head = iterator.next()
  if (head == header) iterator else Iterator(head) ++ iterator
})
.map(_.split(",", -1)(columnIndex))

Final points, consider Parquet if you want to only fish out certain columns. Or at least consider implementing a lazily evaluated split function if you have wide rows.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In JSF 1.2 this was done by <f:setPropertyActionListener> (within the command component). In JSF 2.0 (EL 2.2 to be precise, thanks to BalusC) it's possible to do it like this: action="${filterList.insert(f.id)}

Finding import static statements for Mockito constructs

For is()

import static org.hamcrest.CoreMatchers.*;

For assertThat()

import static org.junit.Assert.*;

For when() and verify()

import static org.mockito.Mockito.*;

JavaScript window resize event

window.onresize = function() {
    // your code
};

Error: Argument is not a function, got undefined

Some times this error is a result of two ng-app directives specified in the html. In my case by mistake I had specified ng-app in my html tag and ng-app="myApp" in the body tag like this:

<html ng-app>
  <body ng-app="myApp"></body>
</html>

Prime numbers between 1 to 100 in C Programming Language

The condition i==j+1 will not be true for i==2. This can be fixed by a couple of changes to the inner loop:

#include <stdio.h>
int main(void)
{
 for (int i=2; i<100; i++)
 {
  for (int j=2; j<=i; j++)   // Changed upper bound
  {
    if (i == j)  // Changed condition and reversed order of if:s
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}

How to count the number of letters in a string without the spaces?

Try using...

resp = input("Hello, I am stuck in doors! What is the weather outside?")
print("You answered in", resp.ascii_letters, "letters!")

Didn't work for me but should work for some random guys.

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

Undefined Reference to

Try to remove the constructor and destructors, it's working for me....

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

    protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 405 && Context.Request.HttpMethod == "OPTIONS" )
        {
            Response.Clear();
            Response.StatusCode = 200;
            Response.End();
        }
    }

.NET Events - What are object sender & EventArgs e?

sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

Print all but the first three columns

A solution that does not add extra leading or trailing whitespace:

awk '{ for(i=4; i<NF; i++) printf "%s",$i OFS; if(NF) printf "%s",$NF; printf ORS}'

### Example ###
$ echo '1 2 3 4 5 6 7' |
  awk '{for(i=4;i<NF;i++)printf"%s",$i OFS;if(NF)printf"%s",$NF;printf ORS}' |
  tr ' ' '-'
4-5-6-7

Sudo_O proposes an elegant improvement using the ternary operator NF?ORS:OFS

$ echo '1 2 3 4 5 6 7' |
  awk '{ for(i=4; i<=NF; i++) printf "%s",$i (i==NF?ORS:OFS) }' |
  tr ' ' '-'
4-5-6-7

EdMorton gives a solution preserving original whitespaces between fields:

$ echo '1   2 3 4   5    6 7' |
  awk '{ sub(/([^ ]+ +){3}/,"") }1' |
  tr ' ' '-'
4---5----6-7

BinaryZebra also provides two awesome solutions:
(these solutions even preserve trailing spaces from original string)

$ echo -e ' 1   2\t \t3     4   5   6 7 \t 8\t ' |
  awk -v n=3 '{ for ( i=1; i<=n; i++) { sub("^["FS"]*[^"FS"]+["FS"]+","",$0);} } 1 ' |
  sed 's/ /./g;s/\t/->/g;s/^/"/;s/$/"/'
"4...5...6.7.->.8->."

$ echo -e ' 1   2\t \t3     4   5   6 7 \t 8\t ' |
  awk -v n=3 '{ print gensub("["FS"]*([^"FS"]+["FS"]+){"n"}","",1); }' |
  sed 's/ /./g;s/\t/->/g;s/^/"/;s/$/"/'
"4...5...6.7.->.8->."

The solution given by larsr in the comments is almost correct:

$ echo '1 2 3 4 5 6 7' | 
  awk '{for (i=3;i<=NF;i++) $(i-2)=$i; NF=NF-2; print $0}' | tr  ' ' '-'
3-4-5-6-7

This is the fixed and parametrized version of larsr solution:

$ echo '1 2 3 4 5 6 7' | 
  awk '{for(i=n;i<=NF;i++)$(i-(n-1))=$i;NF=NF-(n-1);print $0}' n=4 | tr ' ' '-'
4-5-6-7

All other answers before Sep-2013 are nice but add extra spaces:

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

Page redirect after certain time PHP

header( "refresh:5;url=wherever.php" );

indeed you can use this code as teneff said, but you don't have to necessarily put the header before any sent output (this would output a "cannot relocate header.... :3 error").

To solve this use the php function ob_start(); before any html is outputed.

To terminate the ob just put ob_end_flush(); after you don't have any html output.

cheers!

How to consume REST in Java

Its just a 2 line of code.

import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);

Ref. Spring.io consuming-rest

How do you append an int to a string in C++?

You also try concatenate player's number with std::string::push_back :

Example with your code:

int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;

You will see in console:

Player 4

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

stdcall and cdecl

I noticed a posting that say that it does not matter if you call a __stdcall from a __cdecl or visa versa. It does.

The reason: with __cdecl the arguments that are passed to the called functions are removed form the stack by the calling function, in __stdcall, the arguments are removed from the stack by the called function. If you call a __cdecl function with a __stdcall, the stack is not cleaned up at all, so eventually when the __cdecl uses a stacked based reference for arguments or return address will use the old data at the current stack pointer. If you call a __stdcall function from a __cdecl, the __stdcall function cleans up the arguments on the stack, and then the __cdecl function does it again, possibly removing the calling functions return information.

The Microsoft convention for C tries to circumvent this by mangling the names. A __cdecl function is prefixed with an underscore. A __stdcall function prefixes with an underscore and suffixed with an at sign “@” and the number of bytes to be removed. Eg __cdecl f(x) is linked as _f, __stdcall f(int x) is linked as _f@4 where sizeof(int) is 4 bytes)

If you manage to get past the linker, enjoy the debugging mess.

How to change menu item text dynamically in Android

As JxDarkAngel suggested, calling this from anywhere in your Activity,

invalidateOptionsMenu();

and then overriding:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  MenuItem item = menu.findItem(R.id.bedSwitch);
    if (item.getTitle().equals("Set to 'In bed'")) {
        item.setTitle("Set to 'Out of bed'");
        inBed = false;
    } else {
        item.setTitle("Set to 'In bed'");
        inBed = true;
    }
  return super.onPrepareOptionsMenu(menu);
}

is a much better choice. I used the answer from https://stackoverflow.com/a/17496503/568197

SQL Server: Query fast, but slow from procedure

This is probably unlikely, but given that your observed behaviour is unusual it needs to be checked and no-one else has mentioned it.

Are you absolutely sure that all objects are owned by dbo and you don't have a rogue copies owned by yourself or a different user present as well?

Just occasionally when I've seen odd behaviour it's because there was actually two copies of an object and which one you get depends on what is specified and who you are logged on as. For example it is perfectly possible to have two copies of a view or procedure with the same name but owned by different owners - a situation that can arise where you are not logged onto the database as a dbo and forget to specify dbo as object owner when you create the object.

In note that in the text you are running some things without specifying owner, eg

sp_recompile ViewOpener

if for example there where two copies of viewOpener present owned by dbo and [some other user] then which one you actually recompile if you don't specify is dependent upon circumstances. Ditto with the Report_Opener view - if there where two copies (and they could differ in specification or execution plan) then what is used depends upon circumstances - and as you do not specify owner it is perfectly possible that your adhoc query might use one and the compiled procedure might use use the other.

As I say, it's probably unlikely but it is possible and should be checked because your issues could be that you're simply looking for the bug in the wrong place.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You can use the Set-Variable cmdlet. Passing $global:var3 sends the value of $var3, which is not what you want. You want to send the name.

$global:var1 = $null

function foo ($a, $b, $varName)
{
   Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}

foo 1 2 var1

This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:

$global:var1 = $null

function ComputeNewValue ($a, $b)
{
   $a + $b
}

$global:var1 = ComputeNewValue 1 2

HashMap and int as key

The main reason with HashMap not allowing primitive as keys is that HashMap is designed in such a way that for comparing the keys, it makes use of equals() method, and a method can be called only on an object not on a primitive.

Thus when int is autoboxed to Integer, Hashmap can call equals() method on Integer object.

That is why, you should use Integer instead of int. I mean hashmap throws an error while putting int as a key (Don't know the meaning of the error that is thrown)

And if you think that, you can make Map performance faster by making a primitive as a key, there is a library called FastUtil which contains a Map implementation with int type as a key.

Because of this, it is much faster than Hashmap

How to export a Vagrant virtual machine to transfer it

My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:

  • I'm vagrant w/ virtualbox on a Mac
  • I'm using git

This is what worked for me:

1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine. 
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines. 
5.) `git clone my_project`
6.) `vagrant up`

I had a few problems with VB Guest additions.

enter image description here

I fixed them with this solution.

How do I access Configuration in any class in ASP.NET Core?

I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

  1. My startup class is as default
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
  1. My appsettings.json is like this
{
  "CompanySettings": {
    "name": "Fake Co"
  }
}

  1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;

public class EmployeeController 
{
    private IConfiguration _configuration;
    public EmployeeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
    var companyName = configuration.GetValue<string>("CompanySettings:name");
    // companyName = "Fake Co"
}

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric