Programs & Examples On #Flexible array member

How can I create an array/list of dictionaries in python?

Use

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

XSL substring and indexOf

There is a substring function in XSLT. Example here.

Export and Import all MySQL databases at one time

Based on these answers I've made script which backups all databases into separate files, but then compress them into one archive with date as name.

This will not ask for password, can be used in cron. To store password in .my.cnf check this answer https://serverfault.com/a/143587/62749

Made also with comments for those who are not very familiar with bash scripts.

#!/bin/bash

# This script will backup all mysql databases into 
# compressed file named after date, ie: /var/backup/mysql/2016-07-13.tar.bz2

# Setup variables used later

# Create date suffix with "F"ull date format
suffix=$(date +%F)
# Retrieve all database names except information schemas. Use sudo here to skip root password.
dbs=$(sudo mysql --defaults-extra-file=/root/.my.cnf --batch --skip-column-names -e "SHOW DATABASES;" | grep -E -v "(information|performance)_schema")
# Create temporary directory with "-d" option
tmp=$(mktemp -d)
# Set output dir here. /var/backups/ is used by system, 
# so intentionally used /var/backup/ for user backups.
outDir="/var/backup/mysql"
# Create output file name
out="$outDir/$suffix.tar.bz2"

# Actual script

# Check if output directory exists
if [ ! -d "$outDir" ];then
  # Create directory with parent ("-p" option) directories
  sudo mkdir -p "$outDir"
fi

# Loop through all databases
for db in $dbs; do
  # Dump database to temporary directory with file name same as database name + sql suffix
  sudo mysqldump --defaults-extra-file=/root/.my.cnf --databases "$db" > "$tmp/$db.sql"
done

# Go to tmp dir
cd $tmp

# Compress all dumps with bz2, discard any output to /dev/null
sudo tar -jcf "$out" * > "/dev/null"

# Cleanup
cd "/tmp/"
sudo rm -rf "$tmp"

Failed to find target with hash string 'android-25'

You can open the SDK standalone by going to installation directory, just right click on the SDK Manager.exe and click on run as Administrator. i hope it will help.

How to use custom font in a project written in Android Studio

Hello here we have a better way to apply fonts on EditTexts and TextViews on android at once and apply it in whole project.

First of All you need to make fonts folder. Here are Steps.

1: Go to the (project folder) Then app>src>main

2: Create folders named 'assets/fonts' into the main folder.

3: Put your fonts into the fonts folder. Here I Have 'MavenPro-Regular.ttf'

Here are the Steps for applying custom fonts on EditText and using this approach you can apply fonts on every input.

1 : Create a Class MyEditText (your preferred name ...)

2 : which extends EditText

3 : Apply your font

Here is code Example;

public class MyEditText extends EditText {

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyEditText(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MavenPro-Regular.ttf");
            setTypeface(tf);
        }
    }

}

And in Here is the code how to use it.

MyEditText editText = (MyEditText) findViewById(R.id.editText);

editText.setText("Hello");

Or in Your xml File

   <MyEditText
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textColor="#fff"
    android:textSize="16dp"
    android:id="@+id/editText"
    />

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

What is `related_name` used for in Django?

The related_name argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:

class UserMapDataFrame(models.Model):
    user = models.ForeignKey(User) 

In order to access UserMapDataFrame objects from the related User, the default call would be User.usermapdataframe_set.all(), which it is quite difficult to read.

Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='map_data'), the call would then be User.map_data.all().

What is a segmentation fault?

To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.

They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are

  1. Used before being properly initialised
  2. Used after the memory they point to has been realloced or deleted.
  3. Used in an indexed array where the index is outside of the array bounds. This is generally only when you're doing pointer math on traditional arrays or c-strings, not STL / Boost based collections (in C++.)

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves

Is it possible to use raw SQL within a Spring Repository

It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.

It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.

How do I declare a global variable in VBA?

Create a public integer in the General Declaration.

Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).

Public Numerator As Integer

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String

saveFolder = "c:\temp\"

     For Each objAtt In itm.Attachments
            FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
                      objAtt.SaveAsFile saveFolder & "\" & FileName
                      Numerator = Numerator + 1

          Set objAtt = Nothing
     Next
End Sub

Comma separated results in SQL

For Sql Server 2017 and later you can use the new STRING_AGG function

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.

SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv 
FROM Person.Person;

Here is the result set.

John,N/A,Mike,Peter,N/A,N/A,Alice,Bob

Perhaps a more common use case is to group together and then aggregate, just like you would with SUM, COUNT or AVG.

SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags 
FROM dbo.Article AS a       
LEFT JOIN dbo.ArticleTag AS t 
    ON a.ArticleId = t.ArticleId 
GROUP BY a.articleId, title;

AngularJS : ng-click not working

i tried using the same ng-click for two elements with same name showDetail2('abc')

it is working for me . can you check rest of the code which may be breaking you to move further.

here is the sample jsfiddle i tried:

batch file - counting number of files in folder and storing in a variable

The fastest code for counting files with ANY attributes in folder %FOLDER% and its subfolders is the following. The code is for script in a command script (batch) file.

@for /f %%a in ('2^>nul dir "%FOLDER%" /a-d/b/-o/-p/s^|find /v /c ""') do set n=%%a
@echo Total files: %n%.

Check if int is between two numbers

You are human, and therefore you understand what the term "10 < x < 20" suppose to mean. The computer doesn't have this intuition, so it reads it as: "(10 < x) < 20".

For example, if x = 15, it will calculate:

(10 < x) => TRUE

"TRUE < 20" => ???

In C programming, it will be worse, since there are no True\False values. If x = 5, the calculation will be:

10 < x => 0 (the value of False)

0 < 20 => non-0 number (True)

and therefore "10 < 5 < 20" will return True! :S

How to use CMAKE_INSTALL_PREFIX

That should be (see the docs):

cmake -DCMAKE_INSTALL_PREFIX=/usr ..

How to Sort a List<T> by a property in the object

A Classical Object Oriented Solution

First I must genuflect to the awesomeness of LINQ.... Now that we've got that out of the way

A variation on JimmyHoffa answer. With generics the CompareTo parameter becomes type safe.

public class Order : IComparable<Order> {

    public int CompareTo( Order that ) {
        if ( that == null ) return 1;
        if ( this.OrderDate > that.OrderDate) return 1;
        if ( this.OrderDate < that.OrderDate) return -1;
        return 0;
    }
}

// in the client code
// assume myOrders is a populated List<Order>
myOrders.Sort(); 

This default sortability is re-usable of course. That is each client does not have to redundantly re-write the sorting logic. Swapping the "1" and "-1" (or the logic operators, your choice) reverses the sort order.

Dynamically add child components in React

First, I wouldn't use document.body. Instead add an empty container:

index.html:

<html>
    <head></head>
    <body>
        <div id="app"></div>
    </body>
</html>

Then opt to only render your <App /> element:

main.js:

var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));

Within App.js you can import your other components and ignore your DOM render code completely:

App.js:

var SampleComponent = require('./SampleComponent.js');

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component!</h1>
                <SampleComponent name="SomeName" />
            </div>
        );
    }
});

SampleComponent.js:

var SampleComponent = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Sample Component!</h1>
            </div>
        );
    }
});

Then you can programmatically interact with any number of components by importing them into the necessary component files using require.

Error Running React Native App From Terminal (iOS)

By default, after installing Xcode command-line not selected, so open Xcode and go to Preferences >> Locations and set Command Line Tools...

This worked for me in MAC High Sierra, Xcode Version 9.3:

Xcode Preferences

Press i to open iOS emulator...

Press a to open Android device or emulator, or i to open iOS emulator.

And You can see a cool new iPhone simulator like below image:

React Native prints, I'm Alireza Dezfoolian, a Front End Developer!

How do I remove the file suffix and path portion from a path string in Bash?

