Programs & Examples On #Calculated field

Rotating x axis labels in R for barplot

use optional parameter las=2 .

barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)

enter image description here

Binding select element to object in Angular

Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.

Difference of two date time in sql server

Please check below trick to find the date difference between two dates

 DATEDIFF(DAY,ordr.DocDate,RDR1.U_ProgDate) datedifff

where you can change according your requirement as you want difference of days or month or year or time.

@UniqueConstraint annotation in Java

I'm currently using play framework too with hibernate and JPA 2.0 annotation and this model works without problems

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
public class class_name {

@Id
@GeneratedValue
public Long id;

@NotNull
public Long id_1;

@NotNull
public Long id_2;

}

Hope it helped.

Finding index of character in Swift String

String is a bridge type for NSString, so add

import Cocoa

to your swift file and use all the "old" methods.

How to make node.js require absolute? (instead of relative)

i created a node module called "rekiure"

it allows you to require without the use of relative paths

https://npmjs.org/package/rekuire

it is super easy to use

How to get Bitmap from an Uri?

Use startActivityForResult metod like below

        startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);

And you can get result like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    switch (requestCode) {
        case PICK_IMAGE:
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
         break;
    }
}

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

How do I make a batch file terminate upon encountering an error?

No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:

Build Project and save log to Build.log

SET Build_Opt=/flp:summary;logfile=Build.log;append=true

msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%

search for "0 Error" string in build log, set the result to var

FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
    SET var=%%F
)
echo %var%

get the last character, which indicates how many lines contains the search string

set result=%var:~-1%

echo "%result%"

if string not found, then error > 0, build failed

if "%result%"=="0" ( echo "build failed" )

That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file

and https://ss64.com/nt/syntax-substring.html

How to read the output from git diff?

It's unclear from your question which part of the diffs you find confusing: the actually diff, or the extra header information git prints. Just in case, here's a quick overview of the header.

The first line is something like diff --git a/path/to/file b/path/to/file - obviously it's just telling you what file this section of the diff is for. If you set the boolean config variable diff.mnemonic prefix, the a and b will be changed to more descriptive letters like c and w (commit and work tree).

Next, there are "mode lines" - lines giving you a description of any changes that don't involve changing the content of the file. This includes new/deleted files, renamed/copied files, and permissions changes.

Finally, there's a line like index 789bd4..0afb621 100644. You'll probably never care about it, but those 6-digit hex numbers are the abbreviated SHA1 hashes of the old and new blobs for this file (a blob is a git object storing raw data like a file's contents). And of course, the 100644 is the file's mode - the last three digits are obviously permissions; the first three give extra file metadata information (SO post describing that).

After that, you're on to standard unified diff output (just like the classic diff -U). It's split up into hunks - a hunk is a section of the file containing changes and their context. Each hunk is preceded by a pair of --- and +++ lines denoting the file in question, then the actual diff is (by default) three lines of context on either side of the - and + lines showing the removed/added lines.

How to download Visual Studio 2017 Community Edition for offline installation?

You should goto the Layout folder and issue the following command:

F:\vs2017c>vs_community.exe /finalizeInstall

Then it will auto pickup cache components bypass downloading.

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

What does IFormatProvider do?

In adition to Ian Boyd's answer:

Also CultureInfo implements this interface and can be used in your case. So you could parse a French date string for example; you could use

var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);

Hide axis values but keep axis tick labels in matplotlib

If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels():

import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')

# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])

plt.show()

Difference between final and effectively final

However, starting in Java SE 8, a local class can access local variables and parameters of the >enclosing block that are final or effectively final.

This didn't start on Java 8, I use this since long time. This code used (before java 8) to be legal:

String str = ""; //<-- not accesible from anonymous classes implementation
final String strFin = ""; //<-- accesible 
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
         String ann = str; // <---- error, must be final (IDE's gives the hint);
         String ann = strFin; // <---- legal;
         String str = "legal statement on java 7,"
                +"Java 8 doesn't allow this, it thinks that I'm trying to use the str declared before the anonymous impl."; 
         //we are forced to use another name than str
    }
);

Coerce multiple columns to factors at once

Here is another tidyverse approach using the modify_at() function from the purrr package.

library(purrr)

# Data frame with only integer columns
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

# Modify specified columns to a factor class
data_with_factors <- data %>%
    purrr::modify_at(c("A", "C", "E"), factor)


# Check the results:
str(data_with_factors)
# 'data.frame':   4 obs. of  10 variables:
#  $ A: Factor w/ 4 levels "8","12","33",..: 1 3 4 2
#  $ B: int  25 32 2 19
#  $ C: Factor w/ 4 levels "5","15","35",..: 1 3 4 2
#  $ D: int  11 7 27 6
#  $ E: Factor w/ 4 levels "1","4","16","20": 2 3 1 4
#  $ F: int  21 23 39 18
#  $ G: int  31 14 38 26
#  $ H: int  17 24 34 10
#  $ I: int  13 28 30 29
#  $ J: int  3 22 37 9

How do I check in python if an element of a list is empty?

I got around this with len() and a simple if/else statement.

List elements will come back as an integer when wrapped in len() (1 for present, 0 for absent)

l = []

print(len(l)) # Prints 0

if len(l) == 0:
    print("Element is empty")
else:
    print("Element is NOT empty")

Output:

Element is empty    

How to check if a URL exists or returns 404 with Java?

Based on the given answers and information in the question, this is the code you should use:

public static boolean doesURLExist(URL url) throws IOException
{
    // We want to check the current URL
    HttpURLConnection.setFollowRedirects(false);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    // We don't need to get data
    httpURLConnection.setRequestMethod("HEAD");

    // Some websites don't like programmatic access so pretend to be a browser
    httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    int responseCode = httpURLConnection.getResponseCode();

    // We only accept response code 200
    return responseCode == HttpURLConnection.HTTP_OK;
}

Of course tested and working.

How to render a PDF file in Android

There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.

build.Gradle

compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

dialog_pdf_viewer

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_pdf_viewer_close"
        style="@style/ExitButtonImageViewStyle"
        android:src="@drawable/popup_exit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"
        android:orientation="vertical">

        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <View style="@style/HorizontalLine" />

    <com.pozitron.commons.customviews.ButtonFont
        android:id="@+id/dialog_pdf_viewer_button"
        style="@style/ButtonPrimary2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/agreed" />

</LinearLayout>

DailogPDFViewer.java

public class DialogPdfViewer extends Dialog {
    PDFView pdfView;
    byte[] decodedString;

    public interface OnDialogPdfViewerListener {
        void onAgreeClick(DialogPdfViewer dialogFullEula);

        void onCloseClick(DialogPdfViewer dialogFullEula);
    }

    public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
        super(context);

        setContentView(R.layout.dialog_pdf_viewer);
        findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
            }
        });

        findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
            }
        });

        decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);

        pdfView = ((PDFView) findViewById(R.id.pdfView));
        pdfView.fromBytes(decodedString).load();

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
                return true;
            }
        });

    }
}

Convert DataSet to List

Here's extension method to convert DataTable to object list:

    public static class Extensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(System.DayOfWeek))
                {
                    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                    property.SetValue(item,day,null);
                }
                else
                {
                    if(row[property.Name] == DBNull.Value)
                        property.SetValue(item, null, null);
                    else 
                        property.SetValue(item, row[property.Name], null); 
                }
            }
            return item;
        }
    }

usage:

List<Employee> lst = ds.Tables[0].ToList<Employee>();

@itay.b CODE EXPLAINED: We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.

The property values are picked from the row's matching column cell.

PS: class property name and table column names must be same

ALTER DATABASE failed because a lock could not be placed on database

In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.

Using env variable in Spring Boot's application.properties

I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.

On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.

Getting the idea from PHP Symfony 3 framework that has a parameters.yml (.gitignored) and a parameters.yml.dist (which is a sample that creates the first one through composer install),

I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.

Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:

application.yml.dist (sample)

    spring:
      profiles:
        active: local/dev/prod
      datasource:
        username:
        password:
        url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on dev server)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: verysecretpassword
    url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on local machine)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: rootroot
    url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application-dev.yml (extra environment specific properties not sensitive)

spring:
  datasource:
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: create-droop
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL57InnoDBDialect

Same can be done with .properties

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

How do I space out the child elements of a StackPanel?

