Programs & Examples On #Sp rename

SQL Joins Vs SQL Subqueries (Performance)?

You can use an Explain Plan to get an objective answer.

For your problem, an Exists filter would probably perform the fastest.

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

How do I create a sequence in MySQL?

By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html

Only Add Unique Item To List

//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();

var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash

//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();

dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);

manage.py runserver

For people who are using CentOS7, In order to allow access to port 8000, you need to modify firewall rules in a new SSH connection:

sudo firewall-cmd --zone=public --permanent --add-port=8000/tcp
sudo firewall-cmd --reload

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

HTTP Error 404 when running Tomcat from Eclipse

If you changed the location, using option 'Use custom location (does not modify Tomcat installation)' and the deployed directory is "wtpwebapps" then you'll have to:

  1. Swtich Location from [workspace metadata] to /Servers/Tomcat v...., click Apply, OK.
  2. Retart server and if you find 404 error message than the server is working, it just doesn't have the startup file at the web-server location you have chosen. If you traverse to that location, you'll find a bunch of directories that was created. One of which is wtpwebapps, under which there is ROOT. This is your web-server's directory. You will need to go back to installed Tomcat directory and copy the content of <tomcat's installed dir>/web-apps/ROOT to your wtpwebapps. Restart the webserver and you should see the tomcat default page.
  3. For Server Status, Manager Apps and Host Manager to work, you'll have to copy other subdirectories from <tomcat's installed dir>/webapps (ie. docs, examples, host-manager, manager) to your "webapps" (NOT the wtpwebapps) directory.
  4. Edit the '<your web directory>/conf/tomcat-users.xml' and enter something like:
  5.       <role rolename="manager-gui"/>
          <role rolename="manager-status"/>
          <role rolename="manager-jmx"/>
          <role rolename="manager-script"/>
          <role rolename="admin-gui"/>
          <role rolename="admin"/>
          <user username="admin" password="yourpassword" roles="admin, admin-gui, manager-gui"/>
        
  6. Then edit the '<your web directory>/conf/server.xml', add the attribute:
            readonly="true"
        
    into the <Resource/> key of the <GlobalNamingResources/> group.
  7. Restart the server and try to login with the configured credentials.
NOTE: if you change the server configuration, say if you like to compare the default configuration (use tomcat installation directory) and the 'new directory', when switching back to the 'new directory' this 'tomcat-users.xml' will be overwritten by the default file, so SAVE THE CONTENT OF THIS FILE somewhere before doing that, then copy it back. If you only give the the username "admin" role, you will be prompted of help messages. It says: you should not grant the admin-gui, or manager-gui role the 'manager-jmx' and 'manager-script' roles.

Wavy shape with css

My pure CSS implementation based on above with 100% width. Hope it helps!

_x000D_
_x000D_
#wave-container {_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 40px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  right: -25%;_x000D_
  top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: black;_x000D_
  left: -25%;_x000D_
  top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
  <div id="wave">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to move all files including hidden files into parent directory via *

Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.

$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. ..  .den  .hi .hidden a b c

$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c

$ shopt -s dotglob
$ ls *
.den  .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c

It defaults to "off".

$ shopt dotglob
dotglob         off

It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.

Changing password with Oracle SQL Developer

I confirmed this works in SQL Developer 3.0.04. Our passwords are required to have a special character, so the double-quoted string is needed in our case. Of course, this only works if the password has not already expired and you are currently logged in.

ALTER USER MYUSERID
IDENTIFIED BY "new#password"
REPLACE "old#password"

Random date in C#

Useful extension based of @Jeremy Thompson's solution

public static class RandomExtensions
{
    public static DateTime Next(this Random random, DateTime start, DateTime? end = null)
    {
        end ??= new DateTime();
        int range = (end.Value - start).Days;
        return start.AddDays(random.Next(range));
    }
}

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Import and Export Excel - What is the best library?

Spreadsheetgear is the best commercial library we have found and are using. Our company does a lot of advanced excel import and export and Spreadsheetgear supports lots of advanced excel features far beyond anything you can do with simple CSV, and it's fast. It isn't free or very cheap though but worth it because the support is excellent. The developers will actually respond to you if you run into an issue.

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

How to change color of Toolbar back button in Android?

I think if theme should be generated some problem but its dynamically set black arrow.So i Suggested try this one.

Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
backArrow.setColorFilter(getResources().getColor(R.color.md_grey_900), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(backArrow);

regular expression for Indian mobile numbers

This is worked for me using JAVA script for chrome extension.

document.body.innerHTML = myFunction();
function myFunction()
{
    var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");

    var str = document.body.innerHTML; 
    var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});

    return res;
}

This covers following numbers pattern

9883443344
8888564723 
7856128945

09883443344 
0 9883443344 
0-9883443344

919883443344 
91 8834433441 
91-9883443344 
91 -9883443344 
91- 9883443344 
91 - 9883443344 
91 -9883443344

+917878525200 
+91 8834433441 
+91-9883443344 
+91 -9883443344 
+91- 9883443344 
+91 - 9883443344 
+91 -9883443344

0919883443344 
0091-7779015989 
0091 - 8834433440 
022-24130000 
080 25478965 
0416-2565478 
08172-268032 
04512-895612 
02162-240000 
022-24141414 
079-22892350

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

How to select all the columns of a table except one column?

I just wanted to echo @Luann's comment as I use this approach always.

Just right click on the table > Script table as > Select to > New Query window.

You will see the select query. Just take out the column you want to exclude and you have your preferred select query. enter image description here

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:

someString.matches("[A-F]");

For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

I had similar problem with integer column as input when I needed fixed sized varchar (or string) output. For instance, 1 to '01', 12 to '12'. This code works:

SELECT RIGHT(CONCAT('00',field::text),2)

If the input is also a column of varchar, you can avoid the casting part.

Get a particular cell value from HTML table using JavaScript

You can get cell value with JS even when click on the cell:

.......................

      <head>

        <title>Search students by courses/professors</title>

        <script type="text/javascript">

        function ChangeColor(tableRow, highLight)
        {
           if (highLight){
               tableRow.style.backgroundColor = '00CCCC';
           }

        else{
             tableRow.style.backgroundColor = 'white';
            }   
      }

      function DoNav(theUrl)
      {
      document.location.href = theUrl;
      }
      </script>

    </head>
    <body>

         <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

                <% for (Course cs : courses){ %>

                <tr onmouseover="ChangeColor(this, true);" 
                    onmouseout="ChangeColor(this, false);" 
                    onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                     <td name = "title" align = "center"><%= cs.getTitle() %></td>

                </tr>
               <%}%>

    ........................
    </body>

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.

I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.

The example is working.I've seen.

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

How do I schedule a task to run at periodic intervals?

timer.scheduleAtFixedRate( new Task(), 1000,3000); 

What are the recommendations for html <base> tag?

The hash "#" currently works for jump links in conjunction with the base element, but only in the latest versions of Google Chrome and Firefox, NOT IE9.

IE9 appears to cause the page to be reloaded, without jumping anywhere. If you are using jump links on the outside of an iframe, while directing the frame to load the jump links on a separate page within the frame, you will instead get a second copy of the jump link page loaded inside the frame.

ViewPager PagerAdapter not updating the View

I don't think there is any kind of bug in the PagerAdapter. The problem is that understanding how it works is a little complex. Looking at the solutions explained here, there is a misunderstanding and therefore a poor usage of instantiated views from my point of view.

The last few days I have been working with PagerAdapter and ViewPager, and I found the following:

The notifyDataSetChanged() method on the PagerAdapter will only notify the ViewPager that the underlying pages have changed. For example, if you have created/deleted pages dynamically (adding or removing items from your list) the ViewPager should take care of that. In this case I think that the ViewPager determines if a new view should be deleted or instantiated using the getItemPosition() and getCount() methods.

I think that ViewPager, after a notifyDataSetChanged() call takes it's child views and checks their position with the getItemPosition(). If for a child view this method returns POSITION_NONE, the ViewPager understands that the view has been deleted, calling the destroyItem(), and removing this view.

In this way, overriding getItemPosition() to always return POSITION_NONE is completely wrong if you only want to update the content of the pages, because the previously created views will be destroyed and new ones will be created every time you call notifyDatasetChanged(). It may seem to be not so wrong just for a few TextViews, but when you have complex views, like ListViews populated from a database, this can be a real problem and a waste of resources.

So there are several approaches to efficiently change the content of a view without having to remove and instantiate the view again. It depends on the problem you want to solve. My approach is to use the setTag() method for any instantiated view in the instantiateItem() method. So when you want to change the data or invalidate the view that you need, you can call the findViewWithTag() method on the ViewPager to retrieve the previously instantiated view and modify/use it as you want without having to delete/create a new view each time you want to update some value.

Imagine for example that you have 100 pages with 100 TextViews and you only want to update one value periodically. With the approaches explained before, this means you are removing and instantiating 100 TextViews on each update. It does not make sense...

Get user location by IP address

Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.

The code below requires the Json.NET package.

public static string GetUserCountryByIp(string ip)
{
    IpInfo ipInfo = new IpInfo();
    try
    {
        string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
        ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
        ipInfo.Country = myRI1.EnglishName;
    }
    catch (Exception)
    {
        ipInfo.Country = null;
    }
    
    return ipInfo.Country;
}

And the IpInfo Class I used:

public class IpInfo
{
    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

How can I add a vertical scrollbar to my div automatically?

Since OS X Lion, the scrollbar on websites are hidden by default and only visible once you start scrolling. Personally, I prefer the hidden scrollbar, but in case you really need it, you can overwrite the default and force the scrollbar in WebKit browsers back like this:

_x000D_
_x000D_
::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
_x000D_
_x000D_
_x000D_

Dynamic button click event handler

You can use AddHandler to add a handler for any event.

For example, this might be:

AddHandler theButton.Click, AddressOf Me.theButton_Click

Get selected value from combo box in C# WPF

I have figured it out a bit of a strange way of doing it compared to the old WF forms:

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

window.onload vs $(document).ready()

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

Is there a way to perform "if" in python's lambda

what you need exactly is

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

now call the function the way you need

f(2)
f(3)

How to Initialize char array from a string

Weird error.

Can you test this?

const char* const S = "ABCD";
char t[] = { S[0], S[1], S[2], S[3] };
char u[] = { S[3], S[2], S[1], S[0] };

How to round up the result of integer division?

A generic method, whose result you can iterate over may be of interest:

public static Object[][] chunk(Object[] src, int chunkSize) {

    int overflow = src.length%chunkSize;
    int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
    Object[][] dest = new Object[numChunks][];      
    for (int i=0; i<numChunks; i++) {
        dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); 
    }
    return dest;
}

Redirecting to URL in Flask

Flask includes the redirect function for redirecting to any url. Futhermore, you can abort a request early with an error code with abort:

from flask import abort, Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('hello'))

@app.route('/hello'):
def world:
    abort(401)

By default a black and white error page is shown for each error code.

The redirect method takes by default the code 302. A list for http status codes here.

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

NoClassDefFoundError on Maven dependency

Choosing to Project -> Clean should resolve this

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

It could also mean something like "Lexical Environment Type or Tied".. It bothers me that it would simply be "let this be that". And let rec wouldn't make sense in lambda calculus.

remove url parameters with javascript or jquery

Well, I am using this:

stripUrl(urlToStrip){
        let stripped = urlToStrip.split('?')[0];
        stripped = stripped.split('&')[0];
        stripped = stripped.split('#')[0];
        return stripped;
    }

or:

    stripUrl(urlToStrip){
        return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
    }

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

nodejs module.js:340 error: cannot find module

  1. Try npm start in Node.js Command Prompt.
  2. Look at the end of the messages - it gives you the path of log file in "Additional Logging Details ..." something like c:\users\MyUser\npm-debug.log
  3. Open this file in Notepad and find the real address of Node.exe : something like C:\\Program Files\\nodejs\\\\node.exe
  4. Try cd to this path
  5. Call node.exe + <full path to your server file.js>

    Server is listening on port 1337 !
    

How do I share variables between different .c files?

In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

In those few rare cases when you need to share a variable between files, do like this:

// file.h
extern int my_var;

// file.c
#include "file.h"
int my_var = something;

// main.c
#include "file.h"
use(my_var);

Never put any form of variable definition in a h-file.

How to implement a custom AlertDialog View

The android documents have been edited to correct the errors.

The view inside the AlertDialog is called android.R.id.custom

http://developer.android.com/reference/android/app/AlertDialog.html

How do you add PostgreSQL Driver as a dependency in Maven?

From site PostgreSQL, of date 02/04/2016 (https://jdbc.postgresql.org/download.html):

"This is the current version of the driver. Unless you have unusual requirements (running old applications or JVMs), this is the driver you should be using. It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM. It contains support for SSL and the javax.sql package. If you are using the 1.6 then you should use the JDBC4 version. If you are using 1.7 then you should use the JDBC41 version. If you are using 1.8 then you should use the JDBC42 versionIf you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver, which will by necessity not be current"

Why did I get the compile error "Use of unassigned local variable"?

The default value table only applies to initializing a variable.

Per the linked page, the following two methods of initialization are equivalent...

int x = 0;
int x = new int();

In your code, you merely defined the variable, but never initialized the object.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

To do this easily, the use of Stack is better. Create a Stack Then inside Stack add Align or Positioned and set position according to your needed, You can add multiple Container.

Container
  child: Stack(
    children: <Widget>[
      Align(
         alignment: FractionalOffset.center,
         child: Text(
            "? 1000",
         )
      ),
      Positioned(
        bottom: 0,
        child: Container(
           width: double.infinity,
           height: 30,
           child: Text(
             "Balance", ,
           )
         ),
       )
    ],
  )
)

enter image description here

Stack a widget that positions its children relative to the edges of its box.

Stack class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.

What are Aggregates and PODs and how/why are they special?

Changes in C++17

Download the C++17 International Standard final draft here.

Aggregates

C++17 expands and enhances aggregates and aggregate initialization. The standard library also now includes an std::is_aggregate type trait class. Here is the formal definition from section 11.6.1.1 and 11.6.1.2 (internal references elided):

An aggregate is an array or a class with
— no user-provided, explicit, or inherited constructors,
— no private or protected non-static data members,
— no virtual functions, and
— no virtual, private, or protected base classes.
[ Note: Aggregate initialization does not allow accessing protected and private base class’ members or constructors. —end note ]
The elements of an aggregate are:
— for an array, the array elements in increasing subscript order, or
— for a class, the direct base classes in declaration order, followed by the direct non-static data members that are not members of an anonymous union, in declaration order.

What changed?

  1. Aggregates can now have public, non-virtual base classes. Furthermore, it is not a requirement that base classes be aggregates. If they are not aggregates, they are list-initialized.
struct B1 // not a aggregate
{
    int i1;
    B1(int a) : i1(a) { }
};
struct B2
{
    int i2;
    B2() = default;
};
struct M // not an aggregate
{
    int m;
    M(int a) : m(a) { }
};
struct C : B1, B2
{
    int j;
    M m;
    C() = default;
};
C c { { 1 }, { 2 }, 3, { 4 } };
cout
    << "is C aggregate?: " << (std::is_aggregate<C>::value ? 'Y' : 'N')
    << " i1: " << c.i1 << " i2: " << c.i2
    << " j: " << c.j << " m.m: " << c.m.m << endl;

//stdout: is C aggregate?: Y, i1=1 i2=2 j=3 m.m=4
  1. Explicit defaulted constructors are disallowed
struct D // not an aggregate
{
    int i = 0;
    D() = default;
    explicit D(D const&) = default;
};
  1. Inheriting constructors are disallowed
struct B1
{
    int i1;
    B1() : i1(0) { }
};
struct C : B1 // not an aggregate
{
    using B1::B1;
};


Trivial Classes

The definition of trivial class was reworked in C++17 to address several defects that were not addressed in C++14. The changes were technical in nature. Here is the new definition at 12.0.6 (internal references elided):