The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.

How to run Gradle from the command line on Mac bash

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

You can install gradle with homebrew with the following command:

$ brew install gradle

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

$ gradle test 

Match line break with regular expression

You could search for:

<li><a href="#">[^\n]+

And replace with:

$0</a>

Where $0 is the whole match. The exact semantics will depend on the language are you using though.


WARNING: You should avoid parsing HTML with regex. Here's why.

Winforms TableLayoutPanel adding rows programmatically

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        Dim dc As DataColumn
        dc = New DataColumn("Question", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        dc = New DataColumn("Ans1", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans2", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans3", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Ans4", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("AnsType", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)


        Dim Dr As DataRow
        Dr = dt.NewRow
        Dr("Question") = "What is Your Name"
        Dr("Ans1") = "Ravi"
        Dr("Ans2") = "Mohan"
        Dr("Ans3") = "Sohan"
        Dr("Ans4") = "Gopal"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)

        Dr = dt.NewRow
        Dr("Question") = "What is your father Name"
        Dr("Ans1") = "Ravi22"
        Dr("Ans2") = "Mohan2"
        Dr("Ans3") = "Sohan2"
        Dr("Ans4") = "Gopal2"
        Dr("AnsType") = "Multi"
        dt.Rows.Add(Dr)
        Panel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows
        Panel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
        Panel1.BackColor = Color.Azure
        Panel1.RowStyles.Insert(0, New RowStyle(SizeType.Absolute, 50))
        Dim i As Integer = 0

        For Each dri As DataRow In dt.Rows



            Dim lab As New Label()
            lab.Text = dri("Question")
            lab.AutoSize = True

            Panel1.Controls.Add(lab, 0, i)


            Dim Ans1 As CheckBox
            Ans1 = New CheckBox()
            Ans1.Text = dri("Ans1")
            Panel1.Controls.Add(Ans1, 1, i)

            Dim Ans2 As RadioButton
            Ans2 = New RadioButton()
            Ans2.Text = dri("Ans2")
            Panel1.Controls.Add(Ans2, 2, i)
            i = i + 1

            'Panel1.Controls.Add(Pan)
        Next

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

i was also getting this error, remove oracle folder from

C:\Program Files (x86)\Oracle\Inventory

and

C:\Program Files\Oracle\Inventory

Also remove all component of oracle other version (which you had already in your system).

Go to services and remove all oracle component and delete old client from

C:\app\username\product\11.2.0\client_1\

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

How can I pass command-line arguments to a Perl program?

If the arguments are filenames to be read from, use the diamond (<>) operator to get at their contents:

while (my $line = <>) {
  process_line($line);
}

If the arguments are options/switches, use GetOpt::Std or GetOpt::Long, as already shown by slavy13.myopenid.com.

On the off chance that they're something else, you can access them either by walking through @ARGV explicitly or with the shift command:

while (my $arg = shift) {
  print "Found argument $arg\n";
}

(Note that doing this with shift will only work if you are outside of all subs. Within a sub, it will retrieve the list of arguments passed to the sub rather than those passed to the program.)

How to verify that a specific method was not called using Mockito?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

There are actually many ways to achieve this, however it's (arguably) cleaner to use the

verify(yourMock, times(0)).someMethod();

method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:

verify(yourMock, times(5)).someMethod();

Alternatives are:

verify(yourMock, never()).someMethod();

Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:

verifyZeroInteractions(yourMock)

Add a month to a Date

The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:

date_1m_fwd     <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1

Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.

Still you can perform the add month using basic R codes as follows:

library(data.table)  
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))  
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]

Hope it helps.

Check if input is integer type in C

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    printf("failure\n");
else
    printf("valid integer followed by enter key\n");

Range with step of type float

In order to be able to use decimal numbers in a range expression a cool way for doing it is the following: [x * 0.1 for x in range(0, 10)]

PL/SQL, how to escape single quote in a string?

In addition to DCookie's answer above, you can also use chr(39) for a single quote.

I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.

Here's a very quick example:

Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.

Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
       'VALUES (' || chr(39) || FirstName || chr(39) ',' || 
       chr(39) || LastName || chr(39) || ');' From Customers;

I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.

Reusing output from last command in Bash

Like konsolebox said, you'd have to hack into bash itself. Here is a quite good example on how one might achieve this. The stderred repository (actually meant for coloring stdout) gives instructions on how to build it.

I gave it a try: Defining some new file descriptor inside .bashrc like

exec 41>/tmp/my_console_log

(number is arbitrary) and modify stderred.c accordingly so that content also gets written to fd 41. It kind of worked, but contains loads of NUL bytes, weird formattings and is basically binary data, not readable. Maybe someone with good understandings of C could try that out.

If so, everything needed to get the last printed line is tail -n 1 [logfile].

What is the difference between . (dot) and $ (dollar sign)?

The short and sweet version:

  • ($) calls the function which is its left-hand argument on the value which is its right-hand argument.
  • (.) composes the function which is its left-hand argument on the function which is its right-hand argument.

How can I scale an entire web page with CSS?

If your CSS is constructed completely around ex or em units, then this might be possible and feasible. You'd just need to declare font-size: 150% in your style for body or html. This should cause every other lengths to scale proportionally. You can't scale images this way, though, unless they get a style too.

But that's a very big if on most sites, anyway.

Multi-Line Comments in Ruby?

#!/usr/bin/env ruby

=begin
Between =begin and =end, any number
of lines may be written. All of these
lines are ignored by the Ruby interpreter.
=end

puts "Hello world!"

Cannot install signed apk to device manually, got error "App not installed"

You don't have to uninstall the Google Play version if App Signing by Google Play is enabled for your app, follow the steps:
1. Make a signed version of your app with your release key
2. Go to Google Play Developer console
3. Create a closed track release (alpha or beta release) with the new signed version of your app
4. You can now download the apk signed by App Signing by Google Play, choose derived APKenter image description here

  1. Install the downloaded derived APK

The reason is App Signing by Google Play signs release apps with different keys, if you have an app installed from Play Store, and you want to test the new release version app (generated from Android Studio) in your phone, "App not installed" happens since the old version and the new version were signed by two different keys: one with App Signing by Google Play and one with your key.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

I could be because you might have not restarted PHP artisan since long

So After making DB changes and config:clear Tinker works fine

But to make browser refect the new DB connection you need to re-run

php artisan serve

'str' object does not support item assignment in Python

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

How to set a header in an HTTP response?

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

========================

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

Change content of div - jQuery

You could subscribe for the .click event for the links and change the contents of the div using the .html method:

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').html(linkText);

    // cancel the default action of the link by returning false
    return false;
});

Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate method to attach the handler.

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

use MM(months) instead of mm(minutes) :

DateTime.Now.ToString("dd/MM/yyyy");

check here for more format options.

Why is the Java main method static?

When you execute the Java Virtual Machine (JVM) with the java command,

java ClassName argument1 argument2 ...

When you execute your application, you specify its class name as an argument to the java command, as above

the JVM attempts to invoke the main method of the class you specify

—at this point, no objects of the class have been created.

Declaring main as static allows the JVM to invoke main without creating an instance of the class.

let's back to the command

