Programs & Examples On #High level

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

What in the world are Spring beans?

Spring beans are classes. Instead of instantiating a class (using new), you get an instance as a bean cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.

Is Python interpreted, or compiled, or both?

The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.

Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).

Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.

Simplest way to serve static data from outside the application server in a Java web application

if anyone not able to resolve his problem with accepted answer, then note these below considerations:

  1. no need to mention localhost:<port> with <img> src attribute.
  2. make sure you are running this project outside eclipse, because eclipse creates context docBase entry on its own inside its local server.xml file.

ASP.NET MVC View Engine Comparison

I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.

Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>

Why use pointers?

  • In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.
  • Making compilers
  • Making scientific calculators, where you have an array or vector or string map of function pointers?
  • Trying to modify video memory directly - making your own graphics package
  • Making an API!
  • Data structures - node link pointers for special trees you are making

There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.

python: after installing anaconda, how to import pandas

I've had the same exact problem in that I installed Anaconda because a python script I want to use relies on pandas, and that after so doing, python still returned the same comment that "pandas module is missing" or something to that effect.

When I typed "python" to see which python was being called, I found it was still accessing the older version of python 2.7, even though when I installed Anaconda the installer asked (and I agreed) that it would make its python the default python on my machine (PC running Windows 7).

I tried to find if there is a CONFIG.SYS file on the PC, but gave up after searching in various places (If anyone knows, please tell me). I got around the problem by writing a one-line batch script named python2.bat that called the Anaconda2 version of python, which then worked. However, it would clearly be better to change the CONFIG.SYS or whatever the PC uses to decide which version of python to call.

What does void do in java?

Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.

How do I get git to default to ssh and not https for new repositories

The response provided by Trevor is correct.

But here is what you can directly add in your .gitconfig:

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
  insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/

How do you get the width and height of a multi-dimensional array?

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

Time complexity of nested for-loop

First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

 for (i = 0; i < N; i++) {
     for (j = 0; j < M; j++) {
         sequence of statements
      }
  }

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

SQL server stored procedure return a table

Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.

CREATE PROCEDURE test
AS 
BEGIN

    SELECT * FROM sys.databases

    RETURN 27
END

--Use this to test
DECLARE @returnval int

EXEC @returnval = test 

SELECT @returnval

c# replace \" characters

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

Testing Spring's @RequestBody using Spring MockMVC

The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

If you open up your server logs, you should see something like

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])

among other stack traces.

One solution is to set your Gson date format to one of the above (in the stacktrace).

The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

Java program to find the largest & smallest number in n numbers without using arrays

Try the code mentioned below

public static void main(String[] args) {
    int smallest=0; int large=0; int num;
    System.out.println("enter the number");
    Scanner input=new Scanner(System.in);
    int n=input.nextInt();
    num=input.nextInt();
    smallest = num;
    for(int i=0;i<n-1;i++)
        {
            num=input.nextInt();
            if(num<smallest)
            {
                smallest=num;
            }
        }
        System.out.println("the smallest is:"+smallest);
}

Get class name using jQuery

Try it

HTML

<div class="class_area-1">
    area 1
</div>

<div class="class_area-2">
    area 2
</div>

<div class="class_area-3">
    area 3
</div>

jQuery

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
    $('div').click(function(){
        alert($(this).attr('class'));
    });
</script>

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

In STL maps, is it better to use map::insert than []?

The difference between insert() and operator[] has already been well explained in the other answers. However, new insertion methods for std::map were introduced with C++11 and C++17 respectively:

Let me give a brief summary of the "new" insertion methods:

  • emplace(): When used correctly, this method can avoid unnecessary copy or move operations by constructing the element to be inserted in place. Similar to insert(), an element is only inserted if there is no element with the same key in the container.
  • insert_or_assign(): This method is an "improved" version of operator[]. Unlike operator[], insert_or_assign() doesn't require the map's value type to be default constructible. This overcomes the disadvantage mentioned e.g. in Greg Rogers' answer.
  • try_emplace(): This method is an "improved" version of emplace(). Unlike emplace(), try_emplace() doesn't modify its arguments (due to move operations) if insertion fails due to a key already existing in the map.

For more details on insert_or_assign() and try_emplace() please see my answer here.

Simple example code on Coliru

Where does the @Transactional annotation belong?

I prefer to use @Transactional on services layer at method level.

Is there a constraint that restricts my generic method to numeric types?

I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.

Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support. However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.

So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private. I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.

public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);

private static string DoSomethingHelper<T>(this T input, ....)
{
    // complex logic
}

How to get Bitmap from an Uri?

private void uriToBitmap(Uri selectedFileUri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(selectedFileUri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);

        parcelFileDescriptor.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Check out what's in your database.yml file. If you already have your plain Rails app and simply wrapping it with Docker, you should change (inside database.yml):

socket: /var/run/mysqld/mysqld.sock #just comment it out

to

host: db 

where db is the name of my db-service from docker-compose.yml. And here's my docker-compose.yml:

version: '3'
services:
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    links:
      - db
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: root

You start your app in console (in app folder) as docker-compose up. Then WAIT 1 MINUTE (let your mysql service to completely load) until some new logs stop appearing in console. Usually the last line should be like

db_1 | 2017-12-24T12:25:20.397174Z 0 [Note] End of list of non-natively partitioned tables

Then (in a new terminal window) apply:

docker-compose run web rake db:create

and then

docker-compose run web rake db:migrate

After you finish your work stop the loaded images with

docker-compose stop

Don't use docker-compose down here instead because if you do, you will erase your database content.

Next time when you want to resume your work apply:

docker-compose start

The rest of the things do exactly as explained here: https://docs.docker.com/compose/rails/

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too

Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:

Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with

Wscript.Arguments(0)
Wscript.Arguments(1)

and so on. The number of parameter:

Wscript.Arguments.Count

JPA Hibernate One-to-One relationship

This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:

@Entity
public class Person {

    @Id
    @GeneratedValue
    public int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    public OtherInfo otherInfo;

    rest of attributes ...
}

@Entity
public class OtherInfo {

    @Id
    public int id;

    @MapsId
    @OneToOne
    @JoinColumn(name="id")
    public Person person;

    rest of attributes ...
}

More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7.

Long press on UITableView

Use the UITouch timestamp property in touchesBegan to launch a timer or stop it when touchesEnded got fired

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

Create a .env file that will hold your credentials at the root of your project and leave it out of versioning:

$ echo ".env" >> .gitignore

In the .env file, add the variables (adapt them according to your installation):

$ echo "DJANGO_SETTINGS_MODULE=myproject.settings.production"> .env
#50 caracter random key
$ echo "SECRET_KEY='####'">> .env

To use them, put this on top of your production.py settings file:

import os

env = os.environ.copy()
SECRET_KEY = env['SECRET_KEY']

Publish it to Heroku using this gem: http://github.com/ddollar/heroku-config.git

$ heroku plugins:install git://github.com/ddollar/heroku-config.git
$ heroku config:push

This way you avoid to change virtualenv files.

*Based on this tutorial

How to take character input in java

you can use a Scanner to read from input :

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

Any shortcut to initialize all array elements to zero?

How it Reduces the Performance of your application....? Read Following.

In Java Language Specification the Default / Initial Value for any Object can be given as Follows.

For type byte, the default value is zero, that is, the value of (byte) is 0.

For type short, the default value is zero, that is, the value of (short) is 0.

For type int, the default value is zero, that is, 0.

For type long, the default value is zero, that is, 0L.

For type float, the default value is positive zero, that is, 0.0f.

For type double, the default value is positive zero, that is, 0.0d.

For type char, the default value is the null character, that is, '\u0000'.

For type boolean, the default value is false.

For all reference types, the default value is null.

By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.

Because An array is a container object that holds a fixed number of values of a single type. Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.

Now consider the array for String type so that all array elements has default value is null.

Why don't do that......?

you can assign null value by using loop as you suggest in your Question.

int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
    arr[i] = 0;

But if you do so then it will an useless loss of machine cycle. and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.

The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

Change background color of R plot

adjustcolor("blanchedalmond",alpha.f = 0.3)

The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").

Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:

rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")

By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!

Check whether variable is number or string in JavaScript

Beware that typeof NaN is... 'number'

typeof NaN === 'number'; // true

What does set -e mean in a bash script?

I believe the intention is for the script in question to fail fast.

To test this yourself, simply type set -e at a bash prompt. Now, try running ls. You'll get a directory listing. Now, type lsd. That command is not recognized and will return an error code, and so your bash prompt will close (due to set -e).

Now, to understand this in the context of a 'script', use this simple script:

#!/bin/bash 
# set -e

lsd 

ls

If you run it as is, you'll get the directory listing from the ls on the last line. If you uncomment the set -e and run again, you won't see the directory listing as bash stops processing once it encounters the error from lsd.

When should I use UNSIGNED and SIGNED INT in MySQL?

Basically with UNSIGNED, you're giving yourself twice as much space for the integer since you explicitly specify you don't need negative numbers (usually because values you store will never be negative).

Using DateTime in a SqlParameter for Stored Procedure, format error

Here is how I add parameters:

sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB

I am assuming when you write out DOB there are no quotes.

Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.

Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?

How to select option in drop down using Capybara

For some reason it didn't work for me. So I had to use something else.

select "option_name_here", :from => "organizationSelect"

worked for me.

Not Able To Debug App In Android Studio

I solved this issue after doing the following steps:

Go to Tools==>android==>Disable ADB integration and enable it again.

After that, unplug USB from device and plug in again.

Finally press shift + F9

How can I make grep print the lines below and above each matching line?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

Android failed to load JS bundle

I am using Ubuntu and Android only, and I was unable to get it running. I found a really simple solution which is to update your package.json file, changing this lines:

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },

to

"scripts": {
    "start": "adb reverse tcp:8081 tcp:8081 && node node_modules/react-native/local-cli/cli.js start"
  },

And then you run the server by typing

npm run start

This ensures the android device looks for the node server on your computer instead of locally on the phone.

Rails: How can I rename a database column in a Ruby on Rails migration?

In my opinion, in this case, it's better to use rake db:rollback, then edit your migration and again run rake db:migrate.

However, if you have data in the column you don't want to lose, then use rename_column.

How to clear the cache in NetBeans

Just install cache eraser plugin, it is compatible with nb6.9, 7.0,7.1,7.2 and 7.3: To configure the plugin you have to provide the cache dir which is in netbean's about screen. Then with Tools->erase cache, you clear the netbeans cache. That is all, good luck.

http://plugins.netbeans.org/plugin/40014/cache-eraser

Resizing an iframe based on content

If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it's simple:

<script language="JavaScript">
<!--
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>

<iframe src="usagelogs/default.aspx" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>

How to add column if not exists on PostgreSQL?

Simply check if the query returned a column_name.

If not, execute something like this:

ALTER TABLE x ADD COLUMN y int;

Where you put something useful for 'x' and 'y' and of course a suitable datatype where I used int.

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Like the docs say, think about it this way. If you were to do an application like a book reader, you will not want to load all the fragments into memory at once. You would like to load and destroy Fragments as the user reads. In this case you will use FragmentStatePagerAdapter. If you are just displaying 3 "tabs" that do not contain a lot of heavy data (like Bitmaps), then FragmentPagerAdapter might suit you well. Also, keep in mind that ViewPager by default will load 3 fragments into memory. The first Adapter you mention might destroy View hierarchy and re load it when needed, the second Adapter only saves the state of the Fragment and completely destroys it, if the user then comes back to that page, the state is retrieved.

Android, How to create option Menu

you can create options menu like below:

Menu XML code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/Menu_AboutUs"
        android:icon="@drawable/ic_about_us_over_black"
        android:title="About US"/>
    <item
        android:id="@+id/Menu_LogOutMenu"
        android:icon="@drawable/ic_arrow_forward_black"
        android:title="Logout"/>
</menu>

How you can get the menu from MENU XML(Convert menu XML to java):

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_options_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

How to get Selected Item from Menu:

@Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){

            case R.id.Menu_AboutUs:
                //About US
                break;

            case R.id.Menu_LogOutMenu:
                //Do Logout
                break;
        }
        return super.onOptionsItemSelected(item);
    }

Push to GitHub without a password using ssh-key

As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)

To check everything is correct, use ssh -T [email protected]

Next, don't forget to modify the remote point as follows:

git remote set-url origin [email protected]:username/your-repository.git

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

jQuery Button.click() event is triggered twice

Your current code works, you can try it here: http://jsfiddle.net/s4UyH/

You have something outside the example triggering another .click(), check for other handlers that are also triggering a click event on that element.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How to get a MemoryStream from a Stream in .NET?

Use this:

var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);

This will convert Stream to MemoryStream.

What's the difference between @Component, @Repository & @Service annotations in Spring?

@Component: you annotate a class @Component, it tells hibernate that it is a Bean.

@Repository: you annotate a class @Repository, it tells hibernate it is a DAO class and treat it as DAO class. Means it makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service: This tells hibernate it is a Service class where you will have @Transactional etc Service layer annotations so hibernate treats it as a Service component.

Plus @Service is advance of @Component. Assume the bean class name is CustomerService, since you did not choose XML bean configuration way so you annotated the bean with @Component to indicate it as a Bean. So while getting the bean object CustomerService cust = (CustomerService)context.getBean("customerService"); By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’. But if you use @Service annotation for the bean class you can provide a specific bean name by

@Service("AAA")
public class CustomerService{

and you can get the bean object by

CustomerService cust = (CustomerService)context.getBean("AAA");

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

How do I line up 3 divs on the same row?

I'm not sure how I ended up on this post but since most of the answers are using floats, absolute positioning, and other options which aren't optimal now a days, I figured I'd give a new answer that's more up to date on it's standards (float isn't really kosher anymore).

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction:row;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex: 1 1 0px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="column">Column 1</div>_x000D_
    <div class="column">Column 2<br>Column 2<br>Column 2<br>Column 2<br></div>_x000D_
    <div class="column">Column 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Comparing Class Types in Java

If you don't want to or can't use instanceof, then compare with equals:

 if(obj.getClass().equals(MyObject.class)) System.out.println("true");

BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

  • the classes have the same short name but are defined in different packages
  • the classes have the same full name but are loaded by different classloaders.

Viewing unpushed Git commits

As said above:

git diff origin/master..HEAD

But if you are using git gui

After opening gui interface, Select "Repository"->Under that "Visualize History"

Note: Some people like to use CMD Prompt/Terminal while some like to use Git GUI (for simplicity)

How to have comments in IntelliSense for function in Visual Studio?

All these others answers make sense, but are incomplete. Visual Studio will process XML comments but you have to turn them on. Here's how to do that:

Intellisense will use XML comments you enter in your source code, but you must have them enabled through Visual Studio Options. Go to Tools > Options > Text Editor. For Visual Basic, enable the Advanced > Generate XML documentation comments for ''' setting. For C#, enable the Advanced > Generate XML documentation comments for /// setting. Intellisense will use the summary comments when entered. They will be available from other projects after the referenced project is compiled.

To create external documentation, you need to generate an XML file through the Project Settings > Build > XML documentation file: path that controls the compiler's /doc option. You will need an external tool that will take the XML file as input and generate the documentation in your choice of output formats.

Be aware that generating the XML file can noticeably increase your compile time.

How to access custom attributes from event object in React?

To help you get the desired outcome in perhaps a different way than you asked:

render: function() {
    ...
    <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
    ...
},
removeTag: function(i) {
    // do whatever
},

Notice the bind(). Because this is all javascript, you can do handy things like that. We no longer need to attach data to DOM nodes in order to keep track of them.

IMO this is much cleaner than relying on DOM events.

Update April 2017: These days I would write onClick={() => this.removeTag(i)} instead of .bind

Clear variable in python

  • If want to totally delete it use del:

    del your_variable
    
  • Or otherwise, to make the value None:

    your_variable = None
    
  • If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:

    your_variable.clear()
    

Then your_variable will be empty

Sort ObservableCollection<string> through C#

I created an extension method to the ObservableCollection

public static void MySort<TSource,TKey>(this ObservableCollection<TSource> observableCollection, Func<TSource, TKey> keySelector)
    {
        var a = observableCollection.OrderBy(keySelector).ToList();
        observableCollection.Clear();
        foreach(var b in a)
        {
            observableCollection.Add(b);
        }
    }

It seems to work and you don't need to implement IComparable

Create PDF with Java

Following are few libraries to create PDF with Java:

  1. iText
  2. Apache PDFBox
  3. BFO

I have used iText for genarating PDF's with a little bit of pain in the past.

Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.

Using Gradle to build a jar with dependencies

If you want the jar task to behave normally and also have an additional fatJar task, use the following:

task fatJar(type: Jar) {
    classifier = 'all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

The important part is with jar. Without it, the classes of this project are not included.

Running multiple async tasks and waiting for them all to complete

The best option I've seen is the following extension method:

public static Task ForEachAsync<T>(this IEnumerable<T> sequence, Func<T, Task> action) {
    return Task.WhenAll(sequence.Select(action));
}

Call it like this:

await sequence.ForEachAsync(item => item.SomethingAsync(blah));

Or with an async lambda:

await sequence.ForEachAsync(async item => {
    var more = await GetMoreAsync(item);
    await more.FrobbleAsync();
});

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

Getting MAC Address

netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.

>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0', 'tun2']

>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
[{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]

Current user in Magento?

I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.

When you find the line such as "Hello <? //code for showing username?>", just copy that line and show it where you need to

How to get current working directory in Java?

this.getClass().getClassLoader().getResource("").getPath()

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

Why do we have to normalize the input for an artificial neural network?

Looking at the neural network from the outside, it is just a function that takes some arguments and produces a result. As with all functions, it has a domain (i.e. a set of legal arguments). You have to normalize the values that you want to pass to the neural net in order to make sure it is in the domain. As with all functions, if the arguments are not in the domain, the result is not guaranteed to be appropriate.

The exact behavior of the neural net on arguments outside of the domain depends on the implementation of the neural net. But overall, the result is useless if the arguments are not within the domain.

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

How to embed YouTube videos in PHP?

You can do this simple with Joomla. Let me assume a sample YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

<?php 
$youtubeUrl =  JUri::getInstance('https://www.youtube.com/watch?v=ndmXkyohT1M');
$videoId = $youtubeUrl->getVar('v'); ?>

<iframe id="ytplayer" type="text/html" width="640" height="390"  src="http://www.youtube.com/embed/<?php echo $videoId; ?>"  frameborder="0"/>

How do I remove the first characters of a specific column in a table?

The top answer is not suitable when values may have length less than 4.

In T-SQL

You will get "Invalid length parameter passed to the right function" because it doesn't accept negatives. Use a CASE statement:

SELECT case when len(foo) >= 4 then RIGHT(foo, LEN(foo) - 4) else '' end AS myfoo from mytable;

In Postgres

Values less than 4 give the surprising behavior below instead of an error, because passing negative values to RIGHT trims the first characters instead of the entire string. It makes more sense to use RIGHT(MyColumn, -5) instead.

An example comparing what you get when you use the top answer's "length - 5" instead of "-5":

create temp table foo (foo) as values ('123456789'),('12345678'),('1234567'),('123456'),('12345'),('1234'),('123'),('12'),('1'), ('');

select foo, right(foo, length(foo) - 5), right(foo, -5) from foo;

foo       len(foo) - 5  just -5   
--------- ------------  -------     
123456789 6789          6789 
12345678  678           678  
1234567   67            67   
123456    6             6    
12345                       
1234      234               
123       3                 
12                          
1                           

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

How to tell whether a point is to the right or left side of a line

Using the equation of the line ab, get the x-coordinate on the line at the same y-coordinate as the point to be sorted.

  • If point's x > line's x, the point is to the right of the line.
  • If point's x < line's x, the point is to the left of the line.
  • If point's x == line's x, the point is on the line.

How can I access my localhost from my Android device?

It is actually quite simple.

  • Turn on WiFi Hotspot of your Android phone/router and connect your Laptop to your phone
  • Start your server at localhost (I am using WAMP server for Windows)
  • Now open the command prompt and enter
ipconfig

Once you've done that, you will see something like the following:

Wireless LAN adapter Wireless Network Connection:
  Connection-specific DNS Suffix  . :
  Link-local IPv6 Address . . . . . : fe80::80bc:e378:19ab:e448%11
  IPv4 Address. . . . . . . . . . . : 192.168.43.76
  Subnet Mask . . . . . . . . . . . : 255.255.255.0
  Default Gateway . . . . . . . . . : 192.168.43.1
  • Copy the IPv4 Address (in this case, it is 192.168.43.76)
  • In your mobile browser, simply paste the IPv4 Address

Note: Please set your network as "Home Network". Setting the network as Home Network means that you are allowing your PC to share stuff with other devices on the same network.

If you are using Windows 10, this can be done with the following:

  • Open Settings
  • Go to Network & Internet
  • Select WiFi in the left menu
  • Tap on the name of the connected WiFi
  • Set the Network Profile of the network to be Private

If you are having an issue, it is most likely to do with Windows Firewall.

  • Open Control Panel
  • Go to Windows Defender Firewall
  • Tap on Allow an app or feature through Windows Defender Firewall
  • Check whether the app is enabled for Private networks (there should be a tick)
  • If it is not enabled, tap Change settings and tick the checkbox under Private for the app

Insert line break in wrapped cell via code

You could also use vbCrLf which corresponds to Chr(13) & Chr(10).

How do I iterate and modify Java Sets?

Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.

It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet implementation of java.util.Set interface satisfies your rather special requirements.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html

Python, Unicode, and the Windows console

Note: This answer is sort of outdated (from 2008). Please use the solution below with care!!


Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance):

PrintFails - Python Wiki

Here's a code excerpt from that page:

$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line'
  UTF-8
  <type 'unicode'> 2
  ?
  ?

  $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line' | cat
  None
  <type 'unicode'> 2
  ?
  ?

There's some more information on that page, well worth a read.

How to install a private NPM module without my own registry?

Config to install from public Github repository, even if machine is under firewall:

dependencies: {
   "foo": "https://github.com/package/foo/tarball/master"
}

SQL: How to to SUM two values from different tables

SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result

'And so on and so forth.

"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source

ORA-12560: TNS:protocol adaptor error

Add to the enviroment vars the following varibale and value to identify the place of the tnsnames.ora file:

TNS_ADMIN

C:\oracle\product\10.2.0\client_1\network\admin

Change the Theme in Jupyter Notebook?

To install the Jupyterthemes package directly with conda, use:

conda install -c conda-forge jupyterthemes

Then, as others have pointed out, change the theme with jt -t <theme-name>

Unzipping files in Python

from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")

The directory where you will extract your files doesn't need to exist before, you name it at this moment

YOURZIP.zip is the name of the zip if your project is in the same directory. If not, use the PATH i.e : C://....//YOURZIP.zip

Think to escape the / by an other / in the PATH If you have a permission denied try to launch your ide (i.e: Anaconda) as administrator

YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project

Try reinstalling `node-sass` on node 0.12?

I found this useful command:

npm rebuild node-sass

From the rebuild documentation:

This is useful when you install a new version of node (or switch node versions), and must recompile all your C++ addons with the new node.js binary.

http://laravel.io/forum/10-29-2014-laravel-elixir-sass-error

How do I make an asynchronous GET request in PHP?

For PHP5.5+, mpyw/co is the ultimate solution. It works as if it is tj/co in JavaScript.

Example

Assume that you want to download specified multiple GitHub users' avatars. The following steps are required for each user.

  1. Get content of http://github.com/mpyw (GET HTML)
  2. Find <img class="avatar" src="..."> and request it (GET IMAGE)

---: Waiting my response
...: Waiting other response in parallel flows

Many famous curl_multi based scripts already provide us the following flows.

        /-----------GET HTML\  /--GET IMAGE.........\
       /                     \/                      \ 
[Start] GET HTML..............----------------GET IMAGE [Finish]
       \                     /\                      /
        \-----GET HTML....../  \-----GET IMAGE....../

However, this is not efficient enough. Do you want to reduce worthless waiting times ...?

        /-----------GET HTML--GET IMAGE\
       /                                \            
[Start] GET HTML----------------GET IMAGE [Finish]
       \                                /
        \-----GET HTML-----GET IMAGE.../

Yes, it's very easy with mpyw/co. For more details, visit the repository page.

MySQL Creating tables with Foreign Keys giving errno: 150

(Side notes too big for a Comment)

There is no need for an AUTO_INCREMENT id in a mapping table; get rid of it.

Change the PRIMARY KEY to (role_id, role_group_id) (in either order). This will make accesses faster.

Since you probably want to map both directions, also add an INDEX with those two columns in the opposite order. (There is no need to make it UNIQUE.)

More tips: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta

VBA shorthand for x=x+1?

Sadly there are no operation-assignment operators in VBA.

(Addition-assignment += are available in VB.Net)

Pointless workaround;

Sub Inc(ByRef i As Integer)
   i = i + 1  
End Sub
...
Static value As Integer
inc value
inc value

add a string prefix to each value in a string column using Pandas

You can use pandas.Series.map :

df['col'].map('str{}'.format)

It will apply the word "str" before all your values.

What is polymorphism, what is it for, and how is it used?

Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:

//  Class definitions

class Fraction
{
    public $numerator;
    public $denominator;

    public function __construct($n, $d)
    {
        //  In real life, you'd do some type checking, making sure $d != 0, etc.
        $this->numerator = $n;
        $this->denominator = $d;
    }

    public function display()
    {
        echo $this->numerator . '/' . $this->denominator;
    }
}

class ComplexNumber
{
    public $real;
    public $imaginary;

    public function __construct($a, $b)
    {
        $this->real = $a;
        $this->imaginary = $b;
    }

    public function display()
    {
        echo $this->real . '+' . $this->imaginary . 'i';
    }
}


//  Main program

$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);

echo 'This is a fraction: '
$fraction->display();
echo "\n";

echo 'This is a complex number: '
$complex->display();
echo "\n";

Outputs:

This is a fraction: 1/2
This is a complex number: 1 + 2i

Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.

At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:

$userNumberChoice = $_GET['userNumberChoice'];

switch ($userNumberChoice) {
    case 'fraction':
        $userNumber = new Fraction(1, 2);
        break;
    case 'complex':
        $userNumber = new ComplexNumber(1, 2);
        break;
}

echo "The user's number is: ";
$userNumber->display();
echo "\n";

In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

Why does git status show branch is up-to-date when changes exist upstream?

"origin/master" refers to the reference poiting to the HEAD commit of branch "origin/master". A reference is a human-friendly alias name to a Git object, typically a commit object. "origin/master" reference only gets updated when you git push to your remote (http://git-scm.com/book/en/v2/Git-Internals-Git-References#Remotes).

From within the root of your project, run:

cat .git/refs/remotes/origin/master

Compare the displayed commit ID with:

cat .git/refs/heads/master

They should be the same, and that's why Git says master is up-to-date with origin/master.

When you run

git fetch origin master

That retrieves new Git objects locally under .git/objects folder. And Git updates .git/FETCH_HEAD so that now, it points to the latest commit of the fetched branch.

So to see the differences between your current local branch, and the branch fetched from upstream, you can run

git diff HEAD FETCH_HEAD

How to create a zip file in Java

If you want decompress without software better use this code. Other code with pdf files sends error on manually decompress

byte[] buffer = new byte[1024];     
    try
    {   
        FileOutputStream fos = new FileOutputStream("123.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze= new ZipEntry("file.pdf");
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream("file.pdf");
        int len;
        while ((len = in.read(buffer)) > 0) 
        {
            zos.write(buffer, 0, len);
        }
        in.close();
        zos.closeEntry();
        zos.close();
    }
    catch(IOException ex)
    {
       ex.printStackTrace();
    }

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

How to uninstall a windows service and delete its files without rebooting

Are you not able to stop the service before the update (and restart after the update) using the commands below?

net stop <service name>
net start <service name>

Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped. I'm not sure if the issue you are having is different.

How do detect Android Tablets in general. Useragent?

Xoom has the word Xoom in the user-agent: Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; Xoom Build/HRI66) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13

Galaxy Tab has "Mobile" in the user-agent: Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

So, it's easy to detect the Xoom, hard to detect if a specific Android version is mobile or not.

Reloading module giving NameError: name 'reload' is not defined

To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:

try:
    reload  # Python 2.7
except NameError:
    try:
        from importlib import reload  # Python 3.4+
    except ImportError:
        from imp import reload  # Python 3.0 - 3.3

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

Resize Cross Domain Iframe Height

It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.

https://github.com/davidjbradshaw/iframe-resizer

It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.

Works in all modern browsers and IE8 upwards.

How can I divide two integers to get a double?

Convert one of them to a double first. This form works in many languages:

 real_result = (int_numerator + 0.0) / int_denominator

Query based on multiple where clauses in Firebase

I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.

Meet Querybase!

Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).

const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);

// Automatically handles composite keys
querybaseRef.push({ 
  name: 'David',
  age: 27,
  location: 'SF'
});

// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
 .where({
   name: 'David',
   age: 27
 });

// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));

Find out the history of SQL queries

You can use this sql statement to get the history for any date:

SELECT * FROM V$SQL V where  to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60

Convert string into integer in bash script - "Leading Zero" number error

See ARITHMETIC EVALUATION in man bash:

Constants with a leading 0 are interpreted as octal numbers.

You can remove the leading zero by parameter expansion:

hour=${hour#0}

or force base-10 interpretation:

$((10#$hour + 1))

Plotting a 2D heatmap with Matplotlib

The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

How to run cron job every 2 hours

The line should read either:

0 0-23/2 * * * /home/username/test.sh

or

0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

In nodeJs is there a way to loop through an array without using array size?

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Given a class, see if instance has method (Ruby)

You can use method_defined? as follows:

String.method_defined? :upcase # => true

Much easier, portable and efficient than the instance_methods.include? everyone else seems to be suggesting.

Keep in mind that you won't know if a class responds dynamically to some calls with method_missing, for example by redefining respond_to?, or since Ruby 1.9.2 by defining respond_to_missing?.

Load a UIView from nib in Swift

Swift 4 - 5.1 Protocol Extensions

public protocol NibInstantiatable {
    
    static func nibName() -> String
    
}

extension NibInstantiatable {
    
    static func nibName() -> String {
        return String(describing: self)
    }
    
}

extension NibInstantiatable where Self: UIView {
    
    static func fromNib() -> Self {
        
        let bundle = Bundle(for: self)
        let nib = bundle.loadNibNamed(nibName(), owner: self, options: nil)
        
        return nib!.first as! Self
        
    }
    
}

Adoption

class MyView: UIView, NibInstantiatable {

}

This implementation assumes that the Nib has the same name as the UIView class. Ex. MyView.xib. You can modify this behavior by implementing nibName() in MyView to return a different name than the default protocol extension implementation.

In the xib the files owner is MyView and the root view class is MyView.

Usage

let view = MyView.fromNib()

PDF Blob - Pop up window not showing content

I ended up just downloading my pdf using below code

function downloadPdfDocument(fileName){

var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";

req.onload = function (event) {

    var blob = req.response;

    //for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    }
};

req.send();

}

Rails - How to use a Helper Inside a Controller

In Rails 5 use the helpers.helper_function in your controller.

Example:

def update
  # ...
  redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end

Source: From a comment by @Markus on a different answer. I felt his answer deserved it's own answer since it's the cleanest and easier solution.

Reference: https://github.com/rails/rails/pull/24866

Sorting object property by values

ECMAScript 2017 introduces Object.values / Object.entries. As the name suggests, the former aggregates all the values of an object into an array, and the latter does the whole object into an array of [key, value] arrays; Python's equivalent of dict.values() and dict.items().

The features make it pretty easier to sort any hash into an ordered object. As of now, only a small portion of JavaScript platforms support them, but you can try it on Firefox 47+.

EDIT: Now supported by all modern browsers!

let obj = {"you": 100, "me": 75, "foo": 116, "bar": 15};

let entries = Object.entries(obj);
// [["you",100],["me",75],["foo",116],["bar",15]]

let sorted = entries.sort((a, b) => a[1] - b[1]);
// [["bar",15],["me",75],["you",100],["foo",116]]

Command to open file with git

You can use the git command line as a terminal my dude you just know the commands are bash To create a file

touch file.txt

To open a file

code file.py 
atom file.py
start file.py

ect

To open your current folder and everything inside of it in your text editor

code . 

To make a folder

mkdir folder1 folder2 folder3 

You can make as many as you want at once this works with touch to

Save internal file in my own internal folder in Android

First Way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Second way:

You created an empty file with the desired name, which then prevented you from creating the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Third way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Fourth Way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Fifth way:

You didn't create the directory. Also, you are passing an absolute path to openFileOutput(), which is wrong.

Correct way:

  1. Create a File for your desired directory (e.g., File path=new File(getFilesDir(),"myfolder");)
  2. Call mkdirs() on that File to create the directory if it does not exist
  3. Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
  4. Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))

How do I convert from int to Long in Java?

Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :

public  static  long  integerToLong (int minute ){
    int delay = minute*1000;
    long diff = (long) delay;
    return  diff ; 
}

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

When to choose mouseover() and hover() function?

As you can read at http://api.jquery.com/mouseenter/

The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

How to implement my very own URI scheme on Android

As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.

Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here

Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

GitHub Error Message - Permission denied (publickey)

Using Https is fine, run git config --global credential.helper wincred to create a Github credential helper that stores your credentials for you. If this doesn't work, then you need to edit your config file in your .git directory and update the origin to the https url.

See this link for the github docs.

How to create a folder with name as current date in batch (.bat) files

For YYYY.MM.DD format with HUN settings use following. It converts "2021. 02. 23." to "2021.02.23":

SET dirname="%date:~0,5%%date:~6,3%%date:~10,2%"
md %dirname%

How to test if a string is basically an integer in quotes using Ruby

You can use Integer(str) and see if it raises:

def is_num?(str)
  !!Integer(str)
rescue ArgumentError, TypeError
  false
end

It should be pointed out that while this does return true for "01", it does not for "09", simply because 09 would not be a valid integer literal. If that's not the behaviour you want, you can add 10 as a second argument to Integer, so the number is always interpreted as base 10.

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]

for Int32 -- (-2,147,483,648 to 2,147,483,647)

How to display Oracle schema size with SQL query?

You probably want

SELECT sum(bytes)
  FROM dba_segments
 WHERE owner = <<owner of schema>>

If you are logged in as the schema owner, you can also

SELECT SUM(bytes)
  FROM user_segments

That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.

How to find the last day of the month from date?

You can also use it with datetime

$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

On Windows Powershell:

$env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL-Win64\bin\openssl.cfg"

How do I seed a random class to avoid getting duplicate random values

this workes for me:

private int GetaRandom()
    {
        Thread.Sleep(1);
        return new Random(DateTime.Now.Millisecond).Next();
    }

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Check if xdebug is working

If you are using Eclipse then please note that while running on XDebug mode the magic constant __FILE__ will always be evaluated to:

xdebug://debug-eval

So the following check will return true if your session is under XDebug:

$is_xdebug = false !== strpos(__FILE__,'xdebug'); // true while on XDebug

What does "hashable" mean in Python?

In my understanding according to Python glossary, when you create a instance of objects that are hashable, an unchangeable value is also calculated according to the members or values of the instance. For example, that value could then be used as a key in a dict as below:

>>> tuple_a = (1,2,3)
>>> tuple_a.__hash__()
2528502973977326415
>>> tuple_b = (2,3,4)
>>> tuple_b.__hash__()
3789705017596477050
>>> tuple_c = (1,2,3)
>>> tuple_c.__hash__()
2528502973977326415
>>> id(a) == id(c)  # a and c same object?
False
>>> a.__hash__() == c.__hash__()  # a and c same value?
True
>>> dict_a = {}
>>> dict_a[tuple_a] = 'hiahia'
>>> dict_a[tuple_c]
'hiahia'

we can find that the hash value of tuple_a and tuple_c are the same since they have the same members. When we use tuple_a as the key in dict_a, we can find that the value for dict_a[tuple_c] is the same, which means that, when they are used as the key in a dict, they return the same value because the hash values are the same. For those objects that are not hashable, the method hash is defined as None:

>>> type(dict.__hash__) 
<class 'NoneType'>

I guess this hash value is calculated upon the initialization of the instance, not in a dynamic way, that's why only immutable objects are hashable. Hope this helps.

Making a cURL call in C#

Or in restSharp:

var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Javascript swap array elements

var a = [1,2,3,4,5], b=a.length;

for (var i=0; i<b; i++) {
    a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];

How to convert .pfx file to keystore with private key?

jarsigner can use your pfx file as the keystore for signing your jar. Be sure that your pfx file has the private key and the cert chain when you export it. There is no need to convert to other formats. The trick is to obtain the Alias of your pfx file:

 keytool -list -storetype pkcs12 -keystore your_pfx_file -v | grep Alias

Once you have your alias, signing is easy

jarsigner.exe -storetype pkcs12 -keystore pfx_file jar_file "your alias"

The above two commands will prompt you for the password you specified at pfx export. If you want to have your password hang out in clear text use the -storepass switch before the -keystore switch

Once signed, admire your work:

jarsigner.exe -verify -verbose -certs  yourjarfile

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

find the array index of an object with a specific key value in underscore

If you're expecting multiple matches and hence need an array to be returned, try:

_.where(Users, {age: 24})

If the property value is unique and you need the index of the match, try:

_.findWhere(Users, {_id: 10})

Intellij JAVA_HOME variable

Bit counter-intuitive, but you must first setup a SDK for Java projects. On the bottom right of the IntelliJ welcome screen, select 'Configure > Project Defaults > Project Structure'.

The Project tab on the left will show that you have no SDK selected:

Therefore, you must click the 'New...' button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should be populated with your JAVA_HOME variable, providing you have this set.

Is there an equivalent of CSS max-width that works in HTML emails?

Bit late to the party, but this will get it done. I left the example at 600, as that is what most people will use:

Similar to Shay's example except this also includes max-width to work on the rest of the clients that do have support, as well as a second method to prevent the expansion (media query) which is needed for Outlook '11.

In the head:

  <style type="text/css">
    @media only screen and (min-width: 600px) { .maxW { width:600px !important; } }
  </style>

In the body:

<!--[if (gte mso 9)|(IE)]><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<div class="maxW" style="max-width:600px;">

<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
  <tr>
    <td>
main content here
    </td>
  </tr>
</table>

</div>
<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->

Here is another example of this in use: Responsive order confirmation emails for mobile devices?

How to fix libeay32.dll was not found error

I've encountered this kind of problem before. I was using the Windows x64 operating system, so I was getting an error in openssl. Later I realized that the path to the OpenSSL installation file was "C: \ OpenSSL win32". Finally, I deleted the OpenSSL program and installed it to "C: \ Program Files (x86)" and used it smoothly.

Counting the occurrences / frequency of array elements

var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
  if (typeof acc[curr] == 'undefined') {
    acc[curr] = 1;
  } else {
    acc[curr] += 1;
  }

  return acc;
}, {});

// a == {2: 5, 4: 1, 5: 3, 9: 1}

Calculate the center point of multiple latitude/longitude coordinate pairs

I found this post very useful so here is the solution in PHP. I've been using this successfully and just wanted to save another dev some time.

/**
 * Get a center latitude,longitude from an array of like geopoints
 *
 * @param array data 2 dimensional array of latitudes and longitudes
 * For Example:
 * $data = array
 * (
 *   0 = > array(45.849382, 76.322333),
 *   1 = > array(45.843543, 75.324143),
 *   2 = > array(45.765744, 76.543223),
 *   3 = > array(45.784234, 74.542335)
 * );
*/
function GetCenterFromDegrees($data)
{
    if (!is_array($data)) return FALSE;

    $num_coords = count($data);

    $X = 0.0;
    $Y = 0.0;
    $Z = 0.0;

    foreach ($data as $coord)
    {
        $lat = $coord[0] * pi() / 180;
        $lon = $coord[1] * pi() / 180;

        $a = cos($lat) * cos($lon);
        $b = cos($lat) * sin($lon);
        $c = sin($lat);

        $X += $a;
        $Y += $b;
        $Z += $c;
    }

    $X /= $num_coords;
    $Y /= $num_coords;
    $Z /= $num_coords;

    $lon = atan2($Y, $X);
    $hyp = sqrt($X * $X + $Y * $Y);
    $lat = atan2($Z, $hyp);

    return array($lat * 180 / pi(), $lon * 180 / pi());
}

Android eclipse DDMS - Can't access data/data/ on phone to pull files

No one seems to understand that a retail Nexus One even after being rooted still will not let you browse the file system using DDMS File Explorer. We are talking about real phones here and not the emulator. If you happen to have a Nexus One Developer Phone you can browse the file system using DDMS Filer Explorer, but a retail Nexus One that has been rooted you can't. Got it?

So I hope that answers the question of not being able to use the DDMS File Explorer to browse the file system of a rooted retail Nexus One. After rooting a retail Nexus One there is still something that remains to be done to use DDMS to use the File Explorer to browse the phones File System. I don't know what it is. Maybe someone else knowns.

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

What is the best way to parse html in C#?

The trouble with parsing HTML is that it isn't an exact science. If it was XHTML that you were parsing, then things would be a lot easier (as you mention you could use a general XML parser). Because HTML isn't necessarily well-formed XML you will come into lots of problems trying to parse it. It almost needs to be done on a site-by-site basis.

how to concatenate two dictionaries to create a new one in Python?

Use the dict constructor

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

As a function

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

The overhead of creating intermediate dictionaries can be eliminated by using thedict.update() method:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})

TextFX menu is missing in Notepad++

For 32 bit Notepad++ only

Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.

It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

In my case I was trying to pass a command to a container. In which case only the first word was interpreted. Ensure that you're not running:

mysql

as opposed to:

mysql -uroot -ppassword schemaname

perhaps try quoting:

'mysql -uroot -ppassword schemaname'

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

How to find files that match a wildcard string in Java?

As posted in another answer, the wildcard library works for both glob and regex filename matching: http://code.google.com/p/wildcard/

I used the following code to match glob patterns including absolute and relative on *nix style file systems:

String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
    baseDir = File.separator;
    filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();

I spent some time trying to get the FileUtils.listFiles methods in the Apache commons io library (see Vladimir's answer) to do this but had no success (I realise now/think it can only handle pattern matching one directory or file at a time).

Additionally, using regex filters (see Fabian's answer) for processing arbitrary user supplied absolute type glob patterns without searching the entire file system would require some preprocessing of the supplied glob to determine the largest non-regex/glob prefix.

Of course, Java 7 may handle the requested functionality nicely, but unfortunately I'm stuck with Java 6 for now. The library is relatively minuscule at 13.5kb in size.

Note to the reviewers: I attempted to add the above to the existing answer mentioning this library but the edit was rejected. I don't have enough rep to add this as a comment either. Isn't there a better way...

Using margin:auto to vertically-align a div

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background:yellow;
    width:200px;
    padding:10px;
}

 - 


----------


<div class="black">
<div class="message">
    This is a popup message.
</div>

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Actually, vim does allow what you're looking for. Enter vim, and type the following commands:

:args **/*.java
:argdo set ff=unix | update | next

The first of these commands sets the argument list to every file matching **/*.java, which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:

  • Sets the line-endings to Unix style (you already know this)
  • Writes the file out iff it's been changed
  • Proceeds to the next file

How to install mechanize for Python 2.7?

You need the actual package (the directory containing __init__.py) stored somewhere that's in your system's PYTHONPATH. Normally, packages are distributed with a directory above the package directory, containing setup.py (which you should use to install the package), documentation, etc. This directory is not a package. Additionally, your Python27 directory is probably not in PYTHONPATH; more likely one or more subdirectories of it are.

How can I align YouTube embedded video in the center in bootstrap

<iframe style="display: block; margin: auto;" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen></iframe>

How to do SQL Like % in Linq?

Use such code

try
{
    using (DatosDataContext dtc = new DatosDataContext())
    {
        var query = from pe in dtc.Personal_Hgo
                    where SqlMethods.Like(pe.nombre, "%" + txtNombre.Text + "%")
                    select new
                    {
                        pe.numero
                        ,
                        pe.nombre
                    };
        dgvDatos.DataSource = query.ToList();
    }
}
catch (Exception ex)
{
    string mensaje = ex.Message;
}

Can I specify multiple users for myself in .gitconfig?

Maybe it is a simple hack, but it is useful. Just generate 2 ssh keys like below.

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/GowthamSai/.ssh/id_rsa): work
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in damsn.
Your public key has been saved in damsn.pub.
The key fingerprint is:
SHA256:CrsKDJWVVek5GTCqmq8/8RnwvAo1G6UOmQFbzddcoAY [email protected]
The key's randomart image is:
+---[RSA 4096]----+
|. .oEo+=o+.      |
|.o o+o.o=        |
|o o o.o. +       |
| =.+ .  =        |
|= *+.   S.       |
|o*.++o .         |
|=.oo.+.          |
| +. +.           |
|.o=+.            |
+----[SHA256]-----+

Same way create one more for personal. So, you have 2 ssh keys, work and company. Copy work.pub, work, personal.pub, personal to ~/.ssh/ Directory.

Then create a shell script with the following lines and name it as crev.sh (Company Reverse) with the following content.

cp ~/.ssh/work ~/.ssh/id_rsa
cp ~/.ssh/work.pub ~/.ssh/id_rsa.pub

Same way, create one more called prev.sh (Personal Reverse) with the following content.

cp ~/.ssh/personal ~/.ssh/id_rsa
cp ~/.ssh/personal.pub ~/.ssh/id_rsa.pub

in ~/.bashrc add aliases for those scripts like below

alias crev="sh ~/.ssh/crev.sh"
alias prev="sh ~/.ssh/prev.sh"
source ~/.bashrc

Whenever you wanna use company, just do crev, and if you wanna use personal do prev :-p.

Add those ssh keys to your GitHub accounts. Make sure, you don't have id_rsa generated previously, because those scripts will overwrite id_rsa. If you have already generated id_rsa, use that for one of the accounts. Copy them as personal and skip the generation of personal keys.

How to Check byte array empty or not?

Just do

if (Attachment != null  && Attachment.Length > 0)

From && Operator

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

I am using Debian but this solution should work fine with Ubuntu.
You have to add a line in the neo4j-service script.
Here is what I have done :

nano /etc/init.d/neo4j-service
Add « ulimit –n 40000 » just before the start-stop-daemon line in the do_start section

Note that I am using version 2.0 Enterprise edition. Hope this will help you.

Linux Process States

Yes, the task gets blocked in the read() system call. Another task which is ready runs, or if no other tasks are ready, the idle task (for that CPU) runs.

A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.

Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.

Splitting a continuous variable into equal sized groups

Or see cut_number from the ggplot2 package, e.g.

das$wt_2 <- as.numeric(cut_number(das$wt,3))

Note that cut(...,3) divides the range of the original data into three ranges of equal lengths; it doesn't necessarily result in the same number of observations per group if the data are unevenly distributed (you can replicate what cut_number does by using quantile appropriately, but it's a nice convenience function). On the other hand, Hmisc::cut2() using the g= argument does split by quantiles, so is more or less equivalent to ggplot2::cut_number. I might have thought that something like cut_number would have made its way into dplyr by so far, but as far as I can tell it hasn't.

How to format a QString?

You can use the sprintf method, however the arg method is preferred as it supports unicode.

QString str;
str.sprintf("%s %d", "string", 213);

Centering in CSS Grid

Try using flex:

Plunker demo : https://plnkr.co/edit/nk02ojKuXD2tAqZiWvf9

/* Styles go here */

html,
body {
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 100vh;
  grid-gap: 0px 0px;
}

.left_bg {
  background-color: #3498db;
  grid-column: 1 / 1;
  grid-row: 1 / 1;
  z-index: 0;
  display: flex;
  justify-content: center;
  align-items: center;

}

.right_bg {
  background-color: #ecf0f1;
  grid-column: 2 / 2;
  grid_row: 1 / 1;
  z-index: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.text {
  font-family: Raleway;
  font-size: large;
  text-align: center;
}

HTML

    <div class="container">
  <!--everything on the page-->

  <div class="left_bg">
    <!--left background color of the page-->
    <div class="text">
      <!--left side text content-->
      <p>Review my stuff</p>
    </div>
  </div>

  <div class="right_bg">
    <!--right background color of the page-->
    <div class="text">
      <!--right side text content-->
      <p>Hire me!</p>
    </div>
  </div>
</div>

Trying to merge 2 dataframes but get ValueError

this simple solution works for me

    final = pd.concat([df, rankingdf], axis=1, sort=False)

but you may need to drop some duplicate column first.

Get the last three chars from any string - Java

Why not just String substr = word.substring(word.length() - 3)?

Update

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has less than 3 characters!");
}

CSS transition between left -> right and top -> bottom positions

This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

topleft {
  top: 0%;
  left: 0%;
}
bottomright {
  top: 100%;
  left: 100%;
  -webkit-transform: translate(-100%,-100%);
}

Dump all tables in CSV format using 'mysqldump'

You also can do it using Data Export tool in dbForge Studio for MySQL.

It will allow you to select some or all tables and export them into CSV format.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Using the "start" command with parameters passed to the started program

You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.

    start  /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

or:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

will start IE with default web page.

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com

starts with Bing, but does not reset your home page.

/D stands for "directory" and using quotes is OK!

WRONG EXAMPLE:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE"

gives:

ERROR "The current directory is invalid."

/D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run

Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.

-Mrbios

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

jQuery: how to get which button was clicked upon form submission?

Similar to Stan answer but :

  • if you have more than one button, you have to get only the first button => [0]
  • if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId

$(document).on('submit', function(event) {
    event.preventDefault();
    var pressedButtonId = 
         typeof $(":input[type=submit]:focus")[0] === "undefined" ? 
         "myDefaultButtonId" :
         $(":input[type=submit]:focus")[0].id;
    ...
 }

jQuery Ajax Request inside Ajax Request

Here is an example:

$.ajax({
        type: "post",
        url: "ajax/example.php",
        data: 'page=' + btn_page,
        success: function (data) {
            var a = data; // This line shows error.
            $.ajax({
                type: "post",
                url: "example.php",
                data: 'page=' + a,
                success: function (data) {

                }
            });
        }
    });

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

Get string between two strings in a string

var matches = Regex.Matches(input, @"(?<=key :)(.+?)(?=-)");

This returns only the value(s) between "key :" and the following occurance of "-"

What is a raw type and why shouldn't we use it?

Here I am Considering multiple cases through which you can clearify the concept

1. ArrayList<String> arr = new ArrayList<String>();
2. ArrayList<String> arr = new ArrayList();
3. ArrayList arr = new ArrayList<String>();

Case 1

ArrayList<String> arr it is a ArrayList reference variable with type String which reference to a ArralyList Object of Type String. It means it can hold only String type Object.

It is a Strict to String not a Raw Type so, It will never raise an warning .

    arr.add("hello");// alone statement will compile successfully and no warning.

    arr.add(23);  //prone to compile time error.
     //error: no suitable method found for add(int)

Case 2

In this case ArrayList<String> arr is a strict type but your Object new ArrayList(); is a raw type.

    arr.add("hello"); //alone this compile but raise the warning.
    arr.add(23);  //again prone to compile time error.
    //error: no suitable method found for add(int)

here arr is a Strict type. So, It will raise compile time error when adding a integer.

Warning :- A Raw Type Object is referenced to a Strict type Referenced Variable of ArrayList.

Case 3

In this case ArrayList arr is a raw type but your Object new ArrayList<String>(); is a Strict type.

    arr.add("hello");  
    arr.add(23);  //compiles fine but raise the warning.

It will add any type of Object into it because arr is a Raw Type.

Warning :- A Strict Type Object is referenced to a raw type referenced Variable.

How to calculate the IP range when the IP address and the netmask is given?

my good friend Alessandro have a nice post regarding bit operators in C#, you should read about it so you know what to do.

It's pretty easy. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.

For example:

ip 192.168.33.72 mask 255.255.255.192

11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)

The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:

11000000.10101000.00100001.01000000 (192.168.33.64)

If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):

11000000.10101000.00100001.01111111 (192.168.33.127)

So for my example:

the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

FormsAuthentication.SignOut() does not log the user out

I have been writing a base class for all of my Pages and I came to the same issue. I had code like the following and It didn't work. By tracing, control passes from RedirectToLoginPage() statement to the next line without to be redirected.

if (_requiresAuthentication)
{
    if (!User.Identity.IsAuthenticated)
        FormsAuthentication.RedirectToLoginPage();

    // check authorization for restricted pages only
    if (_isRestrictedPage) AuthorizePageAndButtons();
}

I found out that there are two solutions. Either to modify FormsAuthentication.RedirectToLoginPage(); to be

if (!User.Identity.IsAuthenticated)
    Response.Redirect(FormsAuthentication.LoginUrl);

OR to modify the web.config by adding

<authorization>
  <deny users="?" />
</authorization>

In the second case, while tracing, control didn't reach the requested page. It has been redirected immediately to the login url before hitting the break point. Hence, The SignOut() method isn't the issue, the redirect method is the one.

I hope that may help someone

Regards

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

Draw path between two points using Google Maps Android API v2

Dont know whether I should put this as answer or not...

I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..

going through some other question over SO, I had the following solution

I add the following function in Zeeshan's class

 public void clearRoute(){

         for(Polyline line1 : polylines)
         {
             line1.remove();
         }

         polylines.clear();

     }

in my map activity, before drawing the path, I called this function.. example usage as per my app is

private Route rt;

rt.clearRoute();

            if (src == null) {
                Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
            }else if (Destination == null) {
                Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
            }else if (src.equals(Destination)) {
                Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
            }else{

                rt.drawRoute(mMap, MapsMainActivity.this, src,
                        Destination, false, "en");
            }

you can use rt.clearRoute(); as per your requirements.. Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..

Complete Class Code

see on github

Edit: here is part of code from mainactivity..

case R.id.mkrbtn_set_dest:
                    Destination = selmarker.getPosition();
                    destmarker = selmarker;
                    desShape = createRouteCircle(Destination, false);

                    if (src == null) {
                        Toast.makeText(getApplicationContext(),
                                "Please select your Source first...",
                                Toast.LENGTH_LONG).show();
                    } else if (src.equals(Destination)) {
                        Toast.makeText(getApplicationContext(),
                                "Source and Destinatin can not be the same..",
                                Toast.LENGTH_LONG).show();
                    } else {

                        if (isNetworkAvailable()) {
                            rt.drawRoute(mMap, MapsMainActivity.this, src,
                                    Destination, false, "en");
                            src = null;
                            Destination = null;

                        } else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Internet Connection seems to be OFFLINE...!",
                                    Toast.LENGTH_LONG).show();

                        }

                    }

                    break;

Edit 2 as per comments

usage :

//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned

rt.drawRoute(mMap, MapsMainActivity.this, src,
                            Destination, false, "en");

How to split long commands over multiple lines in PowerShell

Another way to break a string across multiple lines is to put an empty expression in the middle of the string, and break it across lines:

sample string:

"stackoverflow stackoverflow stackoverflow stackoverflow stackoverflow"

broken across lines:

"stackoverflow stackoverflow $(
)stackoverflow stack$(
)overflow stackoverflow"

What are intent-filters in Android?

First change the xml, mark your second activity as DEFAULT

<activity android:name=".AddNewActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Now you can initiate this activity using StartActivity method.

Python non-greedy regexes

To start with, I do not suggest using "*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the + sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the {x, y} syntax to specifically specify the desired length.

However, if you really do need non-greedy repetition, I suggest consulting the all-powerful ?. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible.

That being said, I would be very careful with the ? as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify ((1) (note the lack of a second rparen) as a match.

Creating a dynamic choice field

Underneath working solution with normal choice field. my problem was that each user have their own CUSTOM choicefield options based on few conditions.

class SupportForm(BaseForm):

    affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))

    def __init__(self, *args, **kwargs):

        self.request = kwargs.pop('request', None)
        grid_id = get_user_from_request(self.request)
        for l in get_all_choices().filter(user=user_id):
            admin = 'y' if l in self.core else 'n'
            choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
            self.affiliated_choices.append(choice)
        super(SupportForm, self).__init__(*args, **kwargs)
        self.fields['affiliated'].choices = self.affiliated_choice

Inject service in app.config

Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.

See this question and answer: AngularJS dependency injection of value inside of module.config

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Java: How to read a text file

Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
    list.add(Integer.valueOf(s));
}

Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)

What's the most appropriate HTTP status code for an "item not found" error page

204:

No Content.” This code means that the server has successfully processed the request, but is not going to return any content

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

How do I "select Android SDK" in Android Studio?

In my case there there is no selected java sdk version in project structure-

I had to select the -

1.Source Compatibility (1.7)

2.Target Compatibility (1.7)

as shown in image.

enter image description here

How to remove undefined and null values from an object using lodash?

For deep nested object you can use my snippet for lodash > 4

const removeObjectsWithNull = (obj) => {
    return _(obj)
      .pickBy(_.isObject) // get only objects
      .mapValues(removeObjectsWithNull) // call only for values as objects
      .assign(_.omitBy(obj, _.isObject)) // save back result that is not object
      .omitBy(_.isNil) // remove null and undefined from object
      .value(); // get value
};

Rename file with Git

You've got "Bad Status" its because the target file cannot find or not present, like for example you call README file which is not in the current directory.

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

Return 0 if field is null in MySQL

Yes IFNULL function will be working to achieve your desired result.

SELECT uo.order_id, uo.order_total, uo.order_status,
        (SELECT IFNULL(SUM(uop.price * uop.qty),0) 
         FROM uc_order_products uop 
         WHERE uo.order_id = uop.order_id
        ) AS products_subtotal,
        (SELECT IFNULL(SUM(upr.amount),0) 
         FROM uc_payment_receipts upr 
         WHERE uo.order_id = upr.order_id
        ) AS payment_received,
        (SELECT IFNULL(SUM(uoli.amount),0) 
         FROM uc_order_line_items uoli 
         WHERE uo.order_id = uoli.order_id
        ) AS line_item_subtotal
        FROM uc_orders uo
        WHERE uo.order_status NOT IN ("future", "canceled")
        AND uo.uid = 4172;