A trivially copyable class is a class:
— where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial,
— that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
— that has a trivial, non-deleted destructor.
A trivial class is a class that is trivially copyable and has one or more default constructors, all of which are either trivial or deleted and at least one of which is not deleted. [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

Changes:

  1. Under C++14, for a class to be trivial, the class could not have any copy/move constructor/assignment operators that were non-trivial. However, then an implicitly declared as defaulted constructor/operator could be non-trivial and yet defined as deleted because, for example, the class contained a subobject of class type that could not be copied/moved. The presence of such non-trivial, defined-as-deleted constructor/operator would cause the whole class to be non-trivial. A similar problem existed with destructors. C++17 clarifies that the presence of such constructor/operators does not cause the class to be non-trivially copyable, hence non-trivial, and that a trivially copyable class must have a trivial, non-deleted destructor. DR1734, DR1928
  2. C++14 allowed a trivially copyable class, hence a trivial class, to have every copy/move constructor/assignment operator declared as deleted. If such as class was also standard layout, it could, however, be legally copied/moved with std::memcpy. This was a semantic contradiction, because, by defining as deleted all constructor/assignment operators, the creator of the class clearly intended that the class could not be copied/moved, yet the class still met the definition of a trivially copyable class. Hence in C++17 we have a new clause stating that trivially copyable class must have at least one trivial, non-deleted (though not necessarily publicly accessible) copy/move constructor/assignment operator. See N4148, DR1734
  3. The third technical change concerns a similar problem with default constructors. Under C++14, a class could have trivial default constructors that were implicitly defined as deleted, yet still be a trivial class. The new definition clarifies that a trivial class must have a least one trivial, non-deleted default constructor. See DR1496

Standard-layout Classes

The definition of standard-layout was also reworked to address defect reports. Again the changes were technical in nature. Here is the text from the standard (12.0.7). As before, internal references are elided:

A class S is a standard-layout class if it:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions and no virtual base classes,
— has the same access control for all non-static data members,
— has no non-standard-layout base classes,
— has at most one base class subobject of any given type,
— has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
— has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
— If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
— If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
— If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
— If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
— If X is a non-class, non-array type, the set M(X) is empty.
[ Note: M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X. —end note ]
[ Example:

struct B { int i; }; // standard-layout class
struct C : B { }; // standard-layout class
struct D : C { }; // standard-layout class
struct E : D { char : 4; }; // not a standard-layout class
struct Q {};
struct S : Q { };
struct T : Q { };
struct U : S, T { }; // not a standard-layout class
—end example ]
108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address.

Changes:

  1. Clarified that the requirement that only one class in the derivation tree "has" non-static data members refers to a class where such data members are first declared, not classes where they may be inherited, and extended this requirement to non-static bit fields. Also clarified that a standard-layout class "has at most one base class subobject of any given type." See DR1813, DR1881
  2. The definition of standard-layout has never allowed the type of any base class to be the same type as the first non-static data member. It is to avoid a situation where a data member at offset zero has the same type as any base class. The C++17 standard provides a more rigorous, recursive definition of "the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset" so as to prohibit such types from being the type of any base class. See DR1672, DR2120.

Note: The C++ standards committee intended the above changes based on defect reports to apply to C++14, though the new language is not in the published C++14 standard. It is in the C++17 standard.

How can I reset or revert a file to a specific revision?

Many suggestions here, most along the lines of git checkout $revision -- $file. A couple of obscure alternatives:

git show $revision:$file > $file

And also, I use this a lot just to see a particular version temporarily:

git show $revision:$file

or

git show $revision:$file | vim -R -

(OBS: $file needs to be prefixed with ./ if it is a relative path for git show $revision:$file to work)

And the even more weird:

git archive $revision $file | tar -x0 > $file

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Load content of a div on another page

    You just need to add a jquery selector after the url.

    See: http://api.jquery.com/load/

    Example straight from the API:

    $('#result').load('ajax/test.html #container');
    

    So what that does is it loads the #container element from the specified url.

    Can a table row expand and close?

    You could do it like this:

    HTML

    <table>
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
            <td>Cell 3</td>
            <td>Cell 4</td>
            <td><a href="#" id="show_1">Show Extra</a></td>
        </tr>
        <tr>
            <td colspan="5">
                <div id="extra_1" style="display: none;">
                    <br>hidden row
                    <br>hidden row
                    <br>hidden row
                </div>
            </td>
        </tr>
    </table>
    

    jQuery

    $("a[id^=show_]").click(function(event) {
        $("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
        event.preventDefault();
    });
    

    See a demo on JSFiddle

    Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

    In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

    Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

    How to find keys of a hash?

    I wanted to use the top rated answer above

    Object.prototype.keys = function () ...
    

    However when using in conjunction with the google maps API v3, google maps is non-functional.

    for (var key in h) ...
    

    works well.

    ImportError: No module named - Python

    make sure to include __init__.py, which makes Python know that those directories containpackages

    Android. Fragment getActivity() sometimes returns null

    I know this is a old question but i think i must provide my answer to it because my problem was not solved by others.

    first of all : i was dynamically adding fragments using fragmentTransactions. Second: my fragments were modified using AsyncTasks (DB queries on a server). Third: my fragment was not instantiated at activity start Fourth: i used a custom fragment instantiation "create or load it" in order to get the fragment variable. Fourth: activity was recreated because of orientation change

    The problem was that i wanted to "remove" the fragment because of the query answer, but the fragment was incorrectly created just before. I don't know why, probably because of the "commit" be done later, the fragment was not added yet when it was time to remove it. Therefore getActivity() was returning null.

    Solution : 1)I had to check that i was correctly trying to find the first instance of the fragment before creating a new one 2)I had to put serRetainInstance(true) on that fragment in order to keep it through orientation change (no backstack needed therefore no problem) 3)Instead of "recreating or getting old fragment" just before "remove it", I directly put the fragment at activity start. Instantiating it at activity start instead of "loading" (or instantiating) the fragment variable before removing it prevented getActivity problems.

    Git merge without auto commit

    Note the output while doing the merge - it is saying Fast Forward

    In such situations, you want to do:

    git merge v1.0 --no-commit --no-ff
    

    Rails 3 migrations: Adding reference column?

    With the two previous steps stated above, you're still missing the foreign key constraint. This should work:

      class AddUserReferenceToTester < ActiveRecord::Migration
          def change
              add_column :testers, :user_id, :integer, references: :users
          end
      end
    

    If table exists drop table then create it, if it does not exist just create it

    Just use DROP TABLE IF EXISTS:

    DROP TABLE IF EXISTS `foo`;
    CREATE TABLE `foo` ( ... );
    

    Try searching the MySQL documentation first if you have any other problems.

    How do I create an .exe for a Java program?

    I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.

    How to insert a row between two rows in an existing excel with HSSF (Apache POI)

    Referencing Qwerty's answer, if the destRow isnot null, sheet.shiftRows() will change the destRow's reference to the next row; so we should always create a new row:

    if (destRow != null) {
      sheet.shiftRows(destination, sheet.getLastRowNum(), 1);
    }
    destRow = sheet.createRow(destination);
    

    Custom format for time command

    From the man page for time:

    1. There may be a shell built-in called time, avoid this by specifying /usr/bin/time
    2. You can provide a format string and one of the format options is elapsed time - e.g. %E

      /usr/bin/time -f'%E' $CMD

    Example:

    $ /usr/bin/time -f'%E' ls /tmp/mako/
    res.py  res.pyc
    0:00.01
    

    How do I watch a file for changes?

    If you're using windows, create this POLL.CMD file

    @echo off
    :top
    xcopy /m /y %1 %2 | find /v "File(s) copied"
    timeout /T 1 > nul
    goto :top
    

    then you can type "poll dir1 dir2" and it will copy all the files from dir1 to dir2 and check for updates once per second.

    The "find" is optional, just to make the console less noisy.

    This is not recursive. Maybe you could make it recursive using /e on the xcopy.

    Connecting to local SQL Server database using C#

    In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

    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.

    toggle show/hide div with button?

    Look at jQuery Toggle

    HTML:

    <div id='content'>Hello World</div>
    <input type='button' id='hideshow' value='hide/show'>
    

    jQuery:

    jQuery(document).ready(function(){
        jQuery('#hideshow').live('click', function(event) {        
             jQuery('#content').toggle('show');
        });
    });
    

    For versions of jQuery 1.7 and newer use

    jQuery(document).ready(function(){
        jQuery('#hideshow').on('click', function(event) {        
            jQuery('#content').toggle('show');
        });
    });
    

    For reference, kindly check this demo

    Get path to execution directory of Windows Forms application

    Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx

    Also this should give you the location of the assembly

    AppDomain.CurrentDomain.BaseDirectory
    

    I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)

    In LaTeX, how can one add a header/footer in the document class Letter?

    After I removed

    \usepackage{fontspec}% font selecting commands 
    \usepackage{xunicode}% unicode character macros 
    \usepackage{xltxtra} % some fixes/extras 
    

    it seems to have worked "correctly".

    It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

    FYI: MikTeX 2.7 under Vista

    Sleep function Visual Basic

    This one is much easie.

    Threading.Thread.Sleep(3000)
    

    How can I send an Ajax Request on button click from a form with 2 buttons?

    Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

    $("#button_1, #button_2").on("click", function(e) {
        e.preventDefault();
        $.ajax({type: "POST",
            url: "/pages/test/",
            data: { id: $(this).val(), access_token: $("#access_token").val() },
            success:function(result) {
              alert('ok');
            },
            error:function(result) {
              alert('error');
            }
        });
    });
    

    AngularJS $watch window resize inside directive

    You shouldn't need a $watch. Just bind to resize event on window:

    DEMO

    'use strict';
    
    var app = angular.module('plunker', []);
    
    app.directive('myDirective', ['$window', function ($window) {
    
         return {
            link: link,
            restrict: 'E',
            template: '<div>window size: {{width}}px</div>'
         };
    
         function link(scope, element, attrs){
    
           scope.width = $window.innerWidth;
    
           angular.element($window).bind('resize', function(){
    
             scope.width = $window.innerWidth;
    
             // manuall $digest required as resize event
             // is outside of angular
             scope.$digest();
           });
    
         }
    
     }]);
    

    Java generics: multiple generic parameters?

    Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.

    With the signature you have given, T must be associated to a single type (e.g. String or Integer) at the call-site. You can, however, declare method signatures which take multiple type parameters

    public <S, T> void func(Set<S> s, Set<T> t)
    

    Note in the above signature that I have declared the types S and T in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.

    public class MyClass<S, T> {
       public        void foo(Set<S> s, Set<T> t); //same type params as on class
       public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
    }
    

    You might like to take a look at some of the method signatures of the collection classes in the java.util package. Generics is really rather a complicated subject, especially when wildcards (? extends and ? super) are considered. For example, it's often the case that a method which might take a Set<Number> as a parameter should also accept a Set<Integer>. In which case you'd see a signature like this:

    public void baz(Set<? extends T> s);
    

    There are plenty of questions already on SO for you to look at on the subject!

    Not sure what the point of returning an int from the function is, although you could do that if you want!

    Detect if HTML5 Video element is playing

    a bit example

    _x000D_
    _x000D_
    var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')_x000D_
    _x000D_
    if (audio.paused) {_x000D_
      audio.play()_x000D_
    } else {_x000D_
      audio.pause()_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How to filter multiple values (OR operation) in angularJS

    You can also use ngIf if the situation permits:

    <div ng-repeat="p in [
     { name: 'Justin' }, 
     { name: 'Jimi' }, 
     { name: 'Bob' }
     ]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
     {{ p.name }} is cool
    </div>
    

    What is the most efficient way to get first and last line of a text file?

    Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument will be raised.

    def tail(filepath):
        with open(filepath, "rb") as f:
            first = f.readline()      # Read the first line.
            f.seek(-2, 2)             # Jump to the second last byte.
            while f.read(1) != b"\n": # Until EOL is found...
                try:
                    f.seek(-2, 1)     # ...jump back the read byte plus one more.
                except IOError:
                    f.seek(-1, 1)
                    if f.tell() == 0:
                        break
            last = f.readline()       # Read last line.
        return last
    

    How to send email via Django?

    You could use "Test Mail Server Tool" to test email sending on your machine or localhost. Google and Download "Test Mail Server Tool" and set it up.

    Then in your settings.py:

    EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'localhost'
    EMAIL_PORT = 25
    

    From shell:

    from django.core.mail import send_mail
    send_mail('subject','message','sender email',['receipient email'],    fail_silently=False)
    

    How to set limits for axes in ggplot2 R plots?

    Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

    Fortunately, this is an easy fix; set your limits within coord_flip() like so:

    p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
    

    This just alters the visible range (i.e. doesn't remove data points).

    How can I escape double quotes in XML attributes values?

    A double quote character (") can be escaped as &quot;, but here's the rest of the story...

    Double quote character must be escaped in this context:

    • In XML attributes delimited by double quotes:

      <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
      

    Double quote character need not be escaped in most contexts:

    • In XML textual content:

      <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
      
    • In XML attributes delimited by single quotes ('):

      <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
      

      Similarly, (') require no escaping if (") are used for the attribute value delimiters:

      <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
      

    See also

    IF - ELSE IF - ELSE Structure in Excel

    =IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))
    

    CR = ColRow (Cell) This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.

    You seem to not be depending on "@angular/core". This is an error

    Executing ng new --skip-install PROJECT_NAME and then manually going into the created folder and typing npm install. https://github.com/angular/angular-cli/issues/3906

    How to convert a DataFrame back to normal RDD in pyspark?

    Use the method .rdd like this:

    rdd = df.rdd
    

    python: order a list of numbers without built-in sort, min, max function

    try sorting list , char have the ascii code, the same can be used for sorting the list of char.

    aw=[1,2,2,1,1,3,5,342,345,56,2,35,436,6,576,54,76,47,658,8758,87,878]
    for i in range(aw.__len__()):
        for j in range(aw.__len__()):
            if aw[i] < aw[j] :aw[i],aw[j]=aw[j],aw[i]
    

    How to pass an array into a SQL Server stored procedure

    Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;' in-which 123, 434 and 365 are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.

    CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees  @List AS varchar(max)
    AS
    BEGIN
      SELECT EmployeeID 
      FROM EmployeesTable
      -- inner join AnotherTable on ...
      where @List like '%;'+cast(employeeID as varchar(20))+';%'
    END
    GO
    

    Take a screenshot via a Python script on Linux

    bit late but nevermind easy one is

    import autopy
    import time
    time.sleep(2)
    b = autopy.bitmap.capture_screen()
    b.save("C:/Users/mak/Desktop/m.png")
    

    How to show math equations in general github's markdown(not github's blog)

    One other work-around is to use jupyter notebooks and use the markdown mode in cells to render equations.

    Basic stuff seems to work perfectly, like centered equations

    \begin{equation}
    ...
    \end{equation}
    

    or inline equations

    $ \sum_{\forall i}{x_i^{2}} $
    

    Although, one of the functions that I really wanted did not render at all in github was \mbox{}, which was a bummer. But, all in all this has been the most successful way of rendering equations on github.

    Python: Finding differences between elements of a list

    If you don't want to use numpy nor zip, you can use the following solution:

    >>> t = [1, 3, 6]
    >>> v = [t[i+1]-t[i] for i in range(len(t)-1)]
    >>> v
    [2, 3]
    

    How to decrypt the password generated by wordpress

    This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

    1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
    2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
    3. You will be prompted to enter a new password.

    How to get today's Date?

    Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
    

    DateUtils from Apache Commons-Lang. Watch out for time zone!

    Is there an arraylist in Javascript?

    Use javascript array push() method, it adds the given object in the end of the array. JS Arrays are pretty flexible,you can push as many objects as you wish in an array without specifying its length beforehand. Also,different types of objects can be pushed to the same Array.

    How do I convert a pandas Series or index to a Numpy array?

    Below is a simple way to convert dataframe column into numpy array.

    df = pd.DataFrame(somedict) 
    ytrain = df['label']
    ytrain_numpy = np.array([x for x in ytrain['label']])
    

    ytrain_numpy is a numpy array.

    I tried with to.numpy() but it gave me the below error: TypeError: no supported conversion for types: (dtype('O'),) while doing Binary Relevance classfication using Linear SVC. to.numpy() was converting the dataFrame into numpy array but the inner element's data type was list because of which the above error was observed.

    Round button with text and icon in flutter

    Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:

    Container(
      width: 120.0,
      height: 30.0,
      child: RaisedButton(
        color: Color(0XFFFF0000),
        child: Row(
          children: <Widget>[
            Text('Play this song', style: TextStyle(color: Colors.white),),
            Icon(Icons.play_arrow, color: Colors.white,),
          ],
        ),
      ),
    ),
    

    Multiplication on command line terminal

    I have a simple script I use for this:

    me@mycomputer:~$ cat /usr/local/bin/c

    #!/bin/sh
    
    echo "$*" | sed 's/x/\*/g' | bc -l
    

    It changes x to * since * is a special character in the shell. Use it as follows:

    • c 5x5
    • c 5-4.2 + 1
    • c '(5 + 5) * 30' (you still have to use quotes if the expression contains any parentheses).

    Running SSH Agent when starting Git Bash on Windows

    In a git bash session, you can add a script to ~/.profile or ~/.bashrc (with ~ being usually set to %USERPROFILE%), in order for said session to launch automatically the ssh-agent. If the file doesn't exist, just create it.

    This is what GitHub describes in "Working with SSH key passphrases".

    The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.

    # This is just a snippet. See the article above.
    if ! agent_is_running; then
        agent_start
        ssh-add
    elif ! agent_has_keys; then
        ssh-add
    fi
    

    Other Resources:

    "Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.

    How to update RecyclerView Adapter Data?

    The best and the coolest way to add new data to the present data is

     ArrayList<String> newItems = new ArrayList<String>();
     newItems = getList();
     int oldListItemscount = alcontainerDetails.size();
     alcontainerDetails.addAll(newItems);           
     recyclerview.getAdapter().notifyItemChanged(oldListItemscount+1, al_containerDetails);
    

    git remove merge commit from history

    To Just Remove a Merge Commit

    If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows

    git rebase --onto <sha of 1> <sha of 2> <blue branch>

    And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.

    Hiding the address bar of a browser (popup)

    In the Edge browser as of build 20.10240.16384.0 you can hide the address bar by setting location=no in the window.open features.

    How to read integer value from the standard input in Java

    check this one:

    import java.io.*;
    public class UserInputInteger
    {
            public static void main(String args[])throws IOException
            {
            InputStreamReader read = new InputStreamReader(System.in);
            BufferedReader in = new BufferedReader(read);
            int number;
                    System.out.println("Enter the number");
                    number = Integer.parseInt(in.readLine());
        }
    }
    

    Is it possible to serialize and deserialize a class in C++?

    The Boost::serialization library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.

    The only native way to do it is to use streams. That's essentially all the Boost::serialization library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.

    For built-in types, or your own types with operator<< and operator>> properly defined, that's fairly simple; see the C++ FAQ for more information.

    C++ int to byte array

    An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?

    memcpy(arrayOfByte, &x, sizeof x);
    

    A simple elegant one liner that will also work with any other data type.



    If you need the bytes reversed you can use std::reverse

    memcpy(arrayOfByte, &x, sizeof x);
    std::reverse(arrayOfByte, arrayOfByte + sizeof x);
    

    or better yet, just copy the bytes in reverse to begin with

    BYTE* p = (BYTE*) &x;
    std::reverse_copy(p, p + sizeof x, arrayOfByte);
    

    If you don't want to make a copy of the data at all, and just have its byte representation

    BYTE* bytes = (BYTE*) &x;
    

    MVC Form not able to post List of objects

    Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

    @foreach (var planVM in Model)
    {
        @Html.Partial("_partialView", planVM)
    }
    

    is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

    <input type="hidden" name="yourmodelprefix.PlanID" />
    <input type="hidden" name="yourmodelprefix.CurrentPlan" />
    <input type="checkbox" name="yourmodelprefix.ShouldCompare" />
    

    However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

    <input type="hidden" name="yourmodelprefix[0].PlanID" />
    <input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
    <input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
    <input type="hidden" name="yourmodelprefix[1].PlanID" />
    <input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
    <input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
    

    That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

    1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
    2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

    Now, everything you have in your partial view wants to go in that template:

    @model PlanCompareViewModel
    <div>
        @Html.HiddenFor(p => p.PlanID)
        @Html.HiddenFor(p => p.CurrentPlan)
        @Html.CheckBoxFor(p => p.ShouldCompare)
       <input type="submit" value="Compare"/>
    </div>
    

    Finally, your parent view is simplified to this:

    @model IEnumerable<PlanCompareViewModel>
    @using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
    {
    <div>
        @Html.EditorForModel()
    </div>
    }
    

    DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

    Git add and commit in one command

    I have this function in my .bash_profile or .profile or .zprofile or whatever gets sourced in login shells:

    function gac () {
      # Usage: gac [files] [message]
      # gac (git add commit) stages files specified by the first argument
      # and commits the changes with a message specified by the second argument.
      # Using quotes one can add multiple files at once: gac "file1 file2" "Message".
      git add $1 && git commit -m "$2"
    }
    

    How to add a classname/id to React-Bootstrap Component?

    If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

    How do I vertically align text in a div?

    You need to add the line-height attribute and that attribute must match the height of the div. In your case:

    _x000D_
    _x000D_
    .center {_x000D_
      height: 309px;_x000D_
      line-height: 309px; /* same as height! */_x000D_
    }
    _x000D_
    <div class="center">_x000D_
      A single line._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    In fact, you could probably remove the height attribute altogether.

    This only works for one line of text though, so be careful.

    Powershell script does not run via Scheduled Tasks

    If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:

    1. Run CMD as a user who has been set for Scheduled Task to execute the PowerShell script
    2. Browse to the folder where the PowerShell script is located
    3. Execute the PowerShell script (remove all statements that block the error notifications if any exists inside of the script like $ErrorActionPreference= 'silentlycontinue')

    You should be able to see all error notifications.

    In case of one of my script it was:

    "Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded."

    And in this case I have to add additional line at the begining of the script to load the missing assembly:

    Add-Type -AssemblyName "System.ServiceProcess"

    And next errors:

    Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."

    select : The property cannot be processed because the property "Database Name" already exists

    What should be the sizeof(int) on a 64-bit machine?

    Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.

    How to revert uncommitted changes including files and folders?

    If you want to revert the changes only in current working directory, use

    git checkout -- .
    

    And before that, you can list the files that will be reverted without actually making any action, just to check what will happen, with:

    git checkout --
    

    Determine what attributes were changed in Rails after_save callback?

    You just add an accessor who define what you change

    class Post < AR::Base
      attr_reader :what_changed
    
      before_filter :what_changed?
    
      def what_changed?
        @what_changed = changes || []
      end
    
      after_filter :action_on_changes
    
      def action_on_changes
        @what_changed.each do |change|
          p change
        end
      end
    end
    

    Django Rest Framework File Upload

    You can generalize @Nithin's answer to work directly with DRF's existing serializer system by generating a parser class to parse specific fields which are then fed directly into the standard DRF serializers:

    from django.http import QueryDict
    import json
    from rest_framework import parsers
    
    
    def gen_MultipartJsonParser(json_fields):
        class MultipartJsonParser(parsers.MultiPartParser):
    
            def parse(self, stream, media_type=None, parser_context=None):
                result = super().parse(
                    stream,
                    media_type=media_type,
                    parser_context=parser_context
                )
                data = {}
                # find the data field and parse it
                qdict = QueryDict('', mutable=True)
                for json_field in json_fields:
                    json_data = result.data.get(json_field, None)
                    if not json_data:
                        continue
                    data = json.loads(json_data)
                    if type(data) == list:
                        for d in data:
                            qdict.update({json_field: d})
                    else:
                        qdict.update({json_field: data})
    
                return parsers.DataAndFiles(qdict, result.files)
    
        return MultipartJsonParser
    

    This is used like:

    class MyFileViewSet(ModelViewSet):
        parser_classes = [gen_MultipartJsonParser(['tags', 'permissions'])]
        #                                           ^^^^^^^^^^^^^^^^^^^
        #                              Fields that need to be further JSON parsed
        ....
    

    How to give environmental variable path for file appender in configuration file in log4j

    I got this working.

    1. In my log4j.properties. I specified

    log4j.appender.file.File=${LogFilePath}

    1. in eclipse - JVM arguments

    -DLogFilePath=C:\work\MyLogFile.log

    How to split data into trainset and testset randomly?

    A quick note for the answer from @subin sahayam

     import random
     file=open("datafile.txt","r")
     data=list()
     for line in file:
        data.append(line.split(#your preferred delimiter))
     file.close()
     random.shuffle(data)
     train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
     test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set
    

    If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.

    test_data = data[int(len(data)*.80+1):]

    Change background color of R plot

    Old question but I have a much better way of doing this. Rather than using rect() use polygon. This allows you to keep everything in plot without using points. Also you don't have to mess with par at all. If you want to keep things automated make the coordinates of polygon a function of your data.

    plot.new()
    polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
    par(new=T)
    plot(df)
    

    Set active tab style with AngularJS

    Here's another version of XMLillies w/ domi's LI change that uses a search string instead of a path level. I think this is a little more obvious what's happening for my use case.

    statsApp.directive('activeTab', function ($location) {
      return {
        link: function postLink(scope, element, attrs) {
          scope.$on("$routeChangeSuccess", function (event, current, previous) {
            if (attrs.href!=undefined) { // this directive is called twice for some reason
              // The activeTab attribute should contain a path search string to match on.
              // I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
              if ($location.path().indexOf(attrs.activeTab) >= 0) {
                element.parent().addClass("active");//parent to get the <li>
              } else {
                element.parent().removeClass("active");
              }
            }
          });
        }
      };
    });
    

    HTML now looks like:

    <ul class="nav nav-tabs">
      <li><a href="#/news" active-tab="/news">News</a></li>
      <li><a href="#/some/nested/photos/rawr" active-tab="/photos">Photos</a></li>
      <li><a href="#/contact" active-tab="/contact">Contact</a></li>
    </ul>
    

    Display array values in PHP

    You can use implode to return your array with a string separator.

    $withComma = implode(",", $array);
    
    echo $withComma;
    // Will display apple,banana,orange
    

    Unable to connect PostgreSQL to remote database using pgAdmin

    It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.

    Note: I use Ubuntu 11.04 and PostgreSQL 8.4.

    1. You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:

      listen_addresses = '*'

    2. PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:

      host all all 0.0.0.0/0 md5

      This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .

    3. When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.

    How can I add an empty directory to a Git repository?

    Sometimes I have repositories with folders that will only ever contain files considered to be "content"—that is, they are not files that I care about being versioned, and therefore should never be committed. With Git's .gitignore file, you can ignore entire directories. But there are times when having the folder in the repo would be beneficial. Here's a excellent solution for accomplishing this need.

    What I've done in the past is put a .gitignore file at the root of my repo, and then exclude the folder, like so:

    /app/some-folder-to-exclude
    /another-folder-to-exclude/*
    

    However, these folders then don't become part of the repo. You could add something like a README file in there. But then you have to tell your application not to worry about processing any README files.

    If your app depends on the folders being there (though empty), you can simply add a .gitignore file to the folder in question, and use it to accomplish two goals:

    Tell Git there's a file in the folder, which makes Git add it to the repo. Tell Git to ignore the contents of this folder, minus this file itself. Here is the .gitignore file to put inside your empty directories:

    *
    !.gitignore
    

    The first line (*) tells Git to ignore everything in this directory. The second line tells Git not to ignore the .gitignore file. You can stuff this file into every empty folder you want added to the repository.

    Mismatch Detected for 'RuntimeLibrary'

    I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.

    The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.


    Any ideas how to fix this?

    To resolve your issues, you should download vs2010.zip if you want static C/C++ runtime linking (/MT or /MTd), or vs2010-dynamic.zip if you want dynamic C/C++ runtime linking (/MT or /MTd). Both fix the latent, silent failures produced by VCUpgrade.


    vs2010.zip, vs2010-dynamic.zip and vs2005-dynamic.zip are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.

    There are two minor problems I am aware. First is a rename of bench.cpp to bench1.cpp. Its error is either:

    • C1083: Cannot open source file: 'bench1.cpp': No such file or directory
    • LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)

    The fix is to either (1) open cryptest.vcxproj in notepad, find bench1.cpp, and then rename it to bench.cpp. Or (2) rename bench.cpp to bench1.cpp on the filesystem. Please don't delete this file.

    The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.

    The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.

    Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h, cpu.h and cpu.cpp. The "subtlety" is you won't realize you are getting an under-performing class.

    An example of under-performing class is BLAKE2. config.h adds compile time ARM-32 and ARM-64 detection. cpu.h and cpu.cpp adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.

    How to find out when a particular table was created in Oracle?

    Try this query:

    SELECT sysdate FROM schema_name.table_name;

    This should display the timestamp that you might need.

    Latex Remove Spaces Between Items in List

    You could do something like this:

    \documentclass{article}
    
    \begin{document}
    
    Normal:
    
    \begin{itemize}
      \item foo
      \item bar
      \item baz
    \end{itemize}
    
    Less space:
    
    \begin{itemize}
      \setlength{\itemsep}{1pt}
      \setlength{\parskip}{0pt}
      \setlength{\parsep}{0pt}
      \item foo
      \item bar
      \item baz
    \end{itemize}
    
    \end{document}
    

    Allow all remote connections, MySQL

    Also you need to disable below line in configuration file: bind-address = 127.0.0.1

    What is the python "with" statement designed for?

    Again for completeness I'll add my most useful use-case for with statements.

    I do a lot of scientific computing and for some activities I need the Decimal library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.

    I set my default precision to a low number and then use with to get a more precise answer for some sections:

    from decimal import localcontext
    
    with localcontext() as ctx:
        ctx.prec = 42   # Perform a high precision calculation
        s = calculate_something()
    s = +s  # Round the final result back to the default precision
    

    I use this a lot with the Hypergeometric Test which requires the division of large numbers resulting form factorials. When you do genomic scale calculations you have to be careful of round-off and overflow errors.

    What is 0x10 in decimal?

    The simple version is 0x is a prefix denoting a hexadecimal number, source.

    So the value you're computing is after the prefix, in this case 10.

    But that is not the number 10. The most significant bit 1 denotes the hex value while 0 denotes the units.

    So the simple math you would do is

    0x10

    1 * 16 + 0 = 16
    

    Note - you use 16 because hex is base 16.

    Another example:

    0xF7

    15 * 16 + 7 = 247
    

    You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.

    How to normalize a 2-dimensional numpy array in python less verbose?

    Broadcasting is really good for this:

    row_sums = a.sum(axis=1)
    new_matrix = a / row_sums[:, numpy.newaxis]
    

    row_sums[:, numpy.newaxis] reshapes row_sums from being (3,) to being (3, 1). When you do a / b, a and b are broadcast against each other.

    You can learn more about broadcasting here or even better here.

    NSURLSession/NSURLConnection HTTP load failed on iOS 9

    This is what worked for me when I had this error:

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>example.com</key>
            <dict>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.0</string>
            </dict>
        </dict>
    </dict>
    

    How do you change the character encoding of a postgres database?

    Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

    Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

    And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


    I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

    su root
    

    Reconfigure your local settings :

    dpkg-reconfigure locales
    

    Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

    Uninstall and clean properly postgresql :

    apt-get --purge remove postgresql\*
    rm -r /etc/postgresql/
    rm -r /etc/postgresql-common/
    rm -r /var/lib/postgresql/
    userdel -r postgres
    groupdel postgres
    

    Re-install postgresql :

    aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1
    

    Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

    Show Hide div if, if statement is true

    A fresh look at this(possibly)
    in your php:

    else{
          $hidemydiv = "hide";
    }
    

    And then later in your html code:

    <div class='<?php echo $hidemydiv ?>' > maybe show or hide this</div>
    

    in this way your php remains quite clean

    How do I run Python script using arguments in windows command line

    I found this thread looking for information about dealing with parameters; this easy guide was so cool:

    import argparse
    
    parser = argparse.ArgumentParser(description='Script so useful.')
    parser.add_argument("--opt1", type=int, default=1)
    parser.add_argument("--opt2")
    
    args = parser.parse_args()
    
    opt1_value = args.opt1
    opt2_value = args.opt2
    

    run like:

    python myScript.py --opt2 = 'hi'
    

    How do I create a batch file timer to execute / call another batch throughout the day

    I would use the scheduler (control panel) rather than a cmd line or other application.

    Control Panel -> Scheduled tasks

    What's a good, free serial port monitor for reverse-engineering?

    I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.

    Getting the WordPress Post ID of current post

    In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

    $postID = get_queried_object_id();
    

    No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

    I got

    No 'Access-Control-Allow-Origin' header is present

    and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/.

    When I added a path it worked, e.g., https://misty-valley-1234.herokuapp.com/messages. With GET requests it worked either way but with POST responses it only worked with the added path.

    Bootstrap Align Image with text

    Try using .pull-left to left align image along with text.

    Ex:

    <p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>
    

    How do the post increment (i++) and pre increment (++i) operators work in Java?

    I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.

    The code will work like this:

    int a=5,i;
    
    i=++a + ++a + a++;            /*a = 5;
                                    i=++a + ++a + a++; =>
                                    i=6 + 7 + 7; (a=8); i=20;*/
    
    i=a++ + ++a + ++a;           /*a = 5;
                                    i=a++ + ++a + ++a; =>
                                    i=8 + 10 + 11; (a=11); i=29;*/
    
    a=++a + ++a + a++;            /*a=5;
                                    a=++a + ++a + a++; =>
                                    a=12 + 13 + 13;  a=38;*/
    
    System.out.println(a);        //output: 38
    System.out.println(i);         //output: 29
    

    ReactNative: how to center text?

    You can use two approaches for this...

    1. To make text align center horizontally, apply this Property (textAlign:"center"). Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center") and if flexDirection is row is row apply property (alignItems : "center") .

    2. To Make text align center apply same property (textAlign:"center"). Now to make it align vertically make the hieght of the <Text> </Text> equal to view and then apply property (textAlignVertical: "center")...

    Most Probably it will Work...

    Inserting one list into another list in java?

    Citing the official javadoc of List.addAll:

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

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

    Possible to extend types in Typescript?

    What you are trying to achieve is equivalent to

    interface Event {
       name: string;
       dateCreated: string;
       type: string;
    }
    
    interface UserEvent extends Event {
       UserId: string; 
    }
    

    The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.

    Correct way to pass multiple values for same parameter name in GET request

    Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

    http://localhost/?key[]=1&key[]=2

    Returns:

    Array
    (
    [key] => Array
        (
            [0] => 1
            [1] => 2
        )
    

    How to "properly" create a custom object in JavaScript?

    To continue off of bobince's answer

    In es6 you can now actually create a class

    So now you can do:

    class Shape {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    
        toString() {
            return `Shape at ${this.x}, ${this.y}`;
        }
    }
    

    So extend to a circle (as in the other answer) you can do:

    class Circle extends Shape {
        constructor(x, y, r) {
            super(x, y);
            this.r = r;
        }
    
        toString() {
            let shapeString = super.toString();
            return `Circular ${shapeString} with radius ${this.r}`;
        }
    }
    

    Ends up a bit cleaner in es6 and a little easier to read.


    Here is a good example of it in action:

    _x000D_
    _x000D_
    class Shape {_x000D_
      constructor(x, y) {_x000D_
        this.x = x;_x000D_
        this.y = y;_x000D_
      }_x000D_
    _x000D_
      toString() {_x000D_
        return `Shape at ${this.x}, ${this.y}`;_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    class Circle extends Shape {_x000D_
      constructor(x, y, r) {_x000D_
        super(x, y);_x000D_
        this.r = r;_x000D_
      }_x000D_
    _x000D_
      toString() {_x000D_
        let shapeString = super.toString();_x000D_
        return `Circular ${shapeString} with radius ${this.r}`;_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    let c = new Circle(1, 2, 4);_x000D_
    _x000D_
    console.log('' + c, c);
    _x000D_
    _x000D_
    _x000D_

    javascript return true or return false when and how to use it?

    returning true or false indicates that whether execution should continue or stop right there. So just an example

    <input type="button" onclick="return func();" />
    

    Now if func() is defined like this

    function func()
    {
     // do something
    return false;
    }
    

    the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

    BackgroundWorker vs background Thread

    Also you are tying up a threadpool thread for the lifetime of the background worker, which may be of concern as there are only a finite number of them. I would say that if you are only ever creating the thread once for your app (and not using any of the features of background worker) then use a thread, rather than a backgroundworker/threadpool thread.

    How can I format a list to print each element on a separate line in python?

    Use str.join:

    In [27]: mylist = ['10', '12', '14']
    
    In [28]: print '\n'.join(mylist)
    10
    12
    14
    

    How to remove all MySQL tables from the command-line without DROP database permissions?

    You can drop the database and then recreate it with the below:-

    mysql> drop database [database name];
    mysql> create database [database name];
    

    How to install a Notepad++ plugin offline?

    • Download and extract .zip file having all .dll plugin files under the path

      C:\ProgramData\Notepad++\plugins\

    • Make sure to create a separated folder for each plugin

    • Plugin (.dll) must be compatible with installed Notepad++ version (32 bit or 64 bit)

    Show or hide element in React

    with the newest version react 0.11 you can also just return null to have no content rendered.

    Rendering to null

    ENOENT, no such file or directory

    For me, it was having my code folder in Dropbox on windows 10. During the build process Dropbox would flip out over having more than 500,000 files. I moved my folder out and now it builds fine!

    Error: Can't set headers after they are sent to the client

    In my case this happened with React and postal.js when I didn't unsubscribe from a channel in the componentWillUnmount callback of my React component.

    Class extending more than one class Java?

    Java does not allow extending multiple classes.

    Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:

    C obj1 = new C(); obj1.method1(); - here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.

    Hope this has helped.

    How to set child process' environment variable in Makefile

    I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:

    test:
        ( NODE_ENV=test mocha --harmony --reporter spec test )
    

    Drawing Circle with OpenGL

    glBegin(GL_POLYGON);                        // Middle circle
    double radius = 0.2;
    double ori_x = 0.0;                         // the origin or center of circle
    double ori_y = 0.0;
    for (int i = 0; i <= 300; i++) {
        double angle = 2 * PI * i / 300;
        double x = cos(angle) * radius;
        double y = sin(angle) * radius;
        glVertex2d(ori_x + x, ori_y + y);
    }
    glEnd();
    

    Difference between .on('click') vs .click()

    They've now deprecated click(), so best to go with on('click')

    '"SDL.h" no such file or directory found' when compiling

    Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.

    Fortunately our friends from askUbuntu had something similar:

    Download SDL

    tar xvf SDL-1.2.tar.gz
    cd SDL-1.2
    ./configure
    make
    sudo make install
    

    Prevent nginx 504 Gateway timeout using PHP set_time_limit()

    I solve this trouble with config APACHE ! All methods (in this topic) is incorrect for me... Then I try chanche apache config:

    Timeout 3600

    Then my script worked!

    File uploading with Express 4.0: req.files undefined

    PROBLEM SOLVED !!!!!!!

    Turns out the storage function DID NOT run even once. because i had to include app.use(upload) as upload = multer({storage}).single('file');

     let storage = multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, './storage')
              },
              filename: function (req, file, cb) {
                console.log(file) // this didn't print anything out so i assumed it was never excuted
                cb(null, file.fieldname + '-' + Date.now())
              }
        });
    
        const upload = multer({storage}).single('file');
    

    How can we generate getters and setters in Visual Studio?

    If you're using ReSharper, go into the ReSharper menu → CodeGenerate...

    (Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)

    Index of Currently Selected Row in DataGridView

    try this

    bool flag = dg1.CurrentRow.Selected;
    
    if(flag)
    {
      /// datagridview  row  is  selected in datagridview rowselect selection mode
    
    }
    else
    {
      /// no  row is selected or last empty row is selected
    }
    

    How to read the Stock CPU Usage data

    From High Performance Android Apps book (page 157):

    • what we see is equivalent of adb shell dumpsys cpuinfo command
    • Numbers are showing CPU load over 1 minute, 5 minutes and 15 minutes (from the left)
    • Colors are showing time spent by CPU in user space (green), kernel (red) and IO interrupt (blue)

    Getting year in moment.js

    The year() function just retrieves the year component of the underlying Date object, so it returns a number.

    Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

    If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

    Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

    how to access parent window object using jquery?

    or you can use another approach:

    $( "#serverMsg", window.opener.document )
    

    What is the difference between canonical name, simple name and class name in Java Class?

    In addition to Nick Holt's observations, I ran a few cases for Array data type:

    //primitive Array
    int demo[] = new int[5];
    Class<? extends int[]> clzz = demo.getClass();
    System.out.println(clzz.getName());
    System.out.println(clzz.getCanonicalName());
    System.out.println(clzz.getSimpleName());       
    
    System.out.println();
    
    
    //Object Array
    Integer demo[] = new Integer[5]; 
    Class<? extends Integer[]> clzz = demo.getClass();
    System.out.println(clzz.getName());
    System.out.println(clzz.getCanonicalName());
    System.out.println(clzz.getSimpleName());
    

    Above code snippet prints:

    [I
    int[]
    int[]
    
    [Ljava.lang.Integer;
    java.lang.Integer[]
    Integer[]
    

    How to use jQuery in AngularJS

    This should be working. Please have a look at this fiddle.

    $(function() {
       $( "#slider" ).slider();
    });//Links to jsfiddle must be accompanied by code
    

    Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.

    Why is my toFixed() function not working?

    Your conversion data is response[25] and follow the below steps.

    var i = parseFloat(response[25]).toFixed(2)
    console.log(i)//-6527.34
    

    Casting interfaces for deserialization in JSON.NET

    For those that might be curious about the ConcreteListTypeConverter that was referenced by Oliver, here is my attempt:

    public class ConcreteListTypeConverter<TInterface, TImplementation> : JsonConverter where TImplementation : TInterface 
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var res = serializer.Deserialize<List<TImplementation>>(reader);
            return res.ConvertAll(x => (TInterface) x);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }
    }
    

    How to end C++ code

    Dude... exit() function is defined under stdlib.h

    So you need to add a preprocessor.

    Put include stdlib.h in the header section

    Then use exit(); wherever you like but remember to put an interger number in the parenthesis of exit.

    for example:

    exit(0);
    

    How to call a asp:Button OnClick event using JavaScript?

    If you're open to using jQuery:

    <script type="text/javascript">
     function fncsave()
     {
        $('#<%= savebtn.ClientID %>').click();
     }
    </script>
    

    Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

    <script type="text/javascript">
     function fncsave()
     {
        $("#savebtn").click();
     }
    </script>
    

    Reference: MSDN Article for Control.ClientIDMode

    FirstOrDefault returns NullReferenceException if no match is found

    You can use a combination of other LINQ methods to handle not matching condition:

    var res = dictionary.Where(x => x.Value.ID == someID)
                        .Select(x => x.Value.DisplayName)
                        .DefaultIfEmpty("Unknown")
                        .First();
    

    Remove duplicate values from JS array

    The most concise way to remove duplicates from an array using native javascript functions is to use a sequence like below:

    vals.sort().reduce(function(a, b){ if (b != a[0]) a.unshift(b); return a }, [])
    

    there's no need for slice nor indexOf within the reduce function, like i've seen in other examples! it makes sense to use it along with a filter function though:

    vals.filter(function(v, i, a){ return i == a.indexOf(v) })
    

    Yet another ES6(2015) way of doing this that already works on a few browsers is:

    Array.from(new Set(vals))
    

    or even using the spread operator:

    [...new Set(vals)]
    

    cheers!

    How to close the current fragment by using Button like the back button?

    You can try this logic because it is worked for me.

    frag_profile profile_fragment = new frag_profile();
    
    boolean flag = false;
    @SuppressLint("ResourceType")
    public void profile_Frag(){
        if (flag == false) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            manager.getBackStackEntryCount();
            transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
            transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
            transaction.commit();
            flag = true;
        }
    
    }
    
    @Override
    public void onBackPressed() {
        if (flag == true) {
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            manager.getBackStackEntryCount();
            transaction.remove(profile_fragment);
            transaction.commit();
            flag = false;
        }
        else super.onBackPressed();
    }
    

    Removing special characters VBA Excel

    In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.

    For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:

    Function cleanString(text As String) As String
        Dim output As String
        Dim c 'since char type does not exist in vba, we have to use variant type.
        For i = 1 To Len(text)
            c = Mid(text, i, 1) 'Select the character at the i position
            If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
                output = output & c 'add the character to your output.
            Else
                output = output & " " 'add the replacement character (space) to your output
            End If
        Next
        cleanString = output
    End Function
    

    The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.

    This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.

    How to scroll to top of a div using jQuery?

    You could just use:

    <div id="GridDiv">
    // gridview inside...
    </div>
    
    <a href="#GridDiv">Scroll to top</a>
    

    Are there constants in JavaScript?

    The const keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:

    const CONSTANT_NAME = 0;
    

    How to search text using php if ($text contains "World")

    What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:

    if(strstr($text, "world")) {/* do stuff */}
    

    Referring to the null object in Python

    None, Python's null?

    There's no null in Python; instead there's None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

    >>> foo is None
    True
    >>> foo = 'bar'
    >>> foo is None
    False
    

    The basics

    There is and can only be one None

    None is the sole instance of the class NoneType and any further attempts at instantiating that class will return the same object, which makes None a singleton. Newcomers to Python often see error messages that mention NoneType and wonder what it is. It's my personal opinion that these messages could simply just mention None by name because, as we'll see shortly, None leaves little room to ambiguity. So if you see some TypeError message that mentions that NoneType can't do this or can't do that, just know that it's simply the one None that was being used in a way that it can't.

    Also, None is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType by contrast is not, you'd need to get a reference to it first by querying None for its class.

    >>> NoneType
    NameError: name 'NoneType' is not defined
    >>> type(None)
    NoneType
    

    You can check None's uniqueness with Python's identity function id(). It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.

    >>> NoneType = type(None)
    >>> id(None)
    10748000
    >>> my_none = NoneType()
    >>> id(my_none)
    10748000
    >>> another_none = NoneType()
    >>> id(another_none)
    10748000
    >>> def function_that_does_nothing(): pass
    >>> return_value = function_that_does_nothing()
    >>> id(return_value)
    10748000
    

    None cannot be overwritten

    In much older versions of Python (before 2.4) it was possible to reassign None, but not any more. Not even as a class attribute or in the confines of a function.

    # In Python 2.7
    >>> class SomeClass(object):
    ...     def my_fnc(self):
    ...             self.None = 'foo'
    SyntaxError: cannot assign to None
    >>> def my_fnc():
            None = 'foo'
    SyntaxError: cannot assign to None
    
    # In Python 3.5
    >>> class SomeClass:
    ...     def my_fnc(self):
    ...             self.None = 'foo'
    SyntaxError: invalid syntax
    >>> def my_fnc():
            None = 'foo'
    SyntaxError: cannot assign to keyword
    

    It's therefore safe to assume that all None references are the same. There isn't any "custom" None.

    To test for None use the is operator

    When writing code you might be tempted to test for Noneness like this:

    if value==None:
        pass
    

    Or to test for falsehood like this

    if not value:
        pass
    

    You need to understand the implications and why it's often a good idea to be explicit.

    Case 1: testing if a value is None

    Why do

    value is None
    

    rather than

    value==None
    

    ?

    The first is equivalent to:

    id(value)==id(None)
    

    Whereas the expression value==None is in fact applied like this

    value.__eq__(None)
    

    If the value really is None then you'll get what you expected.

    >>> nothing = function_that_does_nothing()
    >>> nothing.__eq__(None)
    True
    

    In most common cases the outcome will be the same, but the __eq__() method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.

    Consider this class.

    >>> class Empty(object):
    ...     def __eq__(self, other):
    ...         return not other
    

    So you try it on None and it works

    >>> empty = Empty()
    >>> empty==None
    True
    

    But then it also works on the empty string

    >>> empty==''
    True
    

    And yet

    >>> ''==None
    False
    >>> empty is None
    False
    

    Case 2: Using None as a boolean

    The following two tests

    if value:
        # Do something
    
    if not value:
        # Do something
    

    are in fact evaluated as

    if bool(value):
        # Do something
    
    if not bool(value):
        # Do something
    

    None is a "falsey", meaning that if cast to a boolean it will return False and if applied the not operator it will return True. Note however that it's not a property unique to None. In addition to False itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__() magic method to return False.

    >>> bool(None)
    False
    >>> not None
    True
    
    >>> bool([])
    False
    >>> not []
    True
    
    >>> class MyFalsey(object):
    ...     def __bool__(self):
    ...         return False
    >>> f = MyFalsey()
    >>> bool(f)
    False
    >>> not f
    True
    

    So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:

    def some_function(value=None):
        if not value:
            value = init_value()
    

    In the above, did you mean to call init_value() when the value is set specifically to None, or did you mean that a value set to 0, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.

    None in practice

    None used as a signal value

    None has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).

    You can assign None to the keyword arguments of a function and then explicitly test for it.

    def my_function(value, param=None):
        if param is None:
            # Do something outrageous!
    

    You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.

    value = getattr(some_obj, 'some_attribute', None)
    if value is None:
        # do something spectacular!
    

    By default a dictionary's get() method returns None when trying to access a non-existing key:

    >>> some_dict = {}
    >>> value = some_dict.get('foo')
    >>> value is None
    True
    

    If you were to try to access it by using the subscript notation a KeyError would be raised

    >>> value = some_dict['foo']
    KeyError: 'foo'
    

    Likewise if you attempt to pop a non-existing item

    >>> value = some_dict.pop('foo')
    KeyError: 'foo'
    

    which you can suppress with a default value that is usually set to None

    value = some_dict.pop('foo', None)
    if value is None:
        # Booom!
    

    None used as both a flag and valid value

    The above described uses of None apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None came from because even though it's used as a signal it could also be part of the data.

    When you query an object for its attribute with getattr(some_obj, 'attribute_name', None) getting back None doesn't tell you if the attribute you were trying to access was set to None or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key'), you don't know if some_dict['some_key'] is missing or if it's just set to None. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except construct:

    try:
        # Equivalent to getattr() without specifying a default
        # value = getattr(some_obj, 'some_attribute')
        value = some_obj.some_attribute
        # Now you handle `None` the data here
        if value is None:
            # Do something here because the attribute was set to None
    except AttributeError:
        # We're now handling the exceptional situation from here.
        # We could assign None as a default value if required.
        value = None
        # In addition, since we now know that some_obj doesn't have the
        # attribute 'some_attribute' we could do something about that.
        log_something(some_obj)
    

    Similarly with dict:

    try:
        value = some_dict['some_key']
        if value is None:
            # Do something here because 'some_key' is set to None
    except KeyError:
        # Set a default
        value = None
        # And do something because 'some_key' was missing
        # from the dict.
        log_something(some_dict)
    

    The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:

    def my_function(**kwargs):
        try:
            value = kwargs['some_key']
            if value is None:
                # Do something because 'some_key' is explicitly
                # set to None
        except KeyError:
            # We assign the default
            value = None
            # And since it's not coming from the caller.
            log_something('did not receive "some_key"')
    

    None used only as a valid value

    If you find that your code is littered with the above try/except pattern simply to differentiate between None flags and None data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None is used as a signal. It's trivial to create a sentinel in Python.

    undefined = object()
    

    The undefined object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None as a flag. Some caveats apply, more about that after the code.

    With function

    def my_function(value, param1=undefined, param2=undefined):
        if param1 is undefined:
            # We know nothing was passed to it, not even None
            log_something('param1 was missing')
            param1 = None
    
    
        if param2 is undefined:
            # We got nothing here either
            log_something('param2 was missing')
            param2 = None
    

    With dict

    value = some_dict.get('some_key', undefined)
    if value is None:
        log_something("'some_key' was set to None")
    
    if value is undefined:
        # We know that the dict didn't have 'some_key'
        log_something("'some_key' was not set at all")
        value = None
    

    With an object

    value = getattr(obj, 'some_attribute', undefined)
    if value is None:
        log_something("'obj.some_attribute' was set to None")
    if value is undefined:
        # We know that there's no obj.some_attribute
        log_something("no 'some_attribute' set on obj")
        value = None
    

    As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None, so Python doesn't protect them. You can overwrite your undefined above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object() is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.

    SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

    One option is to put the subquery in a LEFT JOIN:

    select sum ( t.graduates ) - t1.summedGraduates 
    from table as t
        left join 
         ( 
            select sum ( graduates ) summedGraduates, id
            from table  
            where group_code not in ('total', 'others' )
            group by id 
        ) t1 on t.id = t1.id
    where t.group_code = 'total'
    group by t1.summedGraduates 
    

    Perhaps a better option would be to use SUM with CASE:

    select sum(case when group_code = 'total' then graduates end) -
        sum(case when group_code not in ('total','others') then graduates end)
    from yourtable
    

    SQL Fiddle Demo with both

    Build .NET Core console application to output an EXE

    The following will produce, in the output directory,

    • all the package references
    • the output assembly
    • the bootstrapping exe

    But it does not contain all .NET Core runtime assemblies.

    <PropertyGroup>
      <Temp>$(SolutionDir)\packaging\</Temp>
    </PropertyGroup>
    
    <ItemGroup>
      <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
    </ItemGroup>
    
    <Target Name="GenerateNetcoreExe"
            AfterTargets="Build"
            Condition="'$(IsNestedBuild)' != 'true'">
      <RemoveDir Directories="$(Temp)" />
      <Exec
        ConsoleToMSBuild="true"
        Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
        <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
      </Exec>
      <Copy
        SourceFiles="@(BootStrapFiles)"
        DestinationFolder="$(OutputPath)"
      />
    
    </Target>
    

    I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole

    R Not in subset

    The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

    !(df1$id %in% idNums1)
    

    Escape a string in SQL Server so that it is safe to use in LIKE expression

    Do you want to look for strings that include an escape character? For instance you want this:

    select * from table where myfield like '%10%%'.
    

    Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.

    select * from table where myfield like '%10!%%' ESCAPE '!'
    

    Select NOT IN multiple columns

    Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

    Be aware of pitfalls with NOT IN, though, when involving any NULL values:

    Variant with LEFT JOIN:

    SELECT *
    FROM   friend f
    LEFT   JOIN likes l USING (id1, id2)
    WHERE  l.id1 IS NULL;
    

    See @Michal's answer for the NOT EXISTS variant.
    A more detailed assessment of four basic variants:

    Mercurial stuck "waiting for lock"

    I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:

    1. I've seen this in the wild, but rarely, and only on Windows machines.
    2. Deleting lock files is the easiest fix, BUT you have to make sure nothing else is accessing the repository. (If the lock is a string of zeros, this is almost certainly true).

    (For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)

    svn cleanup: sqlite: database disk image is malformed

    I copied over .svn folder from my peer worker's directory and that fixed the issue.

    Python Pandas : group by in group by and average?

    I would simply do this, which literally follows what your desired logic was:

    df.groupby(['org']).mean().groupby(['cluster']).mean()
    

    what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

    Simply, @Id: This annotation specifies the primary key of the entity. 
    
    @GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 
    
    GenerationType enum defines four strategies: 
    1. Generation Type . TABLE, 
    2. Generation Type. SEQUENCE,
    3. Generation Type. IDENTITY   
    4. Generation Type. AUTO
    
    GenerationType.SEQUENCE
    
    With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 
    
    GenerationType.TABLE
    
    With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 
    
    GenerationType.IDENTITY
    This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
    
    GenerationType.AUTO
    This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 
    

    Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

    How to get child element by ID in JavaScript?

    $(selectedDOM).find();
    

    function looking for all dom objects inside the selected DOM. i.e.

    <div id="mainDiv">
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <div id="innerDiv">
             <a href="#">link</a>
             <p>Paragraph 3</p>
        </div>
    </div>
    

    here if you write;

    $("#mainDiv").find("p");
    

    you will get tree p elements together. On the other side,

    $("#mainDiv").children("p");
    

    Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

    Why can a function modify some arguments as perceived by the caller, but not others?

    It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].

    You should declare your function f() like this:

    def f(n, x=None):
        if x is None:
            x = []
        ...
    

    How to solve a timeout error in Laravel 5

    Options -MultiViews -Indexes

    RewriteEngine On
    
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
    
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    
    #cambiamos el valor para subir archivos
    php_value memory_limit 400M
    php_value post_max_size 400M
    php_value upload_max_filesize 400M
    php_value max_execution_time 300 #esta es la linea que necesitas agregar.
    

    git discard all changes and pull from upstream

    I finally realized now that instead of

    git fetch --all && git reset --hard origin/master
    

    it should be

    git fetch --all && git reset --hard origin/<branch_name>
    

    instead (if one works on a different branch)

    Regex matching beginning AND end strings

    ^dbo\..*_fn$
    

    This should work you.

    adding a datatable in a dataset

    Just give any name to the DataTable Like:

    DataTable dt = new DataTable();
    dt = SecondDataTable.Copy();    
    dt .TableName = "New Name";
    DataSet.Tables.Add(dt );
    

    Simulate delayed and dropped packets on Linux

    One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:

    ./ipfw pipe 1 config delay 50ms
    ./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2
    

    In order to also introduce 50% of packet losses you have to run:

    ./ipfw pipe 1 config plr 0.5
    

    Here more details.

    How to make an installer for my C# application?

    1. Add a new install project to your solution.
    2. Add targets from all projects you want to be installed.
    3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
    4. Configure your installer settings - company name, version, copyright, etc.
    5. Build and go!

    How to create an instance of System.IO.Stream stream

    Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

    How to close a thread from within?

    If you want force stop your thread: thread._Thread_stop() For me works very good.

    Laravel - Eloquent or Fluent random row

    You can also use order_by method with fluent and eloquent like as:

    Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()')); 
    

    This is a little bit weird usage, but works.

    Edit: As @Alex said, this usage is cleaner and also works:

    Posts::where_status(1)->order_by(DB::raw('RAND()'));
    

    Negative matching using grep (match lines that do not contain foo)

    You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

    Lines not containing foo:

    awk '!/foo/'
    

    Lines containing neither foo nor bar:

    awk '!/foo/ && !/bar/'
    

    Lines containing neither foo nor bar which contain either foo2 or bar2:

    awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'
    

    And so on.

    Error handling in getJSON calls

    $.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

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

    You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

    'generic' would be something like:

    $.ajaxSetup({
          "error":function() { alert("error");  }
    });
    

    And the 'specific' way:

    $.getJSON("example.json", function() {
      alert("success");
    })
    .done(function() { alert("second success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });
    

    java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

    Add the following dependency to your pom.xml

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.2</version>
    </dependency>
    

    Splitting a dataframe string column into multiple different columns

    Is this what you are trying to do?

    # Our data
    text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
    "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
    "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
    )
    
    #  Split into individual elements by the '.' character
    #  Remember to escape it, because '.' by itself matches any single character
    elems <- unlist( strsplit( text , "\\." ) )
    
    #  We know the dataframe should have 4 columns, so make a matrix
    m <- matrix( elems , ncol = 4 , byrow = TRUE )
    
    #  Coerce to data.frame - head() is just to illustrate the top portion
    head( as.data.frame( m ) )
    #  V1 V2  V3  V4
    #1  F US CLE V13
    #2  F US CA6 U13
    #3  F US CA6 U13
    #4  F US CA6 U13
    #5  F US CA6 U13
    #6  F US CA6 U13