ClassName is a command-line argument to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings (separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args in the main

References:Java™ How To Program (Early Objects), Tenth Edition

How do I import a specific version of a package using go get?

It might be useful.

Just type this into your command prompt while cd your/package/src/

go get github.com/go-gl/[email protected]

You get specific revision of package in question right into your source code, ready to use in import statement.

Laravel Eloquent "WHERE NOT IN"

The dynamic way of implement whereNotIn:

 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

Lua - Current time in milliseconds

Get current time in milliseconds.

os.time()

os.time()
return sec // only

posix.clock_gettime(clk)

https://luaposix.github.io/luaposix/modules/posix.time.html#clock_gettime

require'posix'.clock_gettime(0)
return sec, nsec

linux/time.h // man clock_gettime

/*
 * The IDs of the various system clocks (for POSIX.1b interval timers):
 */
#define CLOCK_REALTIME                  0
#define CLOCK_MONOTONIC                 1
#define CLOCK_PROCESS_CPUTIME_ID        2
#define CLOCK_THREAD_CPUTIME_ID         3
#define CLOCK_MONOTONIC_RAW             4
#define CLOCK_REALTIME_COARSE           5
#define CLOCK_MONOTONIC_COARSE          6

socket.gettime()

http://w3.impa.br/~diego/software/luasocket/socket.html#gettime

require'socket'.gettime()
return sec.xxx

as waqas says


compare & test

get_millisecond.lua

local posix=require'posix'
local socket=require'socket'

for i=1,3 do
    print( os.time() )
    print( posix.clock_gettime(0) )
    print( socket.gettime() )
    print''
    posix.nanosleep(0, 1) -- sec, nsec
end

output

lua get_millisecond.lua
1490186718
1490186718      268570540
1490186718.2686

1490186718
1490186718      268662191
1490186718.2687

1490186718
1490186718      268782765
1490186718.2688

Add 10 seconds to a Date

Try this way.

Date.prototype.addSeconds = function(seconds) {
  var copiedDate = new Date(this.getTime());
  return new Date(copiedDate.getTime() + seconds * 1000);
}

Just call and assign new Date().addSeconds(10)

IOError: [Errno 2] No such file or directory trying to open a file

Just as an FYI, here is my working code:

src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"

for f in os.listdir(src_dir):
    file_name = os.path.join(src_dir, f)
    out_file = os.path.join(target_dir, f)
    with open(file_name, "r+") as fi, open(out_file, "w") as fo:
        for line in fi:
            if keyword not in line:
                fo.write(line)

Thanks again to everyone for all the great feedback!

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

How can I plot with 2 different y-axes?

I too suggests, twoord.stackplot() in the plotrix package plots with more of two ordinate axes.

data<-read.table(text=
"e0AL fxAL e0CO fxCO e0BR fxBR anos
 51.8  5.9 50.6  6.8 51.0  6.2 1955
 54.7  5.9 55.2  6.8 53.5  6.2 1960
 57.1  6.0 57.9  6.8 55.9  6.2 1965
 59.1  5.6 60.1  6.2 57.9  5.4 1970
 61.2  5.1 61.8  5.0 59.8  4.7 1975
 63.4  4.5 64.0  4.3 61.8  4.3 1980
 65.4  3.9 66.9  3.7 63.5  3.8 1985
 67.3  3.4 68.0  3.2 65.5  3.1 1990
 69.1  3.0 68.7  3.0 67.5  2.6 1995
 70.9  2.8 70.3  2.8 69.5  2.5 2000
 72.4  2.5 71.7  2.6 71.1  2.3 2005
 73.3  2.3 72.9  2.5 72.1  1.9 2010
 74.3  2.2 73.8  2.4 73.2  1.8 2015
 75.2  2.0 74.6  2.3 74.2  1.7 2020
 76.0  2.0 75.4  2.2 75.2  1.6 2025
 76.8  1.9 76.2  2.1 76.1  1.6 2030
 77.6  1.9 76.9  2.1 77.1  1.6 2035
 78.4  1.9 77.6  2.0 77.9  1.7 2040
 79.1  1.8 78.3  1.9 78.7  1.7 2045
 79.8  1.8 79.0  1.9 79.5  1.7 2050
 80.5  1.8 79.7  1.9 80.3  1.7 2055
 81.1  1.8 80.3  1.8 80.9  1.8 2060
 81.7  1.8 80.9  1.8 81.6  1.8 2065
 82.3  1.8 81.4  1.8 82.2  1.8 2070
 82.8  1.8 82.0  1.7 82.8  1.8 2075
 83.3  1.8 82.5  1.7 83.4  1.9 2080
 83.8  1.8 83.0  1.7 83.9  1.9 2085
 84.3  1.9 83.5  1.8 84.4  1.9 2090
 84.7  1.9 83.9  1.8 84.9  1.9 2095
 85.1  1.9 84.3  1.8 85.4  1.9 2100", header=T)

require(plotrix)
twoord.stackplot(lx=data$anos, rx=data$anos, 
                 ldata=cbind(data$e0AL, data$e0BR, data$e0CO),
                 rdata=cbind(data$fxAL, data$fxBR, data$fxCO),
                 lcol=c("black","red", "blue"),
                 rcol=c("black","red", "blue"), 
                 ltype=c("l","o","b"),
                 rtype=c("l","o","b"), 
                 lylab="Años de Vida", rylab="Hijos x Mujer", 
                 xlab="Tiempo",
                 main="Mortalidad/Fecundidad:1950–2100",
                 border="grey80")
legend("bottomright", c(paste("Proy:", 
                      c("A. Latina", "Brasil", "Colombia"))), cex=1,
        col=c("black","red", "blue"), lwd=2, bty="n",  
        lty=c(1,1,2), pch=c(NA,1,1) )

How to access the last value in a vector?

If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom is

x[length(x)]  

but it's easy enough to write a function to do this:

last <- function(x) { return( x[length(x)] ) }

This missing feature in R annoys me too!

In Perl, how can I read an entire file into a string?

Another possible way:

open my $fh, '<', "filename";
read $fh, my $string, -s $fh;
close $fh;

How to get the Google Map based on Latitude on Longitude?

this is the javascript to display google map by passing your longitude and latitude.

<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    function loadScript() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
      document.body.appendChild(script);
    }

    window.onload = loadScript;


</script>

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

/usr/bin/codesign failed with exit code 1

What worked for me was adding --deep to Other Code Signing Flags in Build Settings. More information here: Codesign of Dropbox API fails in Xcode 4.6.3: "code object is not signed at all"

Unfortunate that this ambiguous error condition has 400 different solutions, but I digress.

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

I get Access Forbidden (Error 403) when setting up new alias

This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.

First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...

    NameVirtualHost     local.webapp.org
    <VirtualHost local.webapp.org:80>
        ServerAdmin [email protected]
        DocumentRoot "E:/Project/my php webapp"
        ServerName local.webapp.org
    </VirtualHost>

Note the way DocumentRoot line is written.

Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.

    <Directory>
        AllowOverride none
        Require all denied
    </Directory>

Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.

    <Directory>
       Options Indexes FollowSymLinks Includes ExecCGI
       AllowOverride none
       Require all granted
    </Directory>

Where can I find Android source code online?

I've found a way to get only the Contacts application:

git clone https://android.googlesource.com/platform/packages/apps/Contacts

which is good enough for me for now, but doesn't answer the question of browsing the code on the web.

What does %5B and %5D in POST requests stand for?

[] is replaced by %5B%5D at URL encoding time.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

You need to let Gson know additional type of your response as below

import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;


Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites  = gson.fromJson( response.getBody() , collectionType);

Remove all unused resources from an android project

Since Support for the ADT in Eclipse has ended, we have to use Android Studio.

In Android Studio 2.0+ use Refactor > Remove Unused Resources...

enter image description here

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Hope this answer will help,Multiple Value Filter

And working example in this fiddle

arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}

Add rows to CSV File in powershell

To simply append to a file in powershell,you can use add-content.

So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.

$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file

Or,

"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file

This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.

How can I calculate the time between 2 Dates in typescript

Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:

var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();

Apache - MySQL Service detected with wrong path. / Ports already in use

To delete existing service is not good solution for me, because on port 3306 run MySQL, which need other service. But it is possible to run two MySQL services at one time (one with other name and port). I found the solution here: http://emjaywebdesigns.com/xampp-and-multiple-instances-of-mysql-on-windows/

Here is my modified setting: Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

Open Windows Services and set Startup Type: Automatic, Start the service