I improved on Elad Katz' answer.

  • Add LastItemMargin property to MarginSetter to specially handle the last item
  • Add Spacing attached property with Vertical and Horizontal properties that adds spacing between items in vertical and horizontal lists and eliminates any trailing margin at the end of the list

Source code in gist.

Example:

<StackPanel Orientation="Horizontal" foo:Spacing.Horizontal="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<StackPanel Orientation="Vertical" foo:Spacing.Vertical="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<!-- Same as vertical example above -->
<StackPanel Orientation="Vertical" foo:MarginSetter.Margin="0 0 0 5" foo:MarginSetter.LastItemMargin="0">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

How to create Password Field in Model Django

I thinks it is vary helpful way.

models.py

from django.db import models
class User(models.Model):
    user_name = models.CharField(max_length=100)
    password = models.CharField(max_length=32)

forms.py

from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
    class Meta:
        model= User
        fields=[
           'user_name',
           'password'
            ]
       widgets = {
      'password': forms.PasswordInput()
         }

toBe(true) vs toBeTruthy() vs toBeTrue()

There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx), if i need to check if all elements are displayed at a single run, i can perform -

expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails

Reason being .all() returns an array of values and so all kinds of expectations(getText, isPresent, etc...) can be performed with toBeTruthy() when .all() comes into picture. Hope this helps.

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

Find what 2 numbers add to something and multiply to something

With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:

$factors = array();
for($i = 0; $i < $target; $i++){
    if($target % $i == 0){
        $temp = array()
        $a = $i;
        $b = $target / $i;
        $temp["a"] = $a;
        $temp["b"] = $b;
        $temp["index"] = $i;
        array_push($factors, $temp);
    }
}

This would leave you with an array of factors of the target number.

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Including a groovy script in another groovy

For late-comers, it appears that groovy now support the :load file-path command which simply redirects input from the given file, so it is now trivial to include library scripts.

It works as input to the groovysh & as a line in a loaded file:
groovy:000> :load file1.groovy

file1.groovy can contain:
:load path/to/another/file invoke_fn_from_file();

php var_dump() vs print_r()

I'd aditionally recommend putting the output of var_dump() or printr into a pre tag when outputting to a browser.

print "<pre>";
print_r($dataset);
print "</pre>";

Will give a more readable result.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

I had similar trouble, have a program running for last 10 years written in VB6, now client wanted to make some major modifications, and all my machines which are now windows 10; failed to open the project, it was always that nasty mscomctl.ocx error. I had done lot of things but could not solve the problem. Then I thought the easy way around, I downloaded the latest mscomctl (mscomctl.ocx Then opened a new project, added all the components like mscomctl, activx controls etc, saved it and opened this newly created project file in Notepad, then copied the exact details and replaced in the original project.... and bingo! The old project opened up normally without any fuss! I hope this experience will help someone.

Python 3 ImportError: No module named 'ConfigParser'

how about checking the version of Python you are using first.

import six
if six.PY2:
    import ConfigParser as configparser
else:
    import configparser

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

cast class into another class or convert class to another

You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:

public class sub1
{
    public int a;
    public int b;
    public int c;

    public static explicit operator maincs(sub1 obj)
    {
        maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
        return output;
    }
}

Which then allows you to do something like

static void Main()
{
    sub1 mySub = new sub1();
    maincs myMain = (maincs)mySub;
}

What does the line "#!/bin/sh" mean in a UNIX shell script?

When you try to execute a program in unix (one with the executable bit set), the operating system will look at the first few bytes of the file. These form the so-called "magic number", which can be used to decide the format of the program and how to execute it.

#! corresponds to the magic number 0x2321 (look it up in an ascii table). When the system sees that the magic number, it knows that it is dealing with a text script and reads until the next \n (there is a limit, but it escapes me atm). Having identified the interpreter (the first argument after the shebang) it will call the interpreter.

Other files also have magic numbers. Try looking at a bitmap (.BMP) file via less and you will see the first two characters are BM. This magic number denotes that the file is indeed a bitmap.

Is there a Python equivalent of the C# null-coalescing operator?

Python has a get function that its very useful to return a value of an existent key, if the key exist;
if not it will return a default value.

def main():
    names = ['Jack','Maria','Betsy','James','Jack']
    names_repeated = dict()
    default_value = 0

    for find_name in names:
        names_repeated[find_name] = names_repeated.get(find_name, default_value) + 1

if you cannot find the name inside the dictionary, it will return the default_value, if the name exist then it will add any existing value with 1.

hope this can help

How do I execute a bash script in Terminal?

cd to the directory that contains the script, or put it in a bin folder that is in your $PATH

then type

./scriptname.sh

if in the same directory or

scriptname.sh

if it's in the bin folder.

Install mysql-python (Windows)

MySqldb python install windows

MySQL-python 1.2.3 for Windows and Python 2.7, 32bit and 64bit versions

download python mysql-python from here

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

Works:

$.ajax({
    url: _saveAllDevicesUrl
,   type: 'POST'
,   contentType: 'application/json'
,   data: JSON.stringify(postData) //stringify is important
,   success: _madeSave.bind(this)
});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.

Peak detection in a 2D array

There are several and extensive pieces of software available from the astronomy and cosmology community - this is a significant area of research both historically and currently.

Do not be alarmed if you are not an astronomer - some are easy to use outside the field. For example, you could use astropy/photutils:

https://photutils.readthedocs.io/en/stable/detection.html#local-peak-detection

[It seems a bit rude to repeat their short sample code here.]

An incomplete and slightly biased list of techniques/packages/links that might be of interest is given below - do add more in the comments and I will update this answer as necessary. Of course there is a trade-off of accuracy vs compute resources. [Honestly, there are too many to give code examples in a single answer such as this so I am not sure whether this answer will fly or not.]

Source Extractor https://www.astromatic.net/software/sextractor

MultiNest https://github.com/farhanferoz/MultiNest [+ pyMultiNest]

ASKAP/EMU source-finding challenge: https://arxiv.org/abs/1509.03931

You could also search for Planck and/or WMAP source-extraction challenges.

...

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

For me, i forget to add AUTO_INCREMENT to my primary field and inserted data without id.

Git "error: The branch 'x' is not fully merged"

You can simply figure out :

git log --cherry master...experimental

--cherry option is a synonym for --right-only --cherry-mark --no-merges

git-log man page said

it's useful to limit the output to the commits on our side and mark those that have been applied to the other side of a forked history with git log --cherry upstream...mybranch, similar to git cherry upstream mybranch.

FYI. --cherry-pick omits equivalent commits but --cherry-marks doesn't. It's useful to find rebase and force updated changes between upstream and co-working public branch

plot different color for different categorical levels using matplotlib

Using Altair.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')

enter image description here

How to keep :active css style after clicking an element

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

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

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

How to install Hibernate Tools in Eclipse?

Once you have copied the plugins and features folder to eclipse (eg. c:\program files\eclipse (or whereever you installed it). You will see a features and plugins folder there already) you can check if hibernate has installed by going to Help > Software updates > installed software. If hibernate is not listed close eclipse and launch it again via a command window with this command "eclipse -clean".

inline conditionals in angular.js

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

I have published an article on working with AngularJS+SVG that talks about this and related issues. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS

java: How can I do dynamic casting of a variable from one type to another?

I recently felt like I had to do this too, but then found another way which possibly makes my code look neater, and uses better OOP.

I have many sibling classes that each implement a certain method doSomething(). In order to access that method, I would have to have an instance of that class first, but I created a superclass for all my sibling classes and now I can access the method from the superclass.

Below I show two ways alternative ways to "dynamic casting".

// Method 1.
mFragment = getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
switch (mUnitNum) {
case 0:
    ((MyFragment0) mFragment).sortNames(sortOptionNum);
    break;
case 1:
    ((MyFragment1) mFragment).sortNames(sortOptionNum);
    break;
case 2:
    ((MyFragment2) mFragment).sortNames(sortOptionNum);
    break;
}

and my currently used method,

// Method 2.
mSuperFragment = (MySuperFragment) getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
mSuperFragment.sortNames(sortOptionNum);

Calculate distance between 2 GPS coordinates

    private double deg2rad(double deg)
    {
        return (deg * Math.PI / 180.0);
    }

    private double rad2deg(double rad)
    {
        return (rad / Math.PI * 180.0);
    }

    private double GetDistance(double lat1, double lon1, double lat2, double lon2)
    {
        //code for Distance in Kilo Meter
        double theta = lon1 - lon2;
        double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
        dist = Math.Abs(Math.Round(rad2deg(Math.Acos(dist)) * 60 * 1.1515 * 1.609344 * 1000, 0));
        return (dist);
    }

    private double GetDirection(double lat1, double lon1, double lat2, double lon2)
    {
        //code for Direction in Degrees
        double dlat = deg2rad(lat1) - deg2rad(lat2);
        double dlon = deg2rad(lon1) - deg2rad(lon2);
        double y = Math.Sin(dlon) * Math.Cos(lat2);
        double x = Math.Cos(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) - Math.Sin(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(dlon);
        double direct = Math.Round(rad2deg(Math.Atan2(y, x)), 0);
        if (direct < 0)
            direct = direct + 360;
        return (direct);
    }

    private double GetSpeed(double lat1, double lon1, double lat2, double lon2, DateTime CurTime, DateTime PrevTime)
    {
        //code for speed in Kilo Meter/Hour
        TimeSpan TimeDifference = CurTime.Subtract(PrevTime);
        double TimeDifferenceInSeconds = Math.Round(TimeDifference.TotalSeconds, 0);
        double theta = lon1 - lon2;
        double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
        dist = rad2deg(Math.Acos(dist)) * 60 * 1.1515 * 1.609344;
        double Speed = Math.Abs(Math.Round((dist / Math.Abs(TimeDifferenceInSeconds)) * 60 * 60, 0));
        return (Speed);
    }

    private double GetDuration(DateTime CurTime, DateTime PrevTime)
    {
        //code for speed in Kilo Meter/Hour
        TimeSpan TimeDifference = CurTime.Subtract(PrevTime);
        double TimeDifferenceInSeconds = Math.Abs(Math.Round(TimeDifference.TotalSeconds, 0));
        return (TimeDifferenceInSeconds);
    }

Detecting installed programs via registry

Win32_Product never shows everything, only software installed via an MSI installer (as far as I can tell.)

There are lots of software packages that get installed via other installers that don't show up in there. another way is needed.

'const int' vs. 'int const' as function parameters in C++ and C

const int is identical to int const, as is true with all scalar types in C. In general, declaring a scalar function parameter as const is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.

Git, fatal: The remote end hung up unexpectedly

If using GitHub, in the repo's directory, run this command to set http.postBuffer to what appears to be its maximum allowable value for GitHub:

git config http.postBuffer 2147483648

If cloning a repo instead using git clone, it can be cloned with the same option:

git clone -c http.postBuffer=2147483648 [email protected]:myuser/myrepo.git /path/to/myrepo

In both cases, the number above is equivalent to 2 GiB. It is however possible that you will need up to this amount of free memory to be able to use this value.

Ensure that each push to GitHub has commits that don't add more than this size of changes. In fact I would keep the commit push size under 1.8 GiB to be safe. This can require dividing a large commit into smaller commits and pushes.

Why this value?

This specific value is used because at least as of the year 2018, this value was documented (archive link) as the push size limit of GitHub:

we don’t allow pushes over 2GB

Why not set lower?

Some prior answers say to set it to 524288000 (500 MiB), but this number seems arbitrary and without merit. Any lower value should work as long as your push size is not larger than the set value.

Why not set higher?

If instead you set the value to higher than 2 GiB, and if your attempted push size is also higher, you can expect the documented error with GitHub:

remote: fatal: pack exceeds maximum allowed size

How can I split a string with a string delimiter?

Read C# Split String Examples - Dot Net Pearls and the solution can be something like:

var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);

Matplotlib (pyplot) savefig outputs blank image

First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists.

Second, after plt.show() is called, a new figure is created. To deal with this, you can

  1. Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show()

  2. Save the figure before you show() by calling plt.gcf() for "get current figure", then you can call savefig() on this Figure object at any time.

For example:

fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)