Maintaining href "open in new tab" with an onClick handler in React

Most Secure Solution, JS only

As mentioned by alko989, there is a major security flaw with _blank (details here).

To avoid it from pure JS code:

const openInNewTab = (url) => {
  const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
  if (newWindow) newWindow.opener = null
}

Then add to your onClick

onClick={() => openInNewTab('https://stackoverflow.com')}

The third param can also take these optional values, based on your needs.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

You are running the Command Prompt as an admin. You have only defined PYTHON for your user. You need to define it in the bottom "System variables" section.

Also, you should only point the variable to the folder, not directly to the executable.

How to remove a column from an existing table?

Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.

If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.

Another option is to find all referencing columns and remove them as well if they are not needed any longer.

In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here

AngularJS - add HTML element to dom in directive without jQuery

If your destination element is empty and will only contain the <svg> tag you could consider using ng-bind-html as follow :

Declare your HTML tag in the directive scope variable

link: function (scope, iElement, iAttrs) {

    scope.svgTag = '<svg width="600" height="100" class="svg"></svg>';

    ...
}

Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :

<!-- start of directive template code -->
...
<!-- end of directive template code -->
<div ng-bind-html="svgTag"></div>

Don't forget to include ngSanitize to allow ng-bind-html to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.

See official documentation for more details.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

How to import a module given its name as string?

If you want it in your locals:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

same would work with globals()

Position a div container on the right side

if you don't want to use float

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

Prevent HTML5 video from being downloaded (right-click saved)?

First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.

A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.

You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well - you should.

You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that.". As suggested in this answer.

This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.

Here is a CSS trick you could use:

video {
    pointer-events: none;
}

CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls cannot be enabled either, in other words they must be set to false. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video tag then this is a feasible option.

controls also has a download button so using it is not such a good idea either.

Here is a JSFiddle example.


If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).

From TxRegex answer:

<video oncontextmenu="return false;" controls>
    <source type="video/mp4" id="video">
</video>

Now add the video via JavaScript:

document.getElementById("video").src = "https://www.w3schools.com/html/mov_bbb.mp4";

Functional JSFiddle


Another way to prevent right click involves using the embed tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:

<embed src="https://www.w3schools.com/html/mov_bbb.mp4"></embed>

How to write palindrome in JavaScript

Here is a 1 line program to check if your string is a palindrome :-

((s) => `Is ${s} a palindrome ? \n Answer is :- ${s.split('').reverse().join('') == s}`)('bob')

Just modify the last parameter of this IIFE to check different inputs. This is perhaps the best solution.

Matplotlib scatter plot legend

2D scatter plot

Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry.

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

3D scatter plot

To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

Compare two dates with JavaScript

Just to add yet another possibility to the many existing options, you could try:

if (date1.valueOf()==date2.valueOf()) .....

...which seems to work for me. Of course you do have to ensure that both dates are not undefined...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

This way we can ensure that a positive comparison is made if both are undefined also, or...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

...if you prefer them not to be equal.

Is it possible to use an input value attribute as a CSS selector?

In Chrome 72 (2019-02-09) I've discovered that the :in-range attribute is applied to empty date inputs, for some reason!

So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:

input[type=date]:not([max]):not([min]):in-range {
    color: blue;
}

Screenshot:


enter image description here


Here's a runnable sample:

_x000D_
_x000D_
window.addEventListener( 'DOMContentLoaded', onLoad );_x000D_
_x000D_
function onLoad() {_x000D_
    _x000D_
    document.getElementById( 'date4' ).value = "2019-02-09";_x000D_
    _x000D_
    document.getElementById( 'date5' ).value = null;_x000D_
    _x000D_
}
_x000D_
label {_x000D_
    display: block;_x000D_
    margin: 1em;_x000D_
}_x000D_
_x000D_
input[type=date]:not([max]):not([min]):in-range {_x000D_
    color: blue;_x000D_
}
_x000D_
<label>_x000D_
    <input type="date" id="date1" />_x000D_
    Without HTML value=""_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date2" value="2019-02-09" />_x000D_
    With HTML value=""_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
    <input type="date" id="date3" />_x000D_
    Without HTML value="" but modified by user_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date4" />_x000D_
    Without HTML value="" but set by script_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date5" value="2019-02-09" />_x000D_
    With HTML value="" but cleared by script_x000D_
</label>
_x000D_
_x000D_
_x000D_

retrieve links from web page using python and BeautifulSoup

Why not use regular expressions:

import urllib2
import re
url = "http://www.somewhere.com"
page = urllib2.urlopen(url)
page = page.read()
links = re.findall(r"<a.*?\s*href=\"(.*?)\".*?>(.*?)</a>", page)
for link in links:
    print('href: %s, HTML text: %s' % (link[0], link[1]))

How can I select all elements without a given class in jQuery?

You could use this to pick all li elements without class:

$('ul#list li:not([class])')

SelectSingleNode returning null for known good xml node path using XPath

Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:

private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
    {
        XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
        XPathNavigator RootNode = xDoc.CreateNavigator();
        RootNode.MoveToFollowing(XPathNodeType.Element);
        IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);

        foreach (KeyValuePair<string, string> kvp in NameSpaces)
        {
            nsm.AddNamespace(kvp.Key, kvp.Value);
        }

        return nsm;
    }

Invalidating JSON Web Tokens

I would keep a record of the jwt version number on the user model. New jwt tokens would set their version to this.

When you validate the jwt, simply check that it has a version number equal to the users current jwt version.

Any time you want to invalidate old jwts, just bump the users jwt version number.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

Removing cordova plugins from the project

From the terminal (osx) I usually use

cordova plugin -l | xargs cordova plugins rm

Pipe, pipe everything!

To expand a bit: this command will loop through the results of cordova plugin -l and feed it to cordova plugins rm.

xargs is one of those commands that you wonder why you didn't know about before. See this tut.

Auto-indent in Notepad++

First download plugin manager this link then unzip the zip folder and copy this inside your program/ notepad++ folder . then restart your notepad++. then you see plugin manager inside plugin menu . then click plugin manager then click show plugin manager . It shows all your plugin list . from the list in bottom find XML tools , checked it and install it. then restart your notepad++. After open a document then plugins/xml tools/pretty plain(indent text) then enjoy.

How to get selected value of a dropdown menu in ReactJS

If you want to get value from a mapped select input then you can refer to this example:

class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          fruit: "banana",
        };
    
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        console.log("Fruit Selected!!");
        this.setState({ fruit: e.target.value });
      }
    
      render() {
        return (
          <div id="App">
            <div className="select-container">
              <select value={this.state.fruit} onChange={this.handleChange}>
                {options.map((option) => (
                  <option value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>
          </div>
        );
      }
    }
    
    export default App;

How to get an array of unique values from an array containing duplicates in JavaScript?

function array_unique(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
        }
    }
    return result;
}

Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.

Undoing a git rebase

Let's say I rebase master to my feature branch and I get 30 new commits which break something. I've found that often it's easiest to just remove the bad commits.

git rebase -i HEAD~31

Interactive rebase for the last 31 commits (it doesn't hurt if you pick way too many).

Simply take the commits that you want to get rid of and mark them with "d" instead of "pick". Now the commits are deleted effectively undoing the rebase (if you remove only the commits you just got when rebasing).

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

javascript toISOString() ignores timezone offset

moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

The following works as well:

var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

Set background image according to screen resolution

Pure CSS approaches that work very well are discussed here. Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better.

If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works).

An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo.

Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows.

A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much.

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

SQL Server using wildcard within IN

The IN operator is nothing but a fancy OR of '=' comparisons. In fact it is so 'nothing but' that in SQL 2000 there was a stack overflow bug due to expansion of the IN into ORs when the list contained about 10k entries (yes, there are people writing 10k IN entries...). So you can't use any wildcard matching in it.

How to add jQuery to an HTML page?

You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag

Using an array as needles in strpos

This expression searches for all letters:

count(array_filter( 
    array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)

Regex to validate date format dd/mm/yyyy

In case you are looking for specific format, This works fine for "dd/MM/yyyy" & "dd/MMM/yyyy" date format only based on Alok answer.

function isValidDateFormatDDMMYYYY(inputDate) {
    var date_regex = /^(?:(?:31(\/)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
    return date_regex.test(inputDate);
}

Few examples working thru this code -

  • isValidDateFormatDDMMYYYY("15/01/1999") // returns True
  • isValidDateFormatDDMMYYYY("15/Jan/1999") // returns True
  • isValidDateFormatDDMMYYYY("15/1/1999") // returns True
  • isValidDateFormatDDMMYYYY("1/15/1999") // returns False

Thanks

Set up git to pull and push all branches

With modern git you always fetch all branches (as remote-tracking branches into refs/remotes/origin/* namespace, visible with git branch -r or git remote show origin).

By default (see documentation of push.default config variable) you push matching branches, which means that first you have to do git push origin branch for git to push it always on git push.

If you want to always push all branches, you can set up push refspec. Assuming that the remote is named origin you can either use git config:

$ git config --add remote.origin.push '+refs/heads/*:refs/heads/*'
$ git config --add remote.origin.push '+refs/tags/*:refs/tags/*'

or directly edit .git/config file to have something like the following:

[remote "origin"]
        url = [email protected]:/srv/git/repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
        fetch = +refs/tags/*:refs/tags/*
        push  = +refs/heads/*:refs/heads/*
        push  = +refs/tags/*:refs/tags/*

How to read an external local JSON file in JavaScript?

All the solutions above mentioned will work only when you have a local webserver running on your local host. If you want to achieve this with out a web server, you might need to put in some manual effort by uploading the JSON file using file upload control. The browser will not offer this functionality with out a local server because of security risks.

You can parse the uploaded file with out a local webserver as well. Here is the sample code I have achieved a solution similar problem.

 <div id="content">
    <input type="file" name="inputfile" id="inputfile">
    <br>

    <h2>
        <pre id="output"></pre>
    </h2>
</div>
<script type="text/javascript">
    document.getElementById('inputfile')
        .addEventListener('change', function () {

            let fileReader = new FileReader();
            fileReader.onload = function () {
                let parsedJSON = JSON.parse(fileReader.result);
                console.log(parsedJSON);
                // your code to consume the json                    
            }
            fileReader.readAsText(this.files[0]);
        }) 
</script>

In my case I want to read a local JSON file and show it in a html file on my desktop, that's all I have to do.

Note: Don't try to automate the file uploading using JavaScript, even that's also not allowed due the same security restrictions imposed by browsers.

Android: why is there no maxHeight for a View?

I would have commented on whizzle's answer if I could, but thought it useful to note that in order for me to solve this problem in the context of multi-window mode in Android N, I needed to change the code slightly to this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if(MeasureSpec.getSize(heightMeasureSpec) > maxHeight) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

This allows for the layout to resize to be smaller than the max height, but also prevent it from being larger than the max height. I used this is a layout class that Overrides RelativeLayout and this allowed me to create a custom dialog with a ScrollView as the child of MaxHeightRelativeLayout that does not expand the full height of the screen and also shrinks to fit within the smallest widow size in multi-window for Android N.

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to set seekbar min and max value

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

Android Studio - Device is connected but 'offline'

If you are on windows and you encountered the same problem, try to kill the adb.exe process from task manager and then try to run your app again.

How do I crop an image in Java?

The solution I found most useful for cropping a buffered image uses the getSubImage(x,y,w,h);

My cropping routine ended up looking like this:

  private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
      BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
      return dest; 
   }

How to make responsive table

Basically

A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }
}

HTML

<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

reading external sql script in python

according me, it is not possible

solution:

  1. import .sql file on mysql server

  2. after

    import mysql.connector
    import pandas as pd
    

    and then you use .sql file by convert to dataframe

How can I make SMTP authenticated in C#

How do you send the message?

The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

String in function parameter

char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character

& char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )

But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.

How do I exit a while loop in Java?

You can use "break" to break the loop, which will not allow the loop to process more conditions

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

on command line type journalctl -xe and the results will be

SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 83 or 80

This means that the SELinux is running on your machine and you need to disable it. then edit the configuration file by type the following

nano /etc/selinux/config

Then find the line SELINUX=enforce and change to SELINUX=disabled

Then type the following and run the command to start httpd

setenforce 0

Lastly start a server

systemctl start httpd

Can I change the Android startActivity() transition animation?

 // CREATE anim 

 // CREATE animation,animation2  xml // animation like fade out 

  Intent myIntent1 = new Intent(getApplicationContext(), Attend.class);
  Bundle bndlanimation1 =  ActivityOptions.makeCustomAnimation(getApplicationContext(), 
  R.anim.animation, R.anim.animation2).toBundle();
  tartActivity(myIntent1, bndlanimation1);

Function to calculate distance between two coordinates

What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.

Wolphram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.

Drive distance vs. straight line distance (red line mine).

If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.

Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical namespace (look for computeDistanceBetween). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).

For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.

Fixed header, footer with scrollable content

Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:

header {
  height: 20px;
  background-color: #1d0d0a;
  position: fixed;
  top: 0;
  width: 100%;
  overflow: hide;
}

content {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 100px;
  margin-top: 20px;
  overflow: auto;
  width: 80%;
}

footer {
  position: fixed;
  bottom: 0px;
  overflow: hide;
  width: 100%;
}

jQuery: Can I call delay() between addClass() and such?

You can create a new queue item to do your removing of the class:

$("#div").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

Or using the dequeue method:

$("#div").addClass("error").delay(1000).queue(function(){
    $(this).removeClass("error").dequeue();
});

The reason you need to call next or dequeue is to let jQuery know that you are done with this queued item and that it should move on to the next one.

How does strcmp() work?

The pseudo-code "implementation" of strcmp would go something like:

define strcmp (s1, s2):
    p1 = address of first character of str1
    p2 = address of first character of str2

    while contents of p1 not equal to null:
        if contents of p2 equal to null: 
            return 1

        if contents of p2 greater than contents of p1:
            return -1

        if contents of p1 greater than contents of p2:
            return 1

        advance p1
        advance p2

    if contents of p2 not equal to null:
        return -1

    return 0

That's basically it. Each character is compared in turn an a decision is made as to whether the first or second string is greater, based on that character.

Only if the characters are identical do you move to the next character and, if all the characters were identical, zero is returned.

Note that you may not necessarily get 1 and -1, the specs say that any positive or negative value will suffice, so you should always check the return value with < 0, > 0 or == 0.

Turning that into real C would be relatively simple:

int myStrCmp (const char *s1, const char *s2) {
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;

    while (*p1 != '\0') {
        if (*p2 == '\0') return  1;
        if (*p2 > *p1)   return -1;
        if (*p1 > *p2)   return  1;

        p1++;
        p2++;
    }

    if (*p2 != '\0') return -1;

    return 0;
}

Also keep in mind that "greater" in the context of characters is not necessarily based on simple ASCII ordering for all string functions.

C has a concept called 'locales' which specify (among other things) collation, or ordering of the underlying character set and you may find, for example, that the characters a, á, à and ä are all considered identical. This will happen for functions like strcoll.

What do *args and **kwargs mean?

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

PHP - how to create a newline character?

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n"

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).

How to convert hex to rgb using Java?

I guess this should do it:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}

Facebook login "given URL not allowed by application configuration"

Also check to see if you are missing the www in the url which was on my case

i was testing on http://www.mywebsite.com and in the facebook app i had set http://mywebsite.com

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

Facebook page automatic "like" URL (for QR Code)

I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.

You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

Download file of any type in Asp.Net MVC using FileResult?

its simple just give your physical path in directoryPath with file name

public FilePathResult GetFileFromDisk(string fileName)
{
    return File(directoryPath, "multipart/form-data", fileName);
}

How can I stage and commit all files, including newly added files, using a single command?

This command will add and commit all the modified files, but not newly created files:

git commit -am  "<commit message>"

From man git-commit:

-a, --all
    Tell the command to automatically stage files that have been modified
    and deleted, but new files you have not told Git about are not
    affected.

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

How to add image in a TextView text?

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

HTML rows and cols are not responsive!

So I define the size in CSS. As a tip: if you define a small size for mobiles think about using textarea:focus {};

Add some extra space here, which will only unfold the moment a user wants to actually write something

2 column div layout: right column with fixed width, left fluid

Best to avoid placing the right column before the left, simply use a negative right-margin.

And be "responsive" by including an @media setting so the right column falls under the left on narrow screens.

<div style="background: #f1f2ea;">
  <div id="container">
    <div id="content">
        <strong>Column 1 - content</strong>
    </div>
  </div>
  <div id="sidebar">
    <strong>Column 2 - sidebar</strong>
  </div>
<div style="clear:both"></div>

<style type="text/css">
#container {
    margin-right: -300px;
    float:left;
    width:100%;
}
#content {
    margin-right: 320px; /* 20px added for center margin */
}
#sidebar {
    width:300px;
    float:left
}
@media (max-width: 480px) {
    #container {
        margin-right:0px;
        margin-bottom:20px;
    }
    #content {
        margin-right:0px;
        width:100%;
    }
    #sidebar {
        clear:left;
    }
}
</style>