In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.

Center image using text-align center?

If you want to set the image as the background, I've got a solution:

.image {
    background-image: url(yourimage.jpg);
    background-position: center;
}

get current date with 'yyyy-MM-dd' format in Angular 4

app.component.html

<div>
     <h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>

app.component.ts

export class AppComponent implements OnInit {
myDate = Date.now();    //date 

Add image in pdf using jspdf

Though I'm not sure, the image might not be added because you create the output before you add it. Try:

function convert(){
    var doc = new jsPDF();
    var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
    console.log(imgData);
    doc.setFontSize(40);
    doc.text(30, 20, 'Hello world!');
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
    doc.output('datauri');
}

Removing duplicate values from a PowerShell array

Another option is to use Sort-Object (whose alias is sort, but only on Windows) with the
-Unique switch, which combines sorting with removal of duplicates:

$a | sort -unique

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

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

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

Two Divs next to each other, that then stack with responsive change

Do like this:

HTML

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>

CSS

.parent{
    width: 400px;
    background: red;
}
.child{
    float: left;
    width:200px;
    background:green;
    height: 100px;
}

This is working jsfiddle. Change child width to more then 200px and they will stack.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

I used this and it worked out well for me. If your directory is

"repo" and your project is "hello" copy the project there

cd /path/to/my/repo

Initialize your directory

git init

Stage the project

git add hello

commit the project

git commit

Add configurations using the email and username you are using in Bitbucket

git config --global user.email
git config --global user.name

Add comment to the project

git commit -m 'comment'

push the project now

git push origin master

Check out of the master

git checkout master

MongoDB SELECT COUNT GROUP BY

Additionally if you need to restrict the grouping you can use:

db.events.aggregate( 
    {$match: {province: "ON"}},
    {$group: {_id: "$date", number: {$sum: 1}}}  
)

How to return JSON data from spring Controller using @ResponseBody

In my case I was using jackson-databind-2.8.8.jar that is not compatible with JDK 1.6 I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.

Getting json body in aws Lambda via API gateway

I think there are a few things to understand when working with API Gateway integration with Lambda.

Lambda Integration vs Lambda Proxy Integration

There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.

As of September 2017, you no longer have to configure mappings to access the request body.

Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.

Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.

Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.

Words need to navigate the thinking. To get the terminologies straight.

  • Lambda Proxy Integration = Pass through
    Simply pass the HTTP request through to lambda.

  • Lambda Integration = Template transformation
    Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.

body is escaped string, not JSON

Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.

"body": "{\"foo\":\"bar\"}" 

If tested in a JSON formatter.

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

The document below is about response but it should apply to request.

The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.

For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.

The AWS documentation shows what to do.

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

regex string replace

This should work :

str = str.replace(/[^a-z0-9-]/g, '');

Everything between the indicates what your are looking for

  1. / is here to delimit your pattern so you have one to start and one to end
  2. [] indicates the pattern your are looking for on one specific character
  3. ^ indicates that you want every character NOT corresponding to what follows
  4. a-z matches any character between 'a' and 'z' included
  5. 0-9 matches any digit between '0' and '9' included (meaning any digit)
  6. - the '-' character
  7. g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string

Then your expression is delimited by / before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".

Adding null values to arraylist

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

Output :

2
null value
5

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

iframe to Only Show a Certain Part of the Page

Set the iframe to the appropriate width and height and set the scrolling attribute to "no".

If the area you want is not in the top-left portion of the page, you can scroll the content to the appropriate area. Refer to this question:

Scrolling an iframe with javascript?

I believe you'll only be able to scroll it if both pages are on the same domain.

How to change the new TabLayout indicator color and height

To change indicator color and height programmatically you can use reflection. for example for indicator color use code below:

        try {
            Field field = TabLayout.class.getDeclaredField("mTabStrip");
            field.setAccessible(true);
            Object ob = field.get(tabLayout);
            Class<?> c = Class.forName("android.support.design.widget.TabLayout$SlidingTabStrip");
            Method method = c.getDeclaredMethod("setSelectedIndicatorColor", int.class);
            method.setAccessible(true);
            method.invoke(ob, Color.RED);//now its ok
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

and to change indicator height use "setSelectedIndicatorHeight" instead of "setSelectedIndicatorColor" then invoke it by your desired height

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Add x and y labels to a pandas plot

pandas uses matplotlib for basic dataframe plots. So, if you are using pandas for basic plot you can use matplotlib for plot customization. However, I propose an alternative method here using seaborn which allows more customization of the plot while not going into the basic level of matplotlib.

Working Code:

import pandas as pd
import seaborn as sns
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
ax= sns.lineplot(data=df2, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category') 

enter image description here

laravel collection to array

Try this:

$comments_collection = $post->comments()->get()->toArray();

see this can help you
toArray() method in Collections

What is the equivalent to getLastInsertId() in Cakephp?

You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?

If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.

How do I handle the window close event in Tkinter?

I'd like to thank the answer by Apostolos for bringing this to my attention. Here's a much more detailed example for Python 3 in the year 2019, with a clearer description and example code.


Beware of the fact that destroy() (or not having a custom window closing handler at all) will destroy the window and all of its running callbacks instantly when the user closes it.

This can be bad for you, depending on your current Tkinter activity, and especially when using tkinter.after (periodic callbacks). You might be using a callback which processes some data and writes to disk... in that case, you obviously want the data writing to finish without being abruptly killed.

The best solution for that is to use a flag. So when the user requests window closing, you mark that as a flag, and then react to it.

(Note: I normally design GUIs as nicely encapsulated classes and separate worker threads, and I definitely don't use "global" (I use class instance variables instead), but this is meant to be a simple, stripped-down example to demonstrate how Tk abruptly kills your periodic callbacks when the user closes the window...)

from tkinter import *
import time

# Try setting this to False and look at the printed numbers (1 to 10)
# during the work-loop, if you close the window while the periodic_call
# worker is busy working (printing). It will abruptly end the numbers,
# and kill the periodic callback! That's why you should design most
# applications with a safe closing callback as described in this demo.
safe_closing = True

# ---------

busy_processing = False
close_requested = False

def close_window():
    global close_requested
    close_requested = True
    print("User requested close at:", time.time(), "Was busy processing:", busy_processing)

root = Tk()
if safe_closing:
    root.protocol("WM_DELETE_WINDOW", close_window)
lbl = Label(root)
lbl.pack()

def periodic_call():
    global busy_processing

    if not close_requested:
        busy_processing = True
        for i in range(10):
            print((i+1), "of 10")
            time.sleep(0.2)
            lbl["text"] = str(time.time()) # Will error if force-closed.
            root.update() # Force redrawing since we change label multiple times in a row.
        busy_processing = False
        root.after(500, periodic_call)
    else:
        print("Destroying GUI at:", time.time())
        try: # "destroy()" can throw, so you should wrap it like this.
            root.destroy()
        except:
            # NOTE: In most code, you'll wanna force a close here via
            # "exit" if the window failed to destroy. Just ensure that
            # you have no code after your `mainloop()` call (at the
            # bottom of this file), since the exit call will cause the
            # process to terminate immediately without running any more
            # code. Of course, you should NEVER have code after your
            # `mainloop()` call in well-designed code anyway...
            # exit(0)
            pass

root.after_idle(periodic_call)
root.mainloop()

This code will show you that the WM_DELETE_WINDOW handler runs even while our custom periodic_call() is busy in the middle of work/loops!

We use some pretty exaggerated .after() values: 500 milliseconds. This is just meant to make it very easy for you to see the difference between closing while the periodic call is busy, or not... If you close while the numbers are updating, you will see that the WM_DELETE_WINDOW happened while your periodic call "was busy processing: True". If you close while the numbers are paused (meaning that the periodic callback isn't processing at that moment), you see that the close happened while it's "not busy".

In real-world usage, your .after() would use something like 30-100 milliseconds, to have a responsive GUI. This is just a demonstration to help you understand how to protect yourself against Tk's default "instantly interrupt all work when closing" behavior.

In summary: Make the WM_DELETE_WINDOW handler set a flag, and then check that flag periodically and manually .destroy() the window when it's safe (when your app is done with all work).

PS: You can also use WM_DELETE_WINDOW to ask the user if they REALLY want to close the window; and if they answer no, you don't set the flag. It's very simple. You just show a messagebox in your WM_DELETE_WINDOW and set the flag based on the user's answer.

show distinct column values in pyspark dataframe: python

you could do

distinct_column = 'somecol' 

distinct_column_vals = df.select(distinct_column).distinct().collect()
distinct_column_vals = [v[distinct_column] for v in distinct_column_vals]

IF... OR IF... in a windows batch file

Never got exist to work.

I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.

Never got batch files to work above Windows XP

Where to change the value of lower_case_table_names=2 on windows xampp

ADD following -

  • look up for: # The MySQL server [mysqld]
  • add this right below it: lower_case_table_names = 1 In file - /etc/mysql/mysql.conf.d/mysqld.cnf

It's works for me.

Format a datetime into a string with milliseconds

from datetime import datetime
from time import clock

t = datetime.utcnow()
print 't == %s    %s\n\n' % (t,type(t))

n = 100000

te = clock()
for i in xrange(1):
    t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"

print

te = clock()
for i in xrange(1):
    t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"

print

te = clock()
for i in xrange(n):
    t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"

print

te = clock()
for i in xrange(n):
    s = str(t)
    t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] 
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "

result

t == 2011-09-28 21:31:45.562000    <type 'datetime.datetime'>


3.33410112179
20110928212155046000  t.strftime('%Y%m%d%H%M%S%f')

1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.658806915404
20110928212130453000 str(t).translate(None,' -:.')

0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

Use of translate() and slicing method run in same time
translate() presents the advantage to be usable in one line

Comparing the times on the basis of the first one:

1.000 * t.strftime('%Y%m%d%H%M%S%f')

0.351 * str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.198 * str(t).translate(None,' -:.')

0.194 * s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

How to create a GUID in Excel?

Italian version:

=CONCATENA(
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
    DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
    DECIMALE.HEX(CASUALE.TRA(0;42949);4))

How to create a function in a cshtml template?

If you want to access your page's global variables, you can do so:

@{
    ViewData["Title"] = "Home Page";

    var LoadingButtons = Model.ToDictionary(person => person, person => false);

    string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}

What is the use of ByteBuffer in Java?

This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.

create a white rgba / CSS3

I believe

rgba( 0, 0, 0, 0.8 )

is equivalent in shade with #333.

Live demo: http://jsfiddle.net/8MVC5/1/

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can get from the same api without any additional api or url call.

HTML

<input class="wd100" id="fromInput" type="text" name="grFrom" placeholder="From" required/>

Javascript

var input = document.getElementById('fromInput');
var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-33.8902, 151.1759),
    new google.maps.LatLng(-33.8474, 1512631)
)

var options = {
bounds: defaultBounds   
}

var autocomplete = new google.maps.places.Autocomplete(input, options);
var searchBox = new google.maps.places.SearchBox(input, {
         bounds: defaultBounds
});


google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();


console.log(places[0].geometry.location.G); // Get Latitude
console.log(places[0].geometry.location.K); // Get Longitude

//Additional information
console.log(places[0].formatted_address); // Formated Address of Place
console.log(places[0].name); // Name of Place






    if (places.length == 0) {
      return;
    }

    var bounds = new google.maps.LatLngBounds();
    console.log(bounds);
     });
   }

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.

I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.

Java 8 stream map on entry set

On Java 9 or later, Map.entry can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry (as suggested in another answer) or AbstractMap.SimpleImmutableEntry would be the way to go.

private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
   int subLength = prefix.length();
   return input.entrySet().stream().map(e -> 
      Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
   }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

Git: How to find a deleted file in the project commit history?

If you prefer to see the size of all deleted file

as well as the associated SHA

git log --all --stat --diff-filter=D --oneline

add a -p to see the contents too

git log --all --stat --diff-filter=D -p

To narrow down to any file simply pipe to grep and search for file name

git log --all --stat --diff-filter=D --oneline | grep someFileName

You might also like this one if you know where the file is

git log --all --full-history -- someFileName

Multiple files upload in Codeigniter

I change upload method with images[] according to @Denmark.

    private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

The easiest way to do this is to format a cell the way you want it, then use the "cell format ..." contextual menu to get to the fill and format colours, use the "more colors ..." button to get to the hexagon colour selector, select the custom tab.

The RGB colours are as in the table at the bottom of the pane. If you prefer HSL values change the color model from RGB to HSL. I have used this to change the saturation on my bad cells. A higher luminosity gives a worse results and the shade of all the cells is the same just the deepness of the colour is modified.