NameError: global name is not defined

try

from sqlitedbx import SqliteDBzz

No connection could be made because the target machine actively refused it?

I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.

Where is Maven's settings.xml located on Mac OS?

I found it under /usr/share/java/maven-3.0.3/conf , 10.8.2

Removing an element from an Array (Java)

Swap the item to be removed with the last item, if resizing the array down is not an interest.

Save plot to image file instead of displaying it using Matplotlib

The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

Like this, I can later load the figure object and manipulate the settings as I please.

I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

NB: Be careful, as sometimes this method generates huge files.

Does Python have an argc argument?

dir(sys) says no. len(sys.argv) works, but in Python it is better to ask for forgiveness than permission, so

#!/usr/bin/python
import sys
try:
    in_file = open(sys.argv[1], "r")
except:
    sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()

works fine and is shorter.

If you're going to exit anyway, this would be better:

#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)

I'm using print() so it works in 2.7 as well as Python 3.

DataAdapter.Fill(Dataset)

DataSet ds = new DataSet();

using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    adapter.Fill(ds);
}

return ds;

When to use %r instead of %s in Python?

%r shows with quotes:

It will be like:

I said: 'There are 10 types of people.'.

If you had used %s it would have been:

I said: There are 10 types of people..

How to delete a cookie?

Here is an implementation of a delete cookie function with unicode support from Mozilla:

function removeItem(sKey, sPath, sDomain) {
    document.cookie = encodeURIComponent(sKey) + 
                  "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + 
                  (sDomain ? "; domain=" + sDomain : "") + 
                  (sPath ? "; path=" + sPath : "");
}

removeItem("cookieName");

If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):

$cookies.remove('cookieName');

How to subtract X days from a date using Java calendar?

int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);

See java.util.Calendar#add(int,int)

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Installing PHP Zip Extension

I tried changing the repository list with:

http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

But none of them seem to work, but I finally found a repository that works running the following command

add-apt-repository ppa:ondrej/php

And then updating and installing normally the package using apt-get

As you can see it's installed at last.

Gradle: How to Display Test Results in the Console in Real Time?

If you are using jupiter and none of the answers work, consider verifying it is setup correctly:

test {
    useJUnitPlatform()
    outputs.upToDateWhen { false }
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

And then try the accepted answers

Chrome refuses to execute an AJAX script due to wrong MIME type

If your proxy server or container adds the following header when serving the .js file, it will force some browsers such as Chrome to perform strict checking of MIME types:

X-Content-Type-Options: nosniff

Remove this header to prevent Chrome performing the MIME check.

How to decompile to java files intellij idea

I use JD-GUI for extract all decompiled java classes to java files.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How can I use UIColorFromRGB in Swift?

This is worked for me in swift. Try this

bottomBorder.borderColor = UIColor (red: 255.0/255.0, green: 215.0/255.0, blue: 60/255.0, alpha: 1.0).CGColor

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

How to Convert double to int in C?

This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.

double a;
a=3669.0;
int b;
b=a+ 1e-9;

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

How to get a context in a recycler view adapter

Create a constructor of FeedAdapter :

Context context; //global
public FeedAdapter(Context context)
{
   this.context = context;  
}

and in Activity

FeedAdapter obj = new FeedAdapter(this);

Python: printing a file to stdout

If you need to do this with the pathlib module, you can use pathlib.Path.open() to open the file and print the text from read():

from pathlib import Path

fpath = Path("somefile.txt")

with fpath.open() as f:
    print(f.read())

Or simply call pathlib.Path.read_text():

from pathlib import Path

fpath = Path("somefile.txt")

print(fpath.read_text())

What is correct content-type for excel files?

Do keep in mind that the file.getContentType could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.

Get spinner selected items text?

use this

import java.util.ArrayList;   
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class dynamic_spinner_main extends Activity {

    private Spinner m_myDynamicSpinner;
    private EditText m_addItemText;
    private ArrayAdapter<CharSequence> m_adapterForSpinner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_spinner);

        ///////////////////////////////////////////////////////////////
        //grab our UI elements so we can manipulate them (in the case of the Spinner)
        //    or add listeners to them (in the case of the buttons)
        m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);        
        m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
        Button addButton = (Button)findViewById(R.id.AddBtn);
        Button clearButton = (Button)findViewById(R.id.ClearBtn);

        ////////////////////////////////////////////////////////////////
        //create an arrayAdapter an assign it to the spinner
        m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
        m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);        
        m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
        m_adapterForSpinner.add("gr");        
        m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // your code here
                Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
                mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
                System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
                startActivity(mIntent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        addButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {               
                addNewSpinnerItem();
            }                   
        });

        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        clearButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                clearSpinnerItems();
            }           
        });  
    }

    private void addNewSpinnerItem() {
        CharSequence textHolder = "" + m_addItemText.getText();
        m_adapterForSpinner.add(textHolder);
    }

    private void clearSpinnerItems() {
        m_adapterForSpinner.clear();
        m_adapterForSpinner.add("dummy item");
    }       
}

main_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText android:layout_height="wrap_content" 
            android:layout_margin="4px" 
            android:id="@+id/newSpinnerItemText" 
            android:layout_width="fill_parent"></EditText>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/AddBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Add To Spinner"></Button>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/ClearBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Clear Spinner Items"></Button>
    <Spinner android:layout_height="wrap_content" 
            android:id="@+id/dynamicSpinner" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent"></Spinner>
</LinearLayout>

Apache and Node.js on the Same Server

I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.

Apache httpd.conf added to the bottom of the file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache) Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias www.example.com
    DocumentRoot /var/html/www.example.com
    ErrorLog /var/html/log/error.log
    CustomLog /var/html/log/requests.log combined
    SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^socket.io          [NC]
    RewriteCond %{QUERY_STRING} transport=websocket [NC]
    RewriteRule /{.*}       ws://localhost:3000/$1  [P,L]

    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]

    ProxyPass /nodejs http://localhost:3000/
    ProxyPassReverse /nodejs http://localhost:3000/

    ProxyPass /socket.io http://localhost:3000/socket.io
    ProxyPassReverse /socket.io http://localhost:3000/socket.io

    ProxyPass /socket.io ws://localhost:3000/socket.io
    ProxyPassReverse /socket.io ws://localhost:3000/socket.io

</VirtualHost>
</IfModule>

Then my node.js app (app.js):

var express = require('express');
var app = express();
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Headers", "Content-Type");
        res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
        next();
    });
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen({host:'0.0.0.0',port:3000});

I force a ip4 listener, but that is optional - you can substitute:

http.listen(3000);

node.js app (app.js) code continues with:

io.of('/nodejs').on('connection', function(socket) {
    //optional settings:
    io.set('heartbeat timeout', 3000); 
    io.set('heartbeat interval', 1000);

    //listener for when a user is added
    socket.on('add user', function(data) {
         socket.join('AnyRoomName');
         socket.broadcast.emit('user joined', data);
    });

    //listener for when a user leaves
    socket.on('remove user', function(data) {
         socket.leave('AnyRoomName');
         socket.broadcast.emit('user left', data);
    });

    //sample listener for any other function
    socket.on('named-event', function(data) {
         //code....
         socket.broadcast.emit('named-event-broadcast', data);
    });

    // add more listeners as needed... use different named-events...
});

finally, on the client side (created as nodejs.js):

//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');

//listener for user joined
socket.on('user joined', function(data) {
    // code... data shows who joined...
});

//listener for user left
socket.on('user left', function(data) {
    // code... data shows who left...
});

// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
    // this receives the broadcast data (I use json then parse and execute code)
    console.log('data1=' + data.data1);
    console.log('data2=' + data.data2);
});

// sample send broadcast json data for user joined:
socket.emit('user joined', {
    'userid': 'userid-value',
    'username':'username-value'
});

// sample send broadcast json data for user left 
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
//     'userid': 'userid-value',
//     'username':'username-value'
// });

// sample send broadcast json data for any named-event:
socket.emit('named-event', {
    'data1': 'value1',
    'data2':'value2'
});

In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.

Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.

Display more Text in fullcalendar

With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.

In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.

function htmlEscape(s) {
    return s.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#039;')
    .replace(/"/g, '&quot;')
    .replace(/\n/g, '<br />')
    .replace(/&lt;br\s?\/?&gt;/g, '<br />');
}

This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'

Having services in React application

I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)

Then write a HOC that does validate and style wrapped component:

function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}

Now those HOCs share the same validating behavior:

const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js

vim line numbers - how to have them on by default?

Add set number to your .vimrc file in your home directory.
If the .vimrc file is not in your home directory create one with vim .vimrc and add the commands you want at open.

Here's a site that explains the vimrc and how to use it.

SQL: ... WHERE X IN (SELECT Y FROM ...)

If you want to know which is more effective, you should try looking at the estimated query plans, or the actual query plans after execution. It'll tell you the costs of the queries (I find CPU and IO cost to be interesting). I wouldn't be surprised much if there's little to no difference, but you never know. I've seen certain queries use multiple cores on our database server, while a rewritten version of that same query would only use one core (needless to say, the query that used all 4 cores was a good 3 times faster). Never really quite put my finger on why that is, but if you're working with large result sets, such differences can occur without your knowing about it.

ResultSet exception - before start of result set

You have to do a result.next() before you can access the result. It's a very common idiom to do

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

In my case I received following error

Installation error: INSTALL_FAILED_DUPLICATE_PERMISSION perm=com.map.permission.MAPS_RECEIVE pkg=com.abc.Firstapp

When I was trying to install the app which have package name com.abc.Secondapp. Here point was that app with package name com.abc.Firstapp was already installed in my application.

I resolved this error by uninstalling the application with package name com.abc.Firstapp and then installing the application with package name com.abc.Secondapp

I hope this will help someone while testing.

How to add key,value pair to dictionary?

To insert/append to a dictionary

{"0": {"travelkey":"value", "travelkey2":"value"},"1":{"travelkey":"value","travelkey2":"value"}} 

travel_dict={} #initialize dicitionary 
travel_key=0 #initialize counter

if travel_key not in travel_dict: #for avoiding keyerror 0
    travel_dict[travel_key] = {}
travel_temp={val['key']:'no flexible'}  
travel_dict[travel_key].update(travel_temp) # Updates if val['key'] exists, else adds val['key']
travel_key=travel_key+1

How to determine the IP address of a Solaris system

/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'

This will list down the exact ip address for the machine

Normalizing a list of numbers in Python

try:

normed = [i/sum(raw) for i in raw]

normed
[0.25, 0.5, 0.25]

JQuery Event for user pressing enter in a textbox?

It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.

I would highly suggest the following methodology for binding, as it solves the following potential challenges:

  1. By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
  2. By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
  3. By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.

Here is an example:

<!DOCTYPE html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var $selector = $('textarea');

        // Prevent double-binding
        // (only a potential issue if script is loaded through AJAX)
        $(document.body).off('keyup', $selector);

        // Bind to keyup events on the $selector.
        $(document.body).on('keyup', $selector, function(event) {
          if(event.keyCode == 13) { // 13 = Enter Key
            alert('enter key pressed.');
          }
        });
      });
    </script>
  </head>
  <body>

  </body>
</html>

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

How to read text files with ANSI encoding and non-English letters?

using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250)))  ////File.Create(path)
        {
            writer.Write("Sample Text");
        }

Git push rejected "non-fast-forward"

I had a similar problem and I resolved it with: git pull origin

The Android emulator is not starting, showing "invalid command-line parameter"

As an alternative to the PROGRA~2 method (which is not working for example in IntelliJ IDEA), you can create a symbolic link.

It can be named, for example, prg to Program Files (run mklink /? from the command line to learn how to do it). Then run the emulator as C:\prg\Android\android-sdk\tools\emulator.exe. Also change the path to SDK/emulator in your IDE.

PostgreSQL "DESCRIBE TABLE"

To improve on the other answer's SQL query (which is great!), here is a revised query. It also includes constraint names, inheritance information, and a data types broken into it's constituent parts (type, length, precision, scale). It also filters out columns that have been dropped (which still exist in the database).

SELECT
    n.nspname as schema,
    c.relname as table,
    f.attname as column,  
    f.attnum as column_id,  
    f.attnotnull as not_null,
    f.attislocal not_inherited,
    f.attinhcount inheritance_count,
    pg_catalog.format_type(f.atttypid,f.atttypmod) AS data_type_full,
    t.typname AS data_type_name,
    CASE  
        WHEN f.atttypmod >= 0 AND t.typname <> 'numeric'THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data
    END AS data_type_length, 
    CASE  
        WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) >> 16) & 65535)
    END AS numeric_precision,   
    CASE  
        WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)& 65535 )
    END AS numeric_scale,       
    CASE  
        WHEN p.contype = 'p' THEN 't'  
        ELSE 'f'  
    END AS is_primary_key,  
    CASE
        WHEN p.contype = 'p' THEN p.conname
    END AS primary_key_name,
    CASE  
        WHEN p.contype = 'u' THEN 't'  
        ELSE 'f'
    END AS is_unique_key,
    CASE
        WHEN p.contype = 'u' THEN p.conname
    END AS unique_key_name,
    CASE
        WHEN p.contype = 'f' THEN 't'
        ELSE 'f'
    END AS is_foreign_key,
    CASE
        WHEN p.contype = 'f' THEN p.conname
    END AS foreignkey_name,
    CASE
        WHEN p.contype = 'f' THEN p.confkey
    END AS foreign_key_columnid,
    CASE
        WHEN p.contype = 'f' THEN g.relname
    END AS foreign_key_table,
    CASE
        WHEN p.contype = 'f' THEN p.conkey
    END AS foreign_key_local_column_id,
    CASE
        WHEN f.atthasdef = 't' THEN d.adsrc
    END AS default_value