Setting initial values on load with Select2 with Ajax

I`ve added

initSelection: function (element, callback) {

      callback({ id: 1, text: 'Text' });
}

BUT also

.select2('val', []);

at the end.

This solved my issue.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

On Windows (msys) using Docker Toolbox/Machine, I had to add an extra / before /bin/bash to indicate that it was a *nix filepath.

So, docker run --rm -it <image>:latest //bin/bash

How does the "final" keyword in Java work? (I can still modify an object.)

If you make foo static, you must initialize it in the class constructor (or inline where you define it) like the following examples.

Class constructor (not instance):

private static final List foo;

static
{
   foo = new ArrayList();
}

Inline:

private static final List foo = new ArrayList();

The problem here is not how the final modifier works, but rather how the static modifier works.

The final modifier enforces an initialization of your reference by the time the call to your constructor completes (i.e. you must initialize it in the constructor).

When you initialize an attribute in-line, it gets initialized before the code you have defined for the constructor is run, so you get the following outcomes:

  • if foo is static, foo = new ArrayList() will be executed before the static{} constructor you have defined for your class is executed
  • if foo is not static, foo = new ArrayList() will be executed before your constructor is run

When you do not initilize an attribute in-line, the final modifier enforces that you initialize it and that you must do so in the constructor. If you also have a static modifier, the constructor you will have to initialize the attribute in is the class' initialization block : static{}.

The error you get in your code is from the fact that static{} is run when the class is loaded, before the time you instantiate an object of that class. Thus, you will have not initialized foo when the class is created.

Think of the static{} block as a constructor for an object of type Class. This is where you must do the initialization of your static final class attributes (if not done inline).

Side note:

The final modifier assures const-ness only for primitive types and references.

When you declare a final object, what you get is a final reference to that object, but the object itself is not constant.

What you are really achieving when declaring a final attribute is that, once you declare an object for your specific purpose (like the final List that you have declared), that and only that object will be used for that purpose: you will not be able to change List foo to another List, but you can still alter your List by adding/removing items (the List you are using will be the same, only with its contents altered).

Ruby on Rails: Where to define global constants?

A common place to put application-wide global constants is inside config/application.

module MyApp
  FOO ||= ENV.fetch('FOO', nil)
  BAR ||= %w(one two three)

  class Application < Rails::Application
    config.foo_bar = :baz
  end
end

Generating random numbers in C

#include <stdlib.h>

int main()
{
    int x;
    x = rand(6);
    printf("%d", x);
}

Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:

$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'

You get two warnings here. The first one says that the rand function only takes zero arguments, not one as you tried. To get a random number between 0 and n, you can use the expression rand() % n, which is not perfect but ok for small n. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.

The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.

These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

Even icfantv's answer to this question is already perfect, I still have more findings in my test.

As a server socket in listening status, if it only in listening status, and even it accepts request and getting data from the client side, but without any data sending action. We still could restart the server at once after it's stopped. But if any data sending action happens in the server side to the client, the same service(same port) restart will have this error: (Address already in use).

I think this is caused by the TCP/IP design principles. When the server send the data back to client, it must ensure the data sending succeed, in order to do this, the OS(Linux) need monitor the connection even the server application closed this socket. But I still believe kernel socket designer could improve this issue.

Where is web.xml in Eclipse Dynamic Web Project

If you don't see the web.xml file in WEB-INF folder,

enter image description here

- Select Deployment Descriptor and right click on it.
- Then select the Generate Deployment Descriptor Stub

enter image description here

Finally you get web.xml file.

enter image description here

Converting List<Integer> to List<String>

The source for String.valueOf shows this:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Not that it matters much, but I would use toString.

Restarting cron after changing crontab file?

Try this out: sudo cron reload It works for me on ubuntu 12.10

What is the difference between .text, .value, and .value2?

Out of curiosity, I wanted to see how Value performed against Value2. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value. I used the below code to run some tests with various ranges.

If anyone sees anything contrary regarding performance, please post.

Sub Trial_RUN()
    For t = 0 To 5
        TestValueMethod (True)
        TestValueMethod (False)
    Next t

End Sub




Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5

'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.



With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents


beginTime = Now

For Each aCell In .Range(rngAddress).Cells
    If useValue2 Then
        aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
    Else
        aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
    End If

Next aCell

Dim Answer As String
 If useValue2 Then Answer = " using Value2"

.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
            " seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer


End With


End Sub

enter image description here

Convert Rows to columns using 'Pivot' in SQL Server

If you are using SQL Server 2005+, then you can use the PIVOT function to transform the data from rows into columns.

It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.

First up, here are some quick table definitions and data for use:

CREATE TABLE #yt 
(
  [Store] int, 
  [Week] int, 
  [xCount] int
);

INSERT INTO #yt
(
  [Store], 
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

If your values are known, then you will hard-code the query:

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;

See SQL Demo

Then if you need to generate the week number dynamically, your code will be:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Week) 
                    from yt
                    group by Week
                    order by Week
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT store,' + @cols + ' from 
             (
                select store, week, xCount
                from yt
            ) x
            pivot 
            (
                sum(xCount)
                for week in (' + @cols + ')
            ) p '

execute(@query);

See SQL Demo.

The dynamic version, generates the list of week numbers that should be converted to columns. Both give the same result:

| STORE |   1 |   2 |   3 |
---------------------------
|   101 | 138 | 282 | 220 |
|   102 |  96 | 212 | 123 |
|   105 |  37 |  78 |  60 |
|   109 |  59 |  97 |  87 |

What is the difference between an IntentService and a Service?

Intent service is child of Service

IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.

Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication

Safe Area of Xcode 9

The Safe Area Layout Guide helps avoid underlapping System UI elements when positioning content and controls.

The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. So when you add a Status bar to your app, the Safe Area shrink. When you add a Navigation Bar to your app, the Safe Area shrinks again.

On the iPhone X, the Safe Area provides additional inset from the top and bottom screen edges in portrait even when no bar is shown. In landscape, the Safe Area is inset from the sides of the screens and the home indicator.

This is taken from Apple's video Designing for iPhone X where they also visualize how different elements affect the Safe Area.

Recommended way to get hostname in Java

Just one-liner ... cross platform (Windows-Linux-Unix-Mac(Unix)) [Always works, No DNS required]:

String hostname = new BufferedReader(
    new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream()))
   .readLine();

You're done !!

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

writing to serial port from linux command line

echo '\x12\x02'

will not be interpreted, and will literally write the string \x12\x02 (and append a newline) to the specified serial port. Instead use

echo -n ^R^B

which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.

The stty command should work, unless another program is interfering. A common culprit is gpsd which looks for GPS devices being plugged in.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

Convert Map<String,Object> to Map<String,String>

Now that we have Java 8/streams, we can add one more possible answer to the list:

Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.

Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

How do I fix a Git detached head?

Detached head means you have not checked out your branch properly or you have just checked out a single commit.

If you encounter such an issue then first stash your local changes so that you won't lose your changes.

After that... checkout your desired branch using the command:

Let's say you want branch MyOriginalBranch:

git checkout -b someName origin/MyOriginalBranch

Remote origin already exists on 'git push' to a new repository

I just faced this issue myself and I just removed it by removing the origin. the origin is removed by this command

git remove rm origin

try implementing this command.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

As the accepted answer suggests you can add "using" to all views by adding to section of config file.

But for a single view you could just use

@using SomeNamespace.Extensions

How do I make a Docker container start automatically on system boot?

Yes, docker has restart policies such as docker run --restart=always that will handle this. This is also available in the compose.yml config file as restart: always.

How do I break a string in YAML over multiple lines?

To preserve newlines use |, for example:

|
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with newlines preserved.

is translated to "This is a very long sentence?\n that spans several lines in the YAML?\n but which will be rendered as a string?\n with newlines preserved.\n"

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

How to get response from S3 getObject in Node.js?

At first glance it doesn't look like you are doing anything wrong but you don't show all your code. The following worked for me when I was first checking out S3 and Node:

var AWS = require('aws-sdk');

if (typeof process.env.API_KEY == 'undefined') {
    var config = require('./config.json');
    for (var key in config) {
        if (config.hasOwnProperty(key)) process.env[key] = config[key];
    }
}

var s3 = new AWS.S3({accessKeyId: process.env.AWS_ID, secretAccessKey:process.env.AWS_KEY});
var objectPath = process.env.AWS_S3_FOLDER +'/test.xml';
s3.putObject({
    Bucket: process.env.AWS_S3_BUCKET, 
    Key: objectPath,
    Body: "<rss><data>hello Fred</data></rss>",
    ACL:'public-read'
}, function(err, data){
    if (err) console.log(err, err.stack); // an error occurred
    else {
        console.log(data);           // successful response
        s3.getObject({
            Bucket: process.env.AWS_S3_BUCKET, 
            Key: objectPath
        }, function(err, data){
            console.log(data.Body.toString());
        });
    }
});

Why do we use arrays instead of other data structures?

Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.

Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.

In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.

  MyArray   [5]
     ^       ^
  Pointer  Offset

All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).

For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================

In an array, we know that each element is next to each other in memory. A C array (Called MyArray here) is simply a pointer to the first element:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^
MyArray

If we wanted to look up MyArray[4], internally it would be accessed like this:

   0     1     2     3     4 
=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
                           ^
MyArray + 4 ---------------/
(Pointer + Offset)

Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000] would take the same amount of time as getting MyArray[5].

An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node

========    ========    ========    ========    ========
| Data |    | Data |    | Data |    | Data |    | Data |
|      | -> |      | -> |      | -> |      | -> |      | 
|  P1  |    |  P2  |    |  P3  |    |  P4  |    |  P5  |        
========    ========    ========    ========    ========

P(X) stands for Pointer to next node.

Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.

If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.

This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.

Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.

You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.

Take our array again. This time, I want to find the array element that holds the value '5'.

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^     ^     ^     ^     ^   FOUND!

In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.

Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.

Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.

A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.

         ==========
         |  Root  |         
         ==========
        /          \ 
  =========       =========
  | Child |       | Child |
  =========       =========
                  /       \
            =========    =========
            | Child |    | Child |
            =========    =========

 Assume that each connector is really a Pointer

When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.

This means that the values in a binary tree could look like this:

         ==========
         |   100  |         
         ==========
        /          \ 
  =========       =========
  |  200  |       |   50  |
  =========       =========
                  /       \
            =========    =========
            |   75  |    |   25  |
            =========    =========

When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:

  • Is 75 less than 100? Look at Right Node
  • Is 75 greater than 50? Look at Left Node
  • There is the 75!

Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.

That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.

This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.

Add Auto-Increment ID to existing table?

ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key FIRST

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

What is the 'realtime' process priority setting for?

It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.

What is the difference between Swing and AWT?

As far as when AWT may be more useful than Swing -

  • you may be targeting an older JVM or platform that doesn't support Swing. This used to really come into play if you were building Applets - you wanted to target the lowest common denominator so people wouldn't have to install a newer Java plugin. I'm not sure what the current most widely installed version of the Java plugin is - this may be different today.
  • some people prefer the native look of AWT over Swing's 'not quite there' platform skins. (There are better 3rd party native looking skins than Swing's implementations BTW) Lots of people preferred using AWT's FileDialog over Swing's FileChooser because it gave the platform file dialog most people were used to rather than the 'weird' custom Swing one.

How to copy and paste code without rich text formatting?

If you are using MS Word then try ALT+E, S, U, Enter (Uses the Paste Special)

pass post data with window.location.href

You can use GET instead of pass, but don't use this method for important values,

function passIDto(IDval){    
window.location.href = "CustomerBasket.php?oridd=" +  IDval ;
}   

In the CustomerBasket.php

<?php
  $value = $_GET["oridd"];
  echo  $value;
?>

Extract a substring using PowerShell

PS> $a = "-----start-------Hello World------end-------"
PS> $a.substring(17, 11)
         or
PS> $a.Substring($a.IndexOf('H'), 11)

$a.Substring(argument1, argument2) --> Here argument1 = Starting position of the desired alphabet and argument2 = Length of the substring you want as output.

Here 17 is the index of the alphabet 'H' and since we want to Print till Hello World, we provide 11 as the second argument

Cannot ping AWS EC2 instance

A few years late but hopefully this will help someone else...

1) First make sure the EC2 instance has a public IP. If has a Public DNS or Public IP address (circled below) then you should be good. This will be the address you ping. AWS public DNS address

2) Next make sure the Amazon network rules allow Echo Requests. Go to the Security Group for the EC2.

  • right click, select inbound rules
  • A: select Add Rule
  • B: Select Custom ICMP Rule - IPv4
  • C: Select Echo Request
  • D: Select either Anywhere or My IP
  • E: Select Save

Add a Security Group ICMP Rule to allow Pings and Echos

3) Next, Windows firewall blocks inbound Echo requests by default. Allow Echo requests by creating a windows firewall exception...

  • Go to Start and type Windows Firewall with Advanced Security
  • Select inbound rules

Add a Windows Server ICMP Rule to allow Pings and Echos

4) Done! Hopefully you should now be able to ping your server.

HTML input textbox with a width of 100% overflows table cells

The problem has been explained previously so I will only reiterate: width doesn't take into account border and padding. One possible answer to this not discussed but which I have found helped me out a bunch is to wrap your inputs. Here's the code, and I'll explain how this helps in a second:

<table>
  <tr>
    <td><div style="overflow:hidden"><input style="width:100%" type="text" name="name" value="hello world" /></div></td>
  </tr>
</table>

The DIV wrapping the INPUT has no padding nor does it have a border. This is the solution. A DIV will expand to its container's size, but it will also respect border and padding. Now, the INPUT will have no issue expanding to the size of its container since it is border-less and pad-less. Also note that the DIV has its overflow set to hidden. It seems that by default items can fall outside of their container with the default overflow of visible. This just ensures that the input stays inside its container and doesn't attempt to poke through.

I've tested this in Chrome and in Fire Fox. Both seem to respect this solution well.

UPDATE: Since I just got a random downvote, I would like to say that a better way to deal with overflow is with the CSS3 box-sizing attribute as described by pricco:

.myinput {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
}

This seems to be pretty well supported by the major browsers and isn't "hacky" like the overflow trick. There are, however, some minor issues on current browsers with this approach (see http://caniuse.com/#search=box-sizing Known Issues).

How do I get the MAX row with a GROUP BY in LINQ query?

I've checked DamienG's answer in LinqPad. Instead of

g.Group.Max(s => s.uid)

should be

g.Max(s => s.uid)

Thank you!

How do I set bold and italic on UILabel of iPhone/iPad?

With Swift 5

For style = BOLD

label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)

For style = Medium

label.font = UIFont(name:"HelveticaNeue-Medium", size: 15.0)

For style = Thin

label.font = UIFont(name:"HelveticaNeue-Thin", size: 15.0)

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

Append TimeStamp to a File Name

Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.

Empty ArrayList equals null

No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true

Convert Unix timestamp to a date string

date -d @1278999698 +'%Y-%m-%d %H:%M:%S' Where the number behind @ is the number in seconds

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

Why are arrays of references illegal?

Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.

A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."

Scraping html tables into R data frames using the XML package

Another option using Xpath.

library(RCurl)
library(XML)

theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)

# Extract table header and contents
tablehead <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/th", xmlValue)
results <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/td", xmlValue)

# Convert character vector to dataframe
content <- as.data.frame(matrix(results, ncol = 8, byrow = TRUE))

# Clean up the results
content[,1] <- gsub(" ", "", content[,1])
tablehead <- gsub(" ", "", tablehead)
names(content) <- tablehead

Produces this result

> head(content)
   Opponent Played Won Drawn Lost Goals for Goals against % Won
1 Argentina     94  36    24   34       148           150 38.3%
2  Paraguay     72  44    17   11       160            61 61.1%
3   Uruguay     72  33    19   20       127            93 45.8%
4     Chile     64  45    12    7       147            53 70.3%
5      Peru     39  27     9    3        83            27 69.2%
6    Mexico     36  21     6    9        69            34 58.3%

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

How to programmatically empty browser cache?

location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.

Installing a pip package from within a Jupyter Notebook not working

The problem is that pyarrow is saved by pip into dist-packages (in your case /usr/local/lib/python2.7/dist-packages). This path is skipped by Jupyter so pip won't help.

As a solution I suggest adding in the first block

import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages')

or whatever is path or python version. In case of Python 3.5 this is

import sys
sys.path.append("/usr/local/lib/python3.5/dist-packages")

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

 sudo nano /etc/nginx/nginx.conf

Add these variables to nginx.conf file:

http {  
  # .....
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

And then restart:

service nginx reload

Android Animation Alpha

This my extension, this is an example of change image with FadIn and FadOut :

fun ImageView.setImageDrawableWithAnimation(@DrawableRes() resId: Int, duration: Long = 300) {    
    if (drawable != null) {
        animate()
            .alpha(0f)
            .setDuration(duration)
             .withEndAction {
                 setImageResource(resId)
                 animate()
                     .alpha(1f)
                     .setDuration(duration)
             }

    } else if (drawable == null) {
        setAlpha(0f)
        setImageResource(resId)
        animate()
            .alpha(1f)
            .setDuration(duration)
    }
}

How to switch between python 2.7 to python 3 from command line?

They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

android:layout_height 50% of the screen size

This is my android:layout_height=50% activity:

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

    <LinearLayout
        android:id="@+id/alipay_login"
        style="@style/loginType"
        android:background="#27b" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/taobao_login"
        style="@style/loginType"
        android:background="#ed6d00" >
    </LinearLayout>

</LinearLayout>

style:

<style name="loginType">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:orientation">vertical</item>
</style>

Do you (really) write exception safe code?

Some of us prefer languages like Java which force us to declare all the exceptions thrown by methods, instead of making them invisible as in C++ and C#.

When done properly, exceptions are superior to error return codes, if for no other reason than you don't have to propagate failures up the call chain manually.

That being said, low-level API library programming should probably avoid exception handling, and stick to error return codes.

It's been my experience that it's difficult to write clean exception handling code in C++. I end up using new(nothrow) a lot.

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Could not autowire field:RestTemplate in Spring boot application

If a TestRestTemplate is a valid option in your unit test, this documentation might be relevant

http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-rest-templates-test-utility

Short answer: if using

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

then @Autowired will work. If using

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)

then create a TestRestTemplate like this

private TestRestTemplate template = new TestRestTemplate();

Java: JSON -> Protobuf & back conversion

Here is my utility class, you may use:

package <removed>;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
 * Author @espresso stackoverflow.
 * Sample use:
 *      Model.Person reqObj = ProtoUtil.toProto(reqJson, Model.Person.getDefaultInstance());
        Model.Person res = personSvc.update(reqObj);
        final String resJson = ProtoUtil.toJson(res);
 **/
public class ProtoUtil {
    public static <T extends Message> String toJson(T obj){
        try{
            return JsonFormat.printer().print(obj);
        }catch(Exception e){
            throw new RuntimeException("Error converting Proto to json", e);
        }
    }
   public static <T extends MessageOrBuilder> T toProto(String protoJsonStr, T message){
        try{
            Message.Builder builder = message.getDefaultInstanceForType().toBuilder();
            JsonFormat.parser().ignoringUnknownFields().merge(protoJsonStr,builder);
            T out = (T) builder.build();
            return out;
        }catch(Exception e){
            throw new RuntimeException(("Error converting Json to proto", e);
        }
    }
}

What is the use of GO in SQL Server Management Studio & Transact SQL?

Go means, whatever SQL statements are written before it and after any earlier GO, will go to SQL server for processing.

Select * from employees;
GO    -- GO 1

update employees set empID=21 where empCode=123;
GO    -- GO 2

In the above example, statements before GO 1 will go to sql sever in a batch and then any other statements before GO 2 will go to sql server in another batch. So as we see it has separated batches.

"Android library projects cannot be launched"?

Through the this steps you can .

  1. In Eclipse , Right Click on Project from Package Explorer.
  2. Select Properties,.
  3. Select Android from Properties pop up window,
  4. See "Is Library" check box,
  5. If it is checked then Unchecked "Is Library" check box.
  6. Click Apply and than OK.

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

Error: macro names must be identifiers using #ifdef 0

This error can also occur if you are not following the marco rules

Like

#define 1K 1024 // Macro rules must be identifiers error occurs

Reason: Macro Should begin with a letter, not a number

Change to

#define ONE_KILOBYTE 1024 // This resolves 

How to copy directories with spaces in the name

robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

Changing the size of a column referenced by a schema-bound view in SQL Server

Check the column collation. This script might change the collation to the table default. Add the current collation to the script.

Java generics: multiple generic parameters?

You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

import java.util.ArrayList;
import java.util.List;

public class GenericMethods {

/*
 Declare the generic type parameter T in this method. 

 After the qualifiers public and static, you put <T> and 
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ? 
 * 
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());


    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak

Sublime Text 2 - Show file navigation in sidebar

You have to add a folder to the Sublime Text window in order to navigate via the sidebar. Go to File -> Open Folder... and select the highest directory you want to be able to navigate.

Also, 'View -> Sidebar -> Show Sidebar' if it still doesn't show. In the new version, there is only an 'open' menu and no separate option for opening a folder.

IOException: The process cannot access the file 'file path' because it is being used by another process

Using FileShare fixed my issue of opening file even if it is opened by another process.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

SQL Server: Difference between PARTITION BY and GROUP BY

As of my understanding Partition By is almost identical to Group By, but with the following differences:

That group by actually groups the result set returning one row per group, which results therefore in SQL Server only allowing in the SELECT list aggregate functions or columns that are part of the group by clause (in which case SQL Server can guarantee that there are unique results for each group).

Consider for example MySQL which allows to have in the SELECT list columns that are not defined in the Group By clause, in which case one row is still being returned per group, however if the column doesn't have unique results then there is no guarantee what will be the output!

But with Partition By, although the results of the function are identical to the results of an aggregate function with Group By, still you are getting the normal result set, which means that one is getting one row per underlying row, and not one row per group, and because of this one can have columns that are not unique per group in the SELECT list.

So as a summary, Group By would be best when needs an output of one row per group, and Partition By would be best when one needs all the rows but still wants the aggregate function based on a group.

Of course there might also be performance issues, see http://social.msdn.microsoft.com/Forums/ms-MY/transactsql/thread/0b20c2b5-1607-40bc-b7a7-0c60a2a55fba.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

just to add another example of what a lambda can do without using map:

a = 10
b = 2

var mixed = (a,b) => a * b; 
// OR
var mixed = (a,b) => { (any logic); return a * b };

console.log(mixed(a,b)) 
// 20

Django - after login, redirect user to his custom page --> mysite.com/username

You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in

This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

EventListener Enter Key

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

Getting the length of two-dimensional array

which 3?

You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.

System.out.println(nir[0].length); 

would give you the length of your first array.

Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).

int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception

What is the volatile keyword useful for?

There are two different uses of volatile keyword.

  1. Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
  2. Reduces the risk of memory in-consistency errors.

Prevents JVM from reading values in register, and forces its value to be read from memory.

A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:

while (busy) {
    /* do something else */
}

The testing thread will continue when another thread turns off the busy flag:

busy = 0;

However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

Reduces the risk of memory consistency errors.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a "happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

The technique of reading, writing without memory consistency errors is called atomic action.

An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.

Below are actions you can specify that are atomic:

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

Cheers!

Detect touch press vs long press vs movement?

From the Android Docs -

onLongClick()

From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).

onTouch()

From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

As for the "moving happens even when I touch" I would set a delta and make sure the View has been moved by at least the delta before kicking in the movement code. If it hasn't been, kick off the touch code.

Calculating Time Difference

The datetime module will do all the work for you:

>>> import datetime
>>> a = datetime.datetime.now()
>>> # ...wait a while...
>>> b = datetime.datetime.now()
>>> print(b-a)
0:03:43.984000

If you don't want to display the microseconds, just use (as gnibbler suggested):

>>> a = datetime.datetime.now().replace(microsecond=0)
>>> b = datetime.datetime.now().replace(microsecond=0)
>>> print(b-a)
0:03:43

Constants in Kotlin -- what's a recommended way to create them?

Something that isn't mentioned in any of the answers is the overhead of using companion objects. As you can read here, companion objects are in fact objects and creating them consumes resources. In addition, you may need to go through more than one getter function every time you use your constant. If all that you need is a few primitive constants you'll probably just be better off using val to get a better performance and avoid the companion object.

TL;DR; of the article:

Using companion object actually turns this code

class MyClass {

    companion object {
        private val TAG = "TAG"
    }

    fun helloWorld() {
        println(TAG)
    }
}

Into this code:

public final class MyClass {
    private static final String TAG = "TAG";
    public static final Companion companion = new Companion();

    // synthetic
    public static final String access$getTAG$cp() {
        return TAG;
    }

    public static final class Companion {
        private final String getTAG() {
            return MyClass.access$getTAG$cp();
        }

        // synthetic
        public static final String access$getTAG$p(Companion c) {
            return c.getTAG();
        }
    }

    public final void helloWorld() {
        System.out.println(Companion.access$getTAG$p(companion));
    }
}

So try to avoid them.

How to use Spring Boot with MySQL database and JPA?

When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication is not enough.

You will have to specify the base package for component scan

@ComponentScan("base_package")

For JPA

@EnableJpaRepositories(basePackages = "repository")

is also needed, so spring data will know where to look into for repository interfaces.

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

error: command 'gcc' failed with exit status 1 while installing eventlet

Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with:

sudo apt-get install python-dev 

for python3 use:

sudo apt-get install python3-dev

For eventlet you might also need the libevent libraries installed so if you get an error talking about that you can install libevent with:

sudo apt-get install libevent-dev

How to import a SQL Server .bak file into MySQL?

The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm

The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.

You will need to use SQL server to extract these. SQL Server Express is free and will do the job.

So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO

This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH 
   MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', 
   MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO

At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database.

MySQL Cannot Add Foreign Key Constraint

I had this same issue then i corrected the Engine name as Innodb in both parent and child tables and corrected the reference field name FOREIGN KEY (c_id) REFERENCES x9o_parent_table(c_id)
then it works fine and the tables are installed correctly. This will be use full for someone.

Convert a bitmap into a byte array

Very simple use this just in one line:

byte[] imgdata = File.ReadAllBytes(@"C:\download.png");

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I removed compile 'com.android.support:support-v4:18.0.+' in dependencies, and it works

Possible reasons for timeout when trying to access EC2 instance

Just reboot the Ec2 Instance once you applied Rules

Changing permissions via chmod at runtime errors with "Operation not permitted"

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Different font size of strings in the same TextView

in kotlin do it as below by using html

HtmlCompat.fromHtml("<html><body><h1>This is Large Heading :-</h1><br>This is normal size<body></html>",HtmlCompat.FROM_HTML_MODE_LEGACY)

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Adding another point of view to above mentioned solutions.

Implicit Wait: When created, is alive until the WebDriver object dies. And is like common for all operations.

Whereas,
Explicit wait, can be declared for a particular operation depending upon the webElement behavior. It has the benefit of customizing the polling time and satisfaction of the condition.
For example, we declared implicit Wait of 10 secs but an element takes more than that, say 20 seconds and sometimes may appears on 5 secs, so in this scenario, Explicit wait is declared.

About "*.d.ts" in TypeScript

Like @takeshin said .d stands for declaration file for typescript (.ts).

Few points to be clarified before proceeding to answer this post -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

For ex -

If you install javascript library -

npm install --save mylib

and try importing it in typescript code -

import * from "mylib";

you will get error.

"Cannot find module 'mylib'."

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

Now when you try -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

CSS background image alt attribute

This article from W3C tells you what they think you should do https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage

and has examples here http://mars.dequecloud.com/demo/ImgRole.htm

among which

<a href="http://www.facebook.com">
 <span class="fb_logo" role="img" aria-label="Connect via Facebook">
 </span>
</a>

Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:

<a href="http://www.facebook.com"><span class="fb_logo">
  Connect via Facebook
</span></a>

.fb_logo {
  height: 37px; width: 37px;
  background-image: url('../gfx/logo-facebook.svg');
  color:transparent; overflow:hidden; /* hide the text */
}

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

Try placing the host name (db01.mysql.vm.MyHostingServer.net) in your windows host (C:\windows\system32\drivers\etc\host) file along with it's IP address and port number and see if that helps.

Xcode 9 Swift Language Version (SWIFT_VERSION)

This Solution works when nothing else works:

I spent more than a week to convert the whole project and came to a solution below:

First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.

Go to Project Directory in the Terminal and Type:

pod deintegrate

This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.

Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.

So to remove those errors you have two options:

  1. Comment down all the code you have used from cocoapods library.
  2. Create a wrapper class which has dummy methods similar to cocopods library, and then call it.

Once all the errors get removed you can convert the code to the latest swift version.

Sometimes if you are getting weird errors then try cleaning derived data and try again.

How do I pass options to the Selenium Chrome driver using Python?

This is how I did it.

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-extensions')

chrome = webdriver.Chrome(chrome_options=chrome_options)

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Which icon sizes should my Windows application's icon include?

Not 96x96, use 64x64 instead. I usually use:

  • 16 - status/titlebar button
  • 32 - desktop icon
  • 48 - folder view
  • 64/128 - Additional sizes

256 works as well on XP, however, old resource compilers sometimes complained about "out of memory" errors.

Best Timer for using in a Windows service

Both System.Timers.Timer and System.Threading.Timer will work for services.

The timers you want to avoid are System.Web.UI.Timer and System.Windows.Forms.Timer, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.

Use System.Timers.Timer like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

If you choose System.Threading.Timer, you can use as follows:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}

Both examples comes from the MSDN pages.

Two versions of python on linux. how to make 2.7 the default

Enter the command

which python

//output:
/usr/bin/python

cd /usr/bin
ls -l

Here you can see something like this

lrwxrwxrwx 1 root   root            9 Mar  7 17:04  python -> python2.7

your default python2.7 is soft linked to the text 'python'

So remove the softlink python

sudo rm -r python

then retry the above command

ls -l

you can see the softlink is removed

-rwxr-xr-x 1 root   root      3670448 Nov 12 20:01  python2.7

Then create a new softlink for python3.6

ln -s /usr/bin/python3.6 python

Then try the command python in terminal

//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux

Type help, copyright, credits or license for more information.

When should I really use noexcept?

In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):

Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a noexcept specifier (§13.5.1.1) can make that desire explicit.

Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore, terminate() supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly, noexcept provides a simple escape for errors where trying to recover seems infeasible.

double compute(double x) noexcept;     {
    string s = "Courtney and Anya";
    vector<double> tmp(10);
    // ...
}

The vector constructor may fail to acquire memory for its ten doubles and throw a std::bad_alloc. In that case, the program terminates. It terminates unconditionally by invoking std::terminate() (§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between the throw and the noexcept (e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding a noexcept specifier, we indicate that our code was not written to cope with a throw.

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

How to wait for a number of threads to complete?

One way would be to make a List of Threads, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call join() on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.

A better approach is to use an ExecutorService and its associated methods:

List<Callable> callables = ... // assemble list of Callables here
                               // Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
//       bother saving them

Using an ExecutorService (and all of the new stuff from Java 5's concurrency utilities) is incredibly flexible, and the above example barely even scratches the surface.

ReactJS SyntheticEvent stopPropagation() only works with React events?

I ran into this problem yesterday, so I created a React-friendly solution.

Check out react-native-listener. It's working very well so far. Feedback appreciated.

How to download a file from a website in C#

Try this example:

public void TheDownload(string path)
{
  System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Disposition",
             "attachment; filename=" + toDownload.Name);
  HttpContext.Current.Response.AddHeader("Content-Length",
             toDownload.Length.ToString());
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.WriteFile(patch);
  HttpContext.Current.Response.End();
} 

The implementation is done in the follows:

TheDownload("@"c:\Temporal\Test.txt"");

Source: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

Check If only numeric values were entered in input. (jQuery)

I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.

$('#txtbox').on('paste', function (e) {
            var $this = $(this);
            setTimeout(function (e) {
                if (($this.val()).match(/[^0-9]/g))
                {
                    $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");                       
                    setTimeout(function (e) {
                        $this.val(null);
                    },2500);
                }                   
            }, 5);
        });

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I tried below line as per @Andrie answer but didn't work,

op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

so after hunting more, I did work around to get it work successfully.

Here is my code snip.

AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];

    NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
    [jsonAcceptableContentTypes addObject:@"text/plain"];
    jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
    operation.responseSerializer = jsonResponseSerializer;

Hope this will help someone out there.