FROM pg_attribute f  
    JOIN pg_class c ON c.oid = f.attrelid  
    JOIN pg_type t ON t.oid = f.atttypid  
    LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum  
    LEFT JOIN pg_namespace n ON n.oid = c.relnamespace  
    LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)  
    LEFT JOIN pg_class AS g ON p.confrelid = g.oid  
WHERE c.relkind = 'r'::char  
    AND f.attisdropped = false
    AND n.nspname = '%s'  -- Replace with Schema name  
    AND c.relname = '%s'  -- Replace with table name  
    AND f.attnum > 0 
ORDER BY f.attnum
;

Visual Studio opens the default browser instead of Internet Explorer

In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.

Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.

How does paintComponent work?

Calling object.paintComponent(g) is an error.

Instead this method is called automatically when the panel is created. The paintComponent() method can also be called explicitly by the repaint() method defined in Component class.

The effect of calling repaint() is that Swing automatically clears the graphic on the panel and executes the paintComponent method to redraw the graphics on this panel.

Convert String to Double - VB

I simple used Eval(string) and it evaluated as Double.

How do I add a Maven dependency in Eclipse?

I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.

 Right click on project >> maven >> updateProject >> selectProject >> OK

Sum values from an array of key-value pairs in JavaScript

You can use the native map method for Arrays. map Method (Array) (JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result

What is the default access specifier in Java?

If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

How do you add a JToken to an JObject?

Just adding .First to your bananaToken should do it:
foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
.First basically moves past the { to make it a JProperty instead of a JToken.

@Brian Rogers, Thanks I forgot the .Parent. Edited

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

Bold & Non-Bold Text In A Single UILabel?

Update

In Swift we don't have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:

Swift 5

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    let nonBoldAttribute = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Swift 3

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
        NSForegroundColorAttributeName: UIColor.black
    ]
    let nonBoldAttribute = [
        NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Usage:

let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()

Bonus: Internationalisation

Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it

// Date we want to show
let date = Date()

// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
                          formatter.string(from: date))

// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))

// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
    nil :
    NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
                targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))

// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
                                        nonBoldRange: nonBoldNSRange)

Result (Assuming English and Japanese Localizable.strings are available)

enter image description here

enter image description here


Previous answer for iOS6 and later (Objective-C still works):

In iOS6 UILabel, UIButton, UITextView, UITextField, support attributed strings which means we don't need to create CATextLayers as our recipient for attributed strings. Furthermore to make the attributed string we don't need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework like NSParagraphStyle and other constants that will make our life easier. Yay!

So, if we have this string:

NSString *text = @"Updated: 2012/10/14 21:59"

We only need to create the attributed string:

if ([_label respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings

    // Create the attributes
    const CGFloat fontSize = 13;
    NSDictionary *attrs = @{
        NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
        NSForegroundColorAttributeName:[UIColor whiteColor]
    };
    NSDictionary *subAttrs = @{
        NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
    };

    // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
    // This example is about attributed strings in one label
    // not about internationalisation, so we keep it simple :)
    // For internationalisation example see above code in swift
    const NSRange range = NSMakeRange(8,12);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
      [[NSMutableAttributedString alloc] initWithString:text
                                             attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_label setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_label setText:text];
}

There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of NSAttributedString, look for "Introduction to NSAttributedString for iOS 6" and "Attributed strings for iOS using Interface Builder" :)

PS: Above code it should work but it was brain-compiled. I hope it is enough :)


Old Answer for iOS5 and below

Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)

Example.

Don't forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>

Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)

- (void)setRefreshDate:(NSDate *)aDate
{
    [aDate retain];
    [refreshDate release];
    refreshDate = aDate;

    if (refreshDate) {

        /* Create the text for the text layer*/    
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm"];

        NSString *dateString = [df stringFromDate:refreshDate];
        NSString *prefix = NSLocalizedString(@"Updated", nil);
        NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString];
        [df release];

        /* Create the text layer on demand */
        if (!_textLayer) {
            _textLayer = [[CATextLayer alloc] init];
            //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
            _textLayer.backgroundColor = [UIColor clearColor].CGColor;
            _textLayer.wrapped = NO;
            CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
            _textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
            _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
            _textLayer.alignmentMode = kCAAlignmentCenter;
            [layer addSublayer:_textLayer];
        }

        /* Create the attributes (for the attributed string) */
        CGFloat fontSize = 13;
        UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
        CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
        UIFont *font = [UIFont systemFontOfSize:13];
        CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
        CGColorRef cgColor = [UIColor whiteColor].CGColor;
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    (id)ctBoldFont, (id)kCTFontAttributeName,
                                    cgColor, (id)kCTForegroundColorAttributeName, nil];
        CFRelease(ctBoldFont);
        NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil];
        CFRelease(ctFont);

        /* Create the attributed string (text + attributes) */
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
        [attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ "

        /* Set the attributes string in the text layer :) */
        _textLayer.string = attrStr;
        [attrStr release];

        _textLayer.opacity = 1.0;
    } else {
        _textLayer.opacity = 0.0;
        _textLayer.string = nil;
    }
}

In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.

Hope it helps

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

How can I get the current class of a div with jQuery?

if you want to look for a div that has more than 1 class try this:

Html:

<div class="class1 class2 class3" id="myDiv">

Jquery:

var check = $( "#myDiv" ).hasClass( "class2" ).toString();

ouput:

true

Tomcat is not deploying my web project from Eclipse

Same problem, not sure why it occurred only after upgrading from Spring v3.2.x to v4.2.x.

Solved it by doing the following:

  1. Clear all eclipse files [.classpath, .project, .settings/].
  2. Perform >mvn eclipse:eclipse
  3. Perform eclipse>project>properties>deployment assembly add [referenced projects, additional classpaths].

Publish and Start the module in Tomcat tab, it now starts properly.

how to use ng-option to set default value of select element

If your array of objects are complex like:

$scope.friends = [{ name: John , uuid: 1234}, {name: Joe, uuid, 5678}];

And your current model was set to something like:

$scope.user.friend = {name:John, uuid: 1234};

It helped to use the track by function on uuid (or any unique field), as long as the ng-model="user.friend" also has a uuid:

<select ng-model="user.friend" 
ng-options="friend as friend.name for friend in friends track by friend.uuid"> 
</select>

Regular expression for excluding special characters

To exclude certain characters ( <, >, %, and $), you can make a regular expression like this:

[<>%\$]

This regular expression will match all inputs that have a blacklisted character in them. The brackets define a character class, and the \ is necessary before the dollar sign because dollar sign has a special meaning in regular expressions.

To add more characters to the black list, just insert them between the brackets; order does not matter.

According to some Java documentation for regular expressions, you could use the expression like this:

Pattern p = Pattern.compile("[<>%\$]");
Matcher m = p.matcher(unsafeInputString);
if (m.matches())
{
    // Invalid input: reject it, or remove/change the offending characters.
}
else
{
    // Valid input.
}

Ruby on Rails - Import Data from a CSV file

Use this gem: https://rubygems.org/gems/active_record_importer

class Moulding < ActiveRecord::Base
  acts_as_importable
end

Then you may now use:

Moulding.import!(file: File.open(PATH_TO_FILE))

Just be sure to that your headers match the column names of your table

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

How to get only filenames within a directory using c#?

You could use the DirectoryInfo and FileInfo classes.

//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");

//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;

npm not working - "read ECONNRESET"

use

npm config set registry http://registry.npmjs.org/

so that npm requests for http url instead of https.

and then try the same npm install command

Getting content/message from HttpResponseMessage

By the answer of rudivonstaden

txtBlock.Text = await response.Content.ReadAsStringAsync();

but if you don't want to make the method async you can use

txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();

Wait() it's important, bec?use we are doing async operations and we must wait for the task to complete before going ahead.

How can I format a String number to have commas and round?

The first answer works very well, but for ZERO / 0 it will format as .00

Hence the format #,##0.00 is working well for me. Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.