Programs & Examples On #Ora 00054

ORA-00054: resource busy and acquire with NOWAIT specified

ORA-00054: resource busy and acquire with NOWAIT specified

When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.

If you absolutely must, you can kill the OS process as well (look up v$process.spid), which would release any locks it was holding on to.

See this for more detailed info.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.

If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.

You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.

In a production system, it really depends. For oracle 10g and older, you could execute

LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);

In a separate session but have the following ready in case it takes too long.

alter system kill session '....

It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.

In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.

ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);

Finally it may be best to wait until there are few users in the system to do this kind of maintenance.

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

How to add a new line of text to an existing file in Java?

In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.

private static final String newLine = System.getProperty("line.separator");

private synchronized void writeToFile(String msg)  {
    String fileName = "c:\\TEMP\\runOutput.txt";
    PrintWriter printWriter = null;
    File file = new File(fileName);
    try {
        if (!file.exists()) file.createNewFile();
        printWriter = new PrintWriter(new FileOutputStream(fileName, true));
        printWriter.write(newLine + msg);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}

How can I detect if this dictionary key exists in C#?

I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }

Calling it:

var entry = GetKey(dictList,"KeyValue1");

Gets the job done.

How do I check what version of Python is running my script?

Several answers already suggest how to query the current python version. To check programmatically the version requirements, I'd make use of one of the following two methods:

# Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))

# Method 2: 
import platform
from distutils.version import StrictVersion 
assert(StrictVersion(platform.python_version()) >= "2.6")

Options for initializing a string array

Basic:

string[] myString = new string[]{"string1", "string2"};

or

string[] myString = new string[4];
myString[0] = "string1"; // etc.

Advanced: From a List

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

From StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();

Why does visual studio 2012 not find my tests?

I found the best way to troubleshoot this issue is to create a .proj msbuild file and add your unit test projects which you hare having an issue into this file and execute the tests using the command line version of mstest. I found a small configuration issue in my app.config which only appeared when running the tests from mstest - otherwise the test project built just fine. Also you will find any indirect reference issues with this method as well. Once you can run the Unit test from the command line using mstest you can then do a clean solution, rebuild solution and your test should be discovered properly.

How to write palindrome in JavaScript

Or you could do it like this.

var palindrome = word => word == word.split('').reverse().join('')

How do I run a program with commandline arguments using GDB within a Bash script?

In addition to the answer of Hugo Ideler. When using arguments having themself prefix like -- or -, I was not sure to conflict with gdb one.

It seems gdb takes all after args option as arguments for the program.

At first I wanted to be sure, I ran gdb with quotes around your args, it is removed at launch.

This works too, but optional:

gdb --args executablename "--arg1" "--arg2" "--arg3"

This doesn't work :

gdb --args executablename "--arg1" "--arg2" "--arg3" -tui

In that case, -tui is used as my program parameter not as gdb one.

Error: request entity too large

I've used another practice for this problem with multer dependancie.

Example:

multer = require('multer');

var uploading = multer({
  limits: {fileSize: 1000000, files:1},
});

exports.uploadpictureone = function(req, res) {
  cloudinary.uploader.upload(req.body.url, function(result) {
    res.send(result);
  });
};

module.exports = function(app) {
    app.route('/api/upload', uploading).all(uploadPolicy.isAllowed)
        .post(upload.uploadpictureone);
};

JavaScript require() on client side

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

How do I read CSV data into a record array in NumPy?

Using numpy.loadtxt

A quite simple method. But it requires all the elements being float (int and so on)

import numpy as np 
data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  

How to select min and max values of a column in a datatable?

The most efficient way to do this (believe it or not) is to make two variables and write a for loop.

Bootstrap 3 offset on right not left

Since Google seems to like this answer...

If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:

.offset-right-12 {
  margin-right: 100%;
}
.offset-right-11 {
  margin-right: 91.66666667%;
}
.offset-right-10 {
  margin-right: 83.33333333%;
}
.offset-right-9 {
  margin-right: 75%;
}
.offset-right-8 {
  margin-right: 66.66666667%;
}
.offset-right-7 {
  margin-right: 58.33333333%;
}
.offset-right-6 {
  margin-right: 50%;
}
.offset-right-5 {
  margin-right: 41.66666667%;
}
.offset-right-4 {
  margin-right: 33.33333333%;
}
.offset-right-3 {
  margin-right: 25%;
}
.offset-right-2 {
  margin-right: 16.66666667%;
}
.offset-right-1 {
  margin-right: 8.33333333%;
}
.offset-right-0 {
  margin-right: 0;
}
@media (min-width: 576px) {
  .offset-sm-right-12 {
    margin-right: 100%;
  }
  .offset-sm-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-sm-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-sm-right-9 {
    margin-right: 75%;
  }
  .offset-sm-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-sm-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-sm-right-6 {
    margin-right: 50%;
  }
  .offset-sm-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-sm-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-sm-right-3 {
    margin-right: 25%;
  }
  .offset-sm-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-sm-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-sm-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 768px) {
  .offset-md-right-12 {
    margin-right: 100%;
  }
  .offset-md-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-md-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-md-right-9 {
    margin-right: 75%;
  }
  .offset-md-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-md-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-md-right-6 {
    margin-right: 50%;
  }
  .offset-md-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-md-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-md-right-3 {
    margin-right: 25%;
  }
  .offset-md-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-md-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-md-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .offset-lg-right-12 {
    margin-right: 100%;
  }
  .offset-lg-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-lg-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-lg-right-9 {
    margin-right: 75%;
  }
  .offset-lg-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-lg-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-lg-right-6 {
    margin-right: 50%;
  }
  .offset-lg-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-lg-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-lg-right-3 {
    margin-right: 25%;
  }
  .offset-lg-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-lg-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-lg-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .offset-xl-right-12 {
    margin-right: 100%;
  }
  .offset-xl-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-xl-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-xl-right-9 {
    margin-right: 75%;
  }
  .offset-xl-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-xl-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-xl-right-6 {
    margin-right: 50%;
  }
  .offset-xl-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-xl-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-xl-right-3 {
    margin-right: 25%;
  }
  .offset-xl-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-xl-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-xl-right-0 {
    margin-right: 0;
  }
}

Sleep for milliseconds

The way to sleep your program in C++ is the Sleep(int) method. The header file for it is #include "windows.h."

For example:

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;

int main()
{
    int x = 6000;
    Sleep(x);
    cout << "6 seconds have passed" << endl;
    return 0;
}

The time it sleeps is measured in milliseconds and has no limit.

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds

How do I remove link underlining in my HTML email?

I added both declarations on the a href which worked in outlook and gmail apps. outlook ignores the !important and gmail needs it. Web versions of email work with both/either.

text-decoration: none !important; text-decoration: none;

Throw HttpResponseException or return Request.CreateErrorResponse?

Case #1

  1. Not necessarily, there are other places in the pipeline to modify the response (action filters, message handlers).
  2. See above -- but if the action returns a domain model, then you can't modify the response inside the action.

Cases #2-4

  1. The main reasons to throw HttpResponseException are:
    • if you are returning a domain model but need to handle error cases,
    • to simplify your controller logic by treating errors as exceptions
  2. These should be equivalent; HttpResponseException encapsulates an HttpResponseMessage, which is what gets returned back as the HTTP response.

    e.g., case #2 could be rewritten as

    public HttpResponseMessage Get(string id)
    {
        HttpResponseMessage response;
        var customer = _customerService.GetById(id);
        if (customer == null)
        {
            response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        else
        {
            response = Request.CreateResponse(HttpStatusCode.OK, customer);
            response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
        }
        return response;
    }
    

    ... but if your controller logic is more complicated, throwing an exception might simplify the code flow.

  3. HttpError gives you a consistent format for the response body and can be serialized to JSON/XML/etc, but it's not required. e.g., you may not want to include an entity-body in the response, or you might want some other format.

Apache won't start in wamp

That is what I did and it helped me to find out what my Apache-PHP needed:

C:\Users\Admin>cd C:\wamp\bin\apache\apache2.4.9\bin

C:\wamp\bin\apache\apache2.4.9\bin>httpd -t
Syntax OK

C:\wamp\bin\apache\apache2.4.9\bin>httpd -k start
[Thu Apr 23 14:14:52.150189 2015] [mpm_winnt:error] [pid 3184:tid 112] 
(OS 2)The system cannot find the file specified.  : AH00436: 
No installed service named "Apache2.4".

C:\wamp\bin\apache\apache2.4.9\bin>

The most simple solution:

Uninstall and reinstall WAMP (do not even try to set it up on top of existing installation - it would not help)

P.S.

If you wonder how did I get to this situation, here is the answer: I was trying to install WAMP and it throws me an error in the middle of installation saying:

httpd.exe - System Error

The program can't start because MSVCR110.dll is missing from your computer. 
Try reinstalling the program to fix this problem.

OK

I got and installed Microsoft Visual C++ 2012 Redistributable from here http://www.microsoft.com/en-us/download/details.aspx?id=30679#

And it gave me the "dll" and the MYSQL started working, but not Apache. To make Apache to work I uninstalled and reinstalled WAMP.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at the DateDiff() function.

-- Syntax
-- DATEDIFF ( datepart , startdate , enddate )

-- Example usage
SELECT DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDiff
SELECT DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDiff
SELECT DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDiff
SELECT DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDiff
SELECT DATEDIFF(HOUR, GETDATE(), GETDATE() + 1) AS HourDiff
...

You can see it in action / play with it here

How to detect IE11?

var ua = navigator.userAgent.toString().toLowerCase();
var match = /(trident)(?:.*rv:([\w.]+))?/.exec(ua) ||/(msie) ([\w.]+)/.exec(ua)||['',null,-1];
var rv = match[2];
return rv;

SQL Server: the maximum number of rows in table

We have tables in SQL Server 2005 and 2008 with over 1 Billion rows in it (30 million added daily). I can't imagine going down the rats nest of splitting that out into a new table each day.

Much cheaper to add the appropriate disk space (which you need anyway) and RAM.

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

jQuery get textarea text

you can get textarea data by name and id

// by name
<textarea name="comment"></textarea>
let text_area_data = $('textarea[name="comment"]').val();

// by id
<textarea id="comment" name="comment"></textarea>
let text_area_data = $('textarea#comment').val();

Difference between try-catch and throw in java

All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

For more detail visit Java tutorial for beginners.

Difference between single and double quotes in Bash

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

The bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

See this example when using let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $bar under single quotes would not expand and needs to be double-quoted as

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..)) should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using let can be simply written as

(( bar=1, foo = bar + 1 ))

Always remember to use $((..)) without single quotes

Though the $((..)) can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..)) operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl statement to pass a counter every time a request is made, do

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++)) is passed to requestCounter field.

How to dismiss AlertDialog in android

Here is How I close my alertDialog

lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
                alertDialog.setTitle(clickedObj.getAd());
                alertDialog.setMessage("Ögrenci Bilgileri Güncelle?");
                alertDialog.setIcon(R.drawable.ic_info);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // User pressed YES button. Write Logic Here
                    }
                });
                alertDialog.setNegativeButton("Iptal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //alertDialog.
                        alertDialog.setCancelable(true); // HERE

                    }
                });
                alertDialog.show();
                return true;
            }
        });

Mocking HttpClient in unit tests

Here's a simple solution, which worked well for me.

Using the moq mocking library.

// ARRANGE
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
   .Protected()
   // Setup the PROTECTED method to mock
   .Setup<Task<HttpResponseMessage>>(
      "SendAsync",
      ItExpr.IsAny<HttpRequestMessage>(),
      ItExpr.IsAny<CancellationToken>()
   )
   // prepare the expected response of the mocked http call
   .ReturnsAsync(new HttpResponseMessage()
   {
      StatusCode = HttpStatusCode.OK,
      Content = new StringContent("[{'id':1,'value':'1'}]"),
   })
   .Verifiable();

// use real http client with mocked handler here
var httpClient = new HttpClient(handlerMock.Object)
{
   BaseAddress = new Uri("http://test.com/"),
};

var subjectUnderTest = new MyTestClass(httpClient);

// ACT
var result = await subjectUnderTest
   .GetSomethingRemoteAsync('api/test/whatever');

// ASSERT
result.Should().NotBeNull(); // this is fluent assertions here...
result.Id.Should().Be(1);

// also check the 'http' call was like we expected it
var expectedUri = new Uri("http://test.com/api/test/whatever");

handlerMock.Protected().Verify(
   "SendAsync",
   Times.Exactly(1), // we expected a single external request
   ItExpr.Is<HttpRequestMessage>(req =>
      req.Method == HttpMethod.Get  // we expected a GET request
      && req.RequestUri == expectedUri // to this uri
   ),
   ItExpr.IsAny<CancellationToken>()
);

Source: https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/

How to Add Date Picker To VBA UserForm

Just throw some light in to some issues related to this control.

Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.

In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.

In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.

If you need the file, download MSCOMCT2.OCX from here.

html 5 audio tag width

You also can set the width of a audio tag by JavaScript:

audio = document.getElementById('audio-id');
audio.style.width = '200px';

Convert PEM to PPK file format

If you have Linux machine just install puttygen in your system and use use below command to convert the key

pem to ppk use below command:

puttygen keyname -o keyname.ppk

Below command is use to convert ppk to pem not pem to ppk

puttygen filename.ppk -O private-openssh -o filename.pem

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

How to drop columns by name in a data frame

I can´t answer your question in the comments due to low reputation score.

The next code will give you an error because the paste function return a character string

for(i in 1:length(var.out)) {
   paste("data$", var.out[i], sep="") <- NULL
}

Here is a possible solution:

for(i in 1:length(var.out)) {

  text_to_source <- paste0 ("data$", var.out[i], "<- NULL") # Write a line of your
                                                  # code like a character string
  eval (parse (text=text_to_source)) # Source a text that contains a code
}

or just do:

for(i in 1:length(var.out)) {
  data[var.out[i]] <- NULL
}

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

Node.js - use of module.exports as a constructor

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

How to avoid warning when introducing NAs by coercion

I have slightly modified the jangorecki function for the case where we may have a variety of values that cannot be converted to a number. In my function, a template search is performed and if the template is not found, FALSE is returned.! before gperl, it means that we need those vector elements that do not match the template. The rest is similar to the as.num function. Example:

as.num.pattern <- function(x, pattern){
  stopifnot(is.character(x))
  na = !grepl(pattern, x)
  x[na] = -Inf
  x = as.numeric(x)
  x[na] = NA_real_
  x
}

as.num.pattern(c('1', '2', '3.43', 'char1', 'test2', 'other3', '23/40', '23, 54 cm.'))

[1] 1.00 2.00 3.43   NA   NA   NA   NA   NA

python: SyntaxError: EOL while scanning string literal

In this case, three single quotations or three double quotations both will work! For example:

    """Parameters:
    ...Type something.....
    .....finishing statement"""

OR

    '''Parameters:
    ...Type something.....
    .....finishing statement'''

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

In my case I was modifying the request to append a header (using Fiddler) to an https request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:

  1. Click Tools > Fiddler Options.
  2. Click the HTTPS tab. Ensure the Decrypt HTTPS traffic checkbox is checked.
  3. Click the Export Fiddler Root Certificate to Desktop button.

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

How to include a sub-view in Blade templates?

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
      @include('parentFolder.childFolder.mypage')
  </html>

Windows 7 - Add Path

Another method that worked for me on Windows 7 that did not require administrative privileges:

Click on the Start menu, search for "environment," click "Edit environment variables for your account."

In the window that opens, select "PATH" under "User variables for username" and click the "Edit..." button. Add your new path to the end of the existing Path, separated by a semi-colon (%PATH%;C:\Python27;...;C:\NewPath). Click OK on all the windows, open a new CMD window, and test the new variable.

Can you nest html forms?

In a word, no. You can have several forms in a page but they should not be nested.

From the html5 working draft:

4.10.3 The form element

Content model:

Flow content, but with no form element descendants.

Convert float64 column to int64 in Pandas

You can need to pass in the string 'int64':

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]})  # some test dataframe

>>> df['a'].astype('int64')
0    1
1    2
Name: a, dtype: int64

There are some alternative ways to specify 64-bit integers:

>>> df['a'].astype('i8')      # integer with 8 bytes (64 bit)
0    1
1    2
Name: a, dtype: int64

>>> import numpy as np
>>> df['a'].astype(np.int64)  # native numpy 64 bit integer
0    1
1    2
Name: a, dtype: int64

Or use np.int64 directly on your column (but it returns a numpy.array):

>>> np.int64(df['a'])
array([1, 2], dtype=int64)

How to get difference between two dates in Year/Month/Week/Day?

What about using the System.Data.Linq namespace and its SqlMethods.DateDiffMonth method?

For example, say:

DateTime starDT = {01-Jul-2009 12:00:00 AM}
DateTime endDT = {01-Nov-2009 12:00:00 AM}

Then:

int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(startDT, endDT);

==> 4

There are other DateDiff static methods in the SqlMethods class.

Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

Online PHP syntax checker / validator

Here is a similar question to yours. (Practically the same.)

What ways are there to validate PHP code?

Edit

The top answer there suggest this resource:

http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/v4/syntax-check.php

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

Try this simple arrow funtion:

setTimeout( () => { $("#div").addClass("error") }, 900 );

Convert seconds to HH-MM-SS with JavaScript?

As Cleiton pointed out in his answer, moment.js can be used for this:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

Error Importing SSL certificate : Not an X.509 Certificate

Many CAs will provide a cert in PKCS7 format.

According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails

The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.

If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

printf %f with only 2 numbers after the decimal point?

Use this:

printf ("%.2f", 3.14159);

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

Sorting a vector of custom objects

    // sort algorithm example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::sort
    #include <vector>       // std::vector
    using namespace std;
    int main () {
        char myints[] = {'F','C','E','G','A','H','B','D'};
        vector<char> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33
        // using default comparison (operator <):
        sort (myvector.begin(), myvector.end());           //(12 32 45 71)26 80 53 33
        // print out content:
        cout << "myvector contains:";
        for (int i=0; i!=8; i++)
            cout << ' ' <<myvector[i];
        cout << '\n';
        system("PAUSE");
    return 0;
    }

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

Same issue as in Error in launching AVD:

1) Install the Intel x86 Emulator Accelerator (HAXM installer) from the Android SDK Manager;

enter image description here

2) Run (for Windows):

{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe

or (for OSX):

{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\IntelHAXM_1.1.1_for_10_9_and_above.dmg

3) Start the emulator.

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Make columns of equal width in <table>

I think that this will do the trick:

table{
    table-layout: fixed;
    width: 300px;
}

What is a good practice to check if an environmental variable exists or not?

To be on the safe side use

os.getenv('FOO') or 'bar'

A corner case with the above answers is when the environment variable is set but is empty

For this special case you get

print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`

or

if "FOO" in os.environ:
    print("FOO is here")
# prints FOO is here - however its not

To avoid this just use or

os.getenv('FOO') or 'bar'

Then you get

print(os.getenv('FOO') or 'bar')
# bar

When do we have empty environment variables?

You forgot to set the value in the .env file

# .env
FOO=

or exported as

$ export FOO=

or forgot to set it in settings.py

# settings.py
os.environ['FOO'] = ''

Update: if in doubt, check out these one-liners

>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))

$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"

How to get the list of properties of a class?

Based on @MarcGravell's answer, here's a version that works in Unity C#.

ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
    Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}

What techniques can be used to speed up C++ compilation times?

Use forward declarations where you can. If a class declaration only uses a pointer or reference to a type, you can just forward declare it and include the header for the type in the implementation file.

For example:

// T.h
class Class2; // Forward declaration

class T {
public:
    void doSomething(Class2 &c2);
private:
    Class2 *m_Class2Ptr;
};

// T.cpp
#include "Class2.h"
void Class2::doSomething(Class2 &c2) {
    // Whatever you want here
}

Fewer includes means far less work for the preprocessor if you do it enough.

How to get a substring between two strings in PHP?

I use

if (count(explode("<TAG>", $input))>1){
      $content = explode("</TAG>",explode("<TAG>", $input)[1])[0];
}else{
      $content = "";
}

Subtitue <TAG> for whatever delimiter you want.

PHP foreach loop through multidimensional array

<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));

//Iterate through an array declared above

foreach($php_multi_array as $key => $value)
{
    if (!is_array($value))
    {
        echo $key ." => ". $value ."\r\n" ;
    }
    else
    {
       echo $key ." => array( \r\n";

       foreach ($value as $key2 => $value2)
       {
           echo "\t". $key2 ." => ". $value2 ."\r\n";
       }

       echo ")";
    }
}
?>

OUTPUT:

lang => PHP
type => array( 
    c_type => MULTI
    p_type => ARRAY
)

Reference Source Code

How can I get sin, cos, and tan to use degrees instead of radians?

You can use a function like this to do the conversion:

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}

Note that functions like sin, cos, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:

function toRadians (angle) {
  return angle * (Math.PI / 180);
}

which you could use to do something like tan(toRadians(45)).

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

In my case (python) it failed because I had these two lines of code in the file, inherited from an older code

http.client.HTTPConnection._http_vsn = 10 http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Can I use CASE statement in a JOIN condition?

A CASE expression returns a value from the THEN portion of the clause. You could use it thusly:

SELECT  * 
FROM    sys.indexes i 
    JOIN sys.partitions p 
        ON i.index_id = p.index_id  
    JOIN sys.allocation_units a 
        ON CASE 
           WHEN a.type IN (1, 3) AND a.container_id = p.hobt_id THEN 1
           WHEN a.type IN (2) AND a.container_id = p.partition_id THEN 1
           ELSE 0
           END = 1

Note that you need to do something with the returned value, e.g. compare it to 1. Your statement attempted to return the value of an assignment or test for equality, neither of which make sense in the context of a CASE/THEN clause. (If BOOLEAN was a datatype then the test for equality would make sense.)

How to specify the default error page in web.xml?

On Servlet 3.0 or newer you could just specify

<web-app ...>
    <error-page>
        <location>/general-error.html</location>
    </error-page>
</web-app>

But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

That should cover the most common ones.

CSS: fixed position on x-axis but not y?

Very easy solution is:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

How to ping multiple servers and return IP address and Hostnames using batch script?

This works for spanish operation system.

Script accepts two parameters:

  • a file with the list of IP or domains
  • output file

script.bat listofurls.txt output.txt

@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
    set SERVER_ADDRESS=No se pudo resolver el host
    for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') 
    do (
        if %%v==Haciendo set SERVER_ADDRESS=%%z
        if %%v==Respuesta set SERVER_ADDRESS=%%x
        if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)

How do you embed binary data in XML?

Base64 is indeed the right answer but CDATA is not, that's basically saying: "this could be anything", however it must not be just anything, it has to be Base64 encoded binary data. XML Schema defines Base 64 binary as a primitive datatype which you can use in your xsd.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

How can I give an imageview click effect like a button on Android?

I create sample here, just change ImageView into ClickableImageView from your layout. Hope it help.

enter image description here

add to array if it isn't there already

if (!in_array($value, $a))
  $a[]=$value;

How can I setup & run PhantomJS on Ubuntu?

Be aware this is definitely one way to do it:

$ sudo apt-get install phantomjs
$ phantomjs -v
1.6.0

Sadly, it installs 1.6 and not the latest one, but this works for my purposes.

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT distinct new com.model.referential.Asset(firefCode,firefDescription) FROM AssetClass ")
List<AssetClass> findDistinctAsset();

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

How to go back to previous page if back button is pressed in WebView?

This is my solution. It works also in Fragment.

webView.setOnKeyListener(new OnKeyListener()
{
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            WebView webView = (WebView) v;

            switch(keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack())
                    {
                        webView.goBack();
                        return true;
                    }
                    break;
            }
        }

        return false;
    }
});

I want my android application to be only run in portrait mode?

I use

 android:screenOrientation="nosensor"

It is helpful if you do not want to support up side down portrait mode.

Can you write nested functions in JavaScript?

Is this really possible.

Yes.

_x000D_
_x000D_
function a(x) {    // <-- function_x000D_
  function b(y) { // <-- inner function_x000D_
    return x + y; // <-- use variables from outer scope_x000D_
  }_x000D_
  return b;       // <-- you can even return a function._x000D_
}_x000D_
console.log(a(3)(4));
_x000D_
_x000D_
_x000D_

How can I convert a .jar to an .exe?

Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:

exestub.sh:

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt  0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
    case $1 in
        -Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
        -D*)  JAVA_OPT="$JAVA_OPT $1" ;;
        *)    PROG_OPT="$PROG_OPT $1" ;;
    esac
    shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT

Then you create your runnable file from your jar:

$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable

It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>, as <myexe> is a valid zip/jar file.

C# Creating an array of arrays

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

Resource u'tokenizers/punkt/english.pickle' not found

Just make sure you are using Jupyter Notebook and in a notebook, do the following:

import nltk

nltk.download()

Then one popup window will appear (showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml) From that you have to download everything.

Then rerun your code.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How to execute UNION without sorting? (SQL)

Consider these tables (Standard SQL code, runs on SQL Server 2008):

WITH A 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (1), 
                     (2), 
                     (3), 
                     (4), 
                     (5), 
                     (6) 
             ) AS T (col)
     ),
     B 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (9), 
                     (8), 
                     (7), 
                     (6), 
                     (5), 
                     (4) 
             ) AS T (col)
     ), ...

The desired effect is this to sort table A by col ascending, sort table B by col descending then unioning the two, removing duplicates, retaining order before the union and leaving table A results on the "top" with table B on the "bottom" e.g. (pesudo code)

(
 SELECT *
   FROM A
  ORDER 
     BY col
)
UNION
(
 SELECT *
   FROM B
  ORDER 
     BY col DESC
);

Of course, this won't work in SQL because there can only be one ORDER BY clause and it can only be applied to the top level table expression (or whatever the output of a SELECT query is known as; I call it the "resultset").

The first thing to address is the intersection between the two tables, in this case the values 4, 5 and 6. How the intersection should be sorted needs to be specified in SQL code, therefore it is desirable that the designer specifies this too! (i.e. the person asking the question, in this case).

The implication in this case would seem to be that the intersection ("duplicates") should be sorted within the results for table A. Therefore, the sorted resultset should look like this:

      VALUES (1), -- A including intersection, ascending
             (2), -- A including intersection, ascending
             (3), -- A including intersection, ascending
             (4), -- A including intersection, ascending
             (5), -- A including intersection, ascending
             (6), -- A including intersection, ascending
             (9), -- B only, descending 
             (8), -- B only, descending  
             (7), -- B only, descending 

Note in SQL "top" and "bottom" has no inferent meaning and a table (other than a resultset) has no inherent ordering. Also (to cut a long story short) consider that UNION removes duplicate rows by implication and must be applied before ORDER BY. The conclusion has to be that each table's sort order must be explicitly defined by exposing a sort order column(s) before being unioned. For this we can use the ROW_NUMBER() windowed function e.g.

     ...
     A_ranked
     AS
     (
      SELECT col, 
             ROW_NUMBER() OVER (ORDER BY col) AS sort_order_1
        FROM A                      -- include the intersection
     ),
     B_ranked
     AS
     (
      SELECT *, 
             ROW_NUMBER() OVER (ORDER BY col DESC) AS sort_order_1
        FROM B
       WHERE NOT EXISTS (           -- exclude the intersection
                         SELECT * 
                           FROM A
                          WHERE A.col = B.col 
                        )
     )
SELECT *, 1 AS sort_order_0 
  FROM A_ranked
UNION
SELECT *, 2 AS sort_order_0 
  FROM B_ranked
ORDER BY sort_order_0, sort_order_1;

Using PowerShell to write a file in UTF-8 without the BOM

One technique I utilize is to redirect output to an ASCII file using the Out-File cmdlet.

For example, I often run SQL scripts that create another SQL script to execute in Oracle. With simple redirection (">"), the output will be in UTF-16 which is not recognized by SQLPlus. To work around this:

sqlplus -s / as sysdba "@create_sql_script.sql" |
Out-File -FilePath new_script.sql -Encoding ASCII -Force

The generated script can then be executed via another SQLPlus session without any Unicode worries:

sqlplus / as sysdba "@new_script.sql" |
tee new_script.log

Nesting await in Parallel.ForEach

Here is a simple generic implementation of a ForEachAsync method, based on an ActionBlock from the TPL Dataflow library, now embedded in the .NET 5 platform:

public static Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action,
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = dop });
    try
    {
        foreach (var item in source) block.Post(item);
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    return block.Completion;
}

This solution enumerates eagerly the supplied IEnumerable, and sends immediately all its elements to the ActionBlock. So it is not very suitable for enumerables with huge number of elements. Below is a more sophisticated approach, that enumerates the source lazily, and sends its elements to the ActionBlock one by one:

public static async Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action, new ExecutionDataflowBlockOptions()
    { MaxDegreeOfParallelism = dop, BoundedCapacity = dop });
    try
    {
        foreach (var item in source)
            if (!await block.SendAsync(item).ConfigureAwait(false)) break;
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    try { await block.Completion.ConfigureAwait(false); }
    catch { block.Completion.Wait(); } // Propagate AggregateException
}

These two methods have different behavior in case of exceptions. The first¹ propagates an AggregateException containing the exceptions directly in its InnerExceptions property. The second propagates an AggregateException that contains another AggregateException with the exceptions. Personally I find the behavior of the second method more convenient in practice, because awaiting it eliminates automatically a level of nesting, and so I can simply catch (AggregateException aex) and handle the aex.InnerExceptions inside the catch block. The first method requires to store the Task before awaiting it, so that I can gain access the task.Exception.InnerExceptions inside the catch block. For more info about propagating exceptions from async methods, look here or here.

Both implementations handle gracefully any errors that may occur during the enumeration of the source. The ForEachAsync method does not complete before all pending operations are completed. No tasks are left behind unobserved (in fire-and-forget fashion).

¹ The first implementation elides async and await.

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

Why use 'virtual' for class properties in Entity Framework model definitions?

It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.

Edit to clarify "create a proxy around": By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".

The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.

If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.

Edit to describe why properties would be marked as virtual

Properties such as:

 public ICollection<RSVP> RSVPs { get; set; }

Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.

//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
    return _RSVPs;
}

public void set_RSVPs(RSVP value)
{
    _RSVPs = value;
}

private RSVP _RSVPs;

That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get and set functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:

 public virtual ICollection<RSVP> RSVPs;

Browser Caching of CSS files

To the first part of your question - yes, browsers cache css files (if this is not disabled by browser's configuration). Many browsers have key combination to reload a page without a cache. If you made changes to css and want users to see them immediately instead of waiting next time when browser reloads the files without caching, you can change the way CSS ir served by adding some parameters to the url like this:

/style.css?modified=20012009

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

check if a string matches an IP address pattern in python?

You can make it a little faster by compiling it:

expression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
for st in strs:
    if expression.match(st):
       print 'IP!'

Regex - how to match everything except a particular pattern

You could use a look-ahead assertion:

(?!999)\d{3}

This example matches three digits other than 999.


But if you happen not to have a regular expression implementation with this feature (see Comparison of Regular Expression Flavors), you probably have to build a regular expression with the basic features on your own.

A compatible regular expression with basic syntax only would be:

[0-8]\d\d|\d[0-8]\d|\d\d[0-8]

This does also match any three digits sequence that is not 999.

SQL Server 2008 R2 can't connect to local database in Management Studio

I have the same error but with different case. Let me quote the solution from here:

Luckly I also have the same set up on my desktop. I have installed first default instance and then Sql Express. Everything is fine for me for several days. Then I tried connecting the way you trying, i.e with MachineName\MsSqlServer to default instance and I got exctaly the same error.

So the solution is when you trying to connect to default instance you don't need to provide instance name.(well this is something puzzled me, why it is failing when we are giving instance name when it is a default instance? Is it some bug, don't know)

Just try with - PC-NAME and everything will be fine. PC-NAME is the MSSQLServer instance.

Edit : Well after reading your question again I realized that you are not aware of the fact that MSSQLSERVER is the default instance of Sql Server. And for connecting to default instance (MSSQLSERVER) you don't need to provide the instance name in connection string. The "MachineName" is itself means "MachineName\MSSQLSERVER".

Differences between Microsoft .NET 4.0 full Framework and Client Profile

Cameron MacFarland nailed it.

I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.

Example on ToggleButton

I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.

I suggest using the radio button provided by Android by default.

Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/

and the android documentation is here-

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Thanks.

SVN Error - Not a working copy

I just got "not a working copy", and for me the reason was the Automouter on Unix. Just a fresh "cd /path/to/work/directory" did the trick.

ReflectionException: Class ClassName does not exist - Laravel

In case of using psr-0 , check the class name does not contain underscore .

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

For the first example and base on the django's doc
It will always return the second list, indeed a non empty list is see as a True value for Python thus python return the 'last' True value so the second list

In [74]: mylist1 = [False]
In [75]: mylist2 = [False, True, False,  True, False]
In [76]: mylist1 and mylist2
Out[76]: [False, True, False, True, False]
In [77]: mylist2 and mylist1
Out[77]: [False]

What is @RenderSection in asp.net MVC

If

(1) you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()

    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

(2) you have Contacts.cshtml

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

(3) you have About.cshtml

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

How do I correctly detect orientation change using Phonegap on iOS?

I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:

// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation); 

function updateOrientation(e) {
switch (e.orientation)
{   
    case 0:
        // Do your thing
        break;

    case -90:
        // Do your thing
        break;

    case 90:
        // Do your thing
        break;

    default:
        break;
    }
}

You may have some luck searching the PhoneGap Google Group for the term "orientation".

One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.

One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.


UPDATE fixed the code above, it works now

How to do join on multiple criteria, returning all combinations of both criteria

SELECT  aa.*,
        bb.meal
FROM    table1 aa
        INNER JOIN table2 bb
            ON aa.tableseat = bb.tableseat AND
                aa.weddingtable = bb.weddingtable
        INNER JOIN
        (
            SELECT  a.tableSeat
            FROM    table1 a
                    INNER JOIN table2 b
                        ON a.tableseat = b.tableseat AND
                            a.weddingtable = b.weddingtable
            WHERE b.meal IN ('chicken', 'steak')
            GROUP by a.tableSeat
            HAVING COUNT(DISTINCT b.Meal) = 2
        ) c ON aa.tableseat = c.tableSeat

How to join (merge) data frames (inner, outer, left, right)

For an inner join on all columns, you could also use fintersect from the data.table-package or intersect from the dplyr-package as an alternative to merge without specifying the by-columns. this will give the rows that are equal between two dataframes:

merge(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
dplyr::intersect(df1, df2)
#   V1 V2
# 1  B  2
# 2  C  3
data.table::fintersect(setDT(df1), setDT(df2))
#    V1 V2
# 1:  B  2
# 2:  C  3

Example data:

df1 <- data.frame(V1 = LETTERS[1:4], V2 = 1:4)
df2 <- data.frame(V1 = LETTERS[2:3], V2 = 2:3)

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

Custom height Bootstrap's navbar

I believe you are using Bootstrap 3. If so, please try this code, here is the bootply

<header>
    <div class="navbar navbar-static-top navbar-default">
        <div class="navbar-header">
            <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </div>
        <div class="container" style="background:yellow;">
            <a href="/">
                <img src="img/logo.png" class="logo img-responsive">
            </a>

            <nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
                <ul class="nav navbar-nav" style="display:inline-block;">
                    <li><a href="">Portfolio</a></li>
                    <li><a href="">Blog</a></li>
                    <li><a href="">Contact</a></li>
                </ul>
            </nav>
        </div>
    </div>
</header>

Spring Boot application can't resolve the org.springframework.boot package

Try this, It might work for you too.

  1. Open command prompt and go to the project folder.
  2. Build project (For Maven, Run mvn clean install)
  3. After successful build,
    • Open your project on any IDE (intellij / eclipse).
    • Restart your IDE incase it is already opened.

This worked for me on both v1.5 and v2.1

Listing only directories in UNIX

Long listing of directories

  • ls -l | grep '^d'
  • ls -l | grep "^d"

Listing directories
- ls -d */

Android. Fragment getActivity() sometimes returns null

The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

Edited, since onAttach(Activity) is depreciated & now onAttach(Context) is being used

Python pip install module is not found. How to link python to pip location?

Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install

What is a 'Closure'?

I'll give an example (in JavaScript):

function makeCounter () {
  var count = 0;
  return function () {
    count += 1;
    return count;
  }
}

var x = makeCounter();

x(); returns 1

x(); returns 2

...etc...

What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.

Here is my currying example again:

function add (a) {
  return function (b) {
    return a + b;
  }
}

var add3 = add(3);

add3(4); returns 7

What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.

Summernote image upload

UPLOAD IMAGES WITH PROGRESS BAR

Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.

HTML

<progress></progress>

<div id="summernote"></div>

JS

// initialise editor

$('#summernote').summernote({
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
});

// send the file

function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
                return myXhr;
            },
            url: root + '/assets/scripts/php/app/uploadEditorImages.php',
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                editor.insertImage(welEditable, url);
            }
        });
}

// update progress bar

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded, max:e.total});
        // reset progress on complete
        if (e.loaded == e.total) {
            $('progress').attr('value','0.0');
        }
    }
}

How to enable Bootstrap tooltip on disabled button?

Simply add the disabled class to the button instead of the disabled attribute to make it visibly disabled instead.

<button class="btn disabled" rel="tooltip" data-title="Dieser Link führt zu Google">button disabled</button>

Note: this button only appears to be disabled, but it still triggers events, and you just have to be mindful of that.

How do I resolve ClassNotFoundException?

Add the full path of jar file to the CLASSPATH. In linux use: export CLASSPATH=".:/full/path/to/file.jar:$CLASSPATH". Other way worked (without editing the CLASSPATH) was unzipping the jar in the current project folder.

Ways didn't work for me:

1) Using -cp option with full path of jar file.

2) Using -cpwith only the name of jar when located in the current folder

3) Copying the jar to the current project folder

4) Copying the jar to standard location of java jars (/usr/share/java)

This solution is reported for class com.mysql.jdbc.Driver in mysql-connector-java.5-*.jar, working on linux with OpenJDK version 1.7

Detailed 500 error message, ASP + IIS 7.5

Fot people who have tried EVERYTHING and just CANNOT get the error details to show, like me, it's a good idea to check the different levels of configuration. I have a config file on Website level and on Application level (inside the website) check both. Also, as it turned out, I had Detailed Errors disabled on the highest node in IIS (just underneath Start Page, it has the name that is the same as the webservers computername). Check the Error Pages there.

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

How to disable compiler optimizations in gcc?

For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.

See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html

How to read a local text file?

If you want to prompt the user to select a file, then read its contents:

// read the contents of a file input
const readInputFile = (inputElement, callback) => {
  const reader = new FileReader();
  reader.onload = () => {
    callback(reader.result)
  };
  reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
export const openFile = (callback) => {
  var el = document.createElement('input');
  el.setAttribute('type', 'file');
  el.style.display = 'none';
  document.body.appendChild(el);
  el.onchange = () => {readInputFile(el, (data) => {
    callback(data)
    document.body.removeChild(el);
  })}
  el.click();
}

Usage:

// prompt the user to select a file and read it
openFile(data => {
    console.log(data)
  })

How to add line break for UILabel?

I have faced same problem, and here is, how i solved the problem. Hope this will be helpful for someone.

// Swift 2

   lblMultiline.lineBreakMode = .ByWordWrapping // or use NSLineBreakMode.ByWordWrapping
   lblMultiline.numberOfLines = 0 

// Objective-C

  lblMultiline.lineBreakMode = NSLineBreakByWordWrapping;
  lblMultiline.numberOfLines = 0;

// C# (Xamarin.iOS)

  lblMultiline.LineBreakMode = UILineBreakMode.WordWrap;
  lblMultiline.Lines = 0;  

Button Center CSS

Consider adding this to your CSS to resolve the problem:

button {
    margin: 0 auto;
    display: block;
}

Escaping Double Quotes in Batch Script

eplawless's own answer simply and effectively solves his specific problem: it replaces all " instances in the entire argument list with \", which is how Bash requires double-quotes inside a double-quoted string to be represented.

To generally answer the question of how to escape double-quotes inside a double-quoted string using cmd.exe, the Windows command-line interpreter (whether on the command line - often still mistakenly called the "DOS prompt" - or in a batch file):See bottom for a look at PowerShell.

tl;dr:

  • You must use "" when passing a string to a(nother) batch file and you may use "" with applications created with Microsoft's C/C++/.NET compilers (which also accept \"), which on Windows includes Python and Node.js:

    • Example: foo.bat "We had 3"" of rain."

    • The following applies to batch files only:

      • "" is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument.

      • Sadly, however, not only are the enclosing double-quotes retained (as usual), but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument, %1:

      • set "str=%~1" removes the enclosing double-quotes; set "str=%str:""="%" then converts the doubled double-quotes to single ones.
        Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

  • \" is required - as the only option - by many other programs, (e.g., Ruby, Perl, and even Microsoft's own Windows PowerShell(!)), but ITS USE IS NOT SAFE:

    • \" is what many executables and interpreters either require - including Windows PowerShell - when passed strings from the outside - or, in the case of Microsoft's compilers, support as an alternative to "" - ultimately, though, it's up to the target program to parse the argument list.
      • Example: foo.exe "We had 3\" of rain."
    • HOWEVER, USE OF \" CAN RESULT IN UNWANTED, ARBITRARY EXECUTION OF COMMANDS and/or INPUT/OUTPUT REDIRECTIONS:
      • The following characters present this risk: & | < >
      • For instance, the following results in unintended execution of the ver command; see further below for an explanation and the next bullet point for a workaround:
        • foo.exe "3\" of snow" "& ver."
    • For Windows PowerShell, \"" and "^"" are robust, but limited alternatives (see section "Calling PowerShell's CLI ..." below).
  • If you must use \", there are only 3 safe approaches, which are, however quite cumbersome: Tip of the hat to T S for his help.

    • Using (possibly selective) delayed variable expansion in your batch file, you can store literal \" in a variable and reference that variable inside a "..." string using !var! syntax - see T S's helpful answer.

      • The above approach, despite being cumbersome, has the advantage that you can apply it methodically and that it works robustly, with any input.
    • Only with LITERAL strings - ones NOT involving VARIABLES - do you get a similarly methodical approach: categorically ^-escape all cmd.exe metacharacters: " & | < > and - if you also want to suppress variable expansion - %:
      foo.exe ^"3\^" of snow^" ^"^& ver.^"

    • Otherwise, you must formulate your string based on recognizing which portions of the string cmd.exe considers unquoted due to misinterpreting \" as closing delimiters:

      • in literal portions containing shell metacharacters: ^-escape them; using the example above, it is & that must be ^-escaped:
        foo.exe "3\" of snow" "^& ver."

      • in portions with %...%-style variable references: ensure that cmd.exe considers them part of a "..." string and that that the variable values do not themselves have embedded, unbalanced quotes - which is not even always possible.

For background information, read on.


Background

Note: This is based on my own experiments. Do let me know if I'm wrong.

POSIX-like shells such as Bash on Unix-like systems tokenize the argument list (string) before passing arguments individually to the target program: among other expansions, they split the argument list into individual words (word splitting) and remove quoting characters from the resulting words (quote removal). The target program is handed an array of individual arguments, with syntactic quotes removed.

By contrast, the Windows command interpreter apparently does not tokenize the argument list and simply passes the single string comprising all arguments - including quoting chars. - to the target program.
However, some preprocessing takes place before the single string is passed to the target program: ^ escape chars. outside of double-quoted strings are removed (they escape the following char.), and variable references (e.g., %USERNAME%) are interpolated first.

Thus, unlike in Unix, it is the target program's responsibility to parse to parse the arguments string and break it down into individual arguments with quotes removed. Thus, different programs can hypothetically require differing escaping methods and there's no single escaping mechanism that is guaranteed to work with all programs - https://stackoverflow.com/a/4094897/45375 contains excellent background on the anarchy that is Windows command-line parsing.

In practice, \" is very common, but NOT SAFE, as mentioned above:

Since cmd.exe itself doesn't recognize \" as an escaped double-quote, it can misconstrue later tokens on the command line as unquoted and potentially interpret them as commands and/or input/output redirections.
In a nutshell: the problem surfaces, if any of the following characters follow an opening or unbalanced \": & | < >; for example:

foo.exe "3\" of snow" "& ver."

cmd.exe sees the following tokens, resulting from misinterpreting \" as a regular double-quote:

  • "3\"
  • of
  • snow" "
  • rest: & ver.

Since cmd.exe thinks that & ver. is unquoted, it interprets it as & (the command-sequencing operator), followed by the name of a command to execute (ver. - the . is ignored; ver reports cmd.exe's version information).
The overall effect is:

  • First, foo.exe is invoked with the first 3 tokens only.
  • Then, command ver is executed.

Even in cases where the accidental command does no harm, your overall command won't work as designed, given that not all arguments are passed to it.

Many compilers / interpreters recognize ONLY \" - e.g., the GNU C/C++ compiler, Python, Perl, Ruby, even Microsoft's own Windows PowerShell when invoked from cmd.exe - and, except (with limitations) for Windows PowerShell with \"", for them there is no simple solution to this problem.
Essentially, you'd have to know in advance which portions of your command line are misinterpreted as unquoted, and selectively ^-escape all instances of & | < > in those portions.

By contrast, use of "" is SAFE, but is regrettably only supported by Microsoft-compiler-based executables and batch files (in the case of batch files, with the quirks discussed above), which notable excludes PowerShell - see next section.


Calling PowerShell's CLI from cmd.exe or POSIX-like shells:

Note: See the bottom section for how quoting is handled inside PowerShell.

When invoked from the outside - e.g., from cmd.exe, whether from the command line or a batch file:

  • PowerShell [Core] v6+ now properly recognizes "" (in addition to \"), which is both safe to use and whitespace-preserving.

    • pwsh -c " ""a & c"".length " doesn't break and correctly yields 6
  • Windows PowerShell (the legacy edition whose last version is 5.1) recognizes only \" and, on Windows also """ and the more robust \"" / "^"" (even though internally PowerShell uses ` as the escape character in double-quoted strings and also accepts "" - see bottom section):

Calling Windows PowerShell from cmd.exe / a batch file:

  • "" breaks, because it is fundamentally unsupported:

    • powershell -c " ""ab c"".length " -> error "The string is missing the terminator"
  • \" and """ work in principle, but aren't safe:

    • powershell -c " \"ab c\".length " works as intended: it outputs 5 (note the 2 spaces)
    • But it isn't safe, because cmd.exe metacharacters break the command, unless escaped:
      powershell -c " \"a& c\".length " breaks, due to the &, which would have to be escaped as ^&
  • \"" is safe, but normalize interior whitespace, which can be undesired:

    • powershell -c " \""a& c\"".length " outputs 4(!), because the 2 spaces are normalized to 1.
  • "^"" is the best choice for Windows PowerShell specifically, where it is both safe and whitespace-preserving, but with PowerShell Core (on Windows) it is the same as \"", i.e, whitespace-normalizing. Credit goes to Venryx for discovering this approach.

    • powershell -c " "^""a& c"^"".length " works: doesn't break - despite & - and outputs 5, i.e., correctly preserved whitespace.

    • PowerShell Core: pwsh -c " "^""a& c"^"".length " works, but outputs 4, i.e. normalizes whitespace, as \"" does.

On Unix-like platforms (Linux, macOS), when calling PowerShell [Core]'s CLI, pwsh, from a POSIX-like shell such as bash:

You must use \", which, however is both safe and whitespace-preserving:

$ pwsh -c " \"a&  c|\".length" # OK: 5

Related information

  • ^ can only be used as the escape character in unquoted strings - inside double-quoted strings, ^ is not special and treated as a literal.

    • CAVEAT: Use of ^ in parameters passed to the call statement is broken (this applies to both uses of call: invoking another batch file or binary, and calling a subroutine in the same batch file):
      • ^ instances in double-quoted values are inexplicably doubled, altering the value being passed: e.g., if variable %v% contains literal value a^b, call :foo "%v%" assigns "a^^b"(!) to %1 (the first parameter) in subroutine :foo.
      • Unquoted use of ^ with call is broken altogether in that ^ can no longer be used to escape special characters: e.g., call foo.cmd a^&b quietly breaks (instead of passing literal a&b too foo.cmd, as would be the case without call) - foo.cmd is never even invoked(!), at least on Windows 7.
  • Escaping a literal % is a special case, unfortunately, which requires distinct syntax depending on whether a string is specified on the command line vs. inside a batch file; see https://stackoverflow.com/a/31420292/45375

    • The short of it: Inside a batch file, use %%. On the command line, % cannot be escaped, but if you place a ^ at the start, end, or inside a variable name in an unquoted string (e.g., echo %^foo%), you can prevent variable expansion (interpolation); % instances on the command line that are not part of a variable reference are treated as literals (e.g, 100%).
  • Generally, to safely work with variable values that may contain spaces and special characters:

    • Assignment: Enclose both the variable name and the value in a single pair of double-quotes; e.g., set "v=a & b" assigns literal value a & b to variable %v% (by contrast, set v="a & b" would make the double-quotes part of the value). Escape literal % instances as %% (works only in batch files - see above).
    • Reference: Double-quote variable references to make sure their value is not interpolated; e.g., echo "%v%" does not subject the value of %v% to interpolation and prints "a & b" (but note that the double-quotes are invariably printed too). By contrast, echo %v% passes literal a to echo, interprets & as the command-sequencing operator, and therefore tries to execute a command named b.
      Also note the above caveat re use of ^ with the call statement.
    • External programs typically take care of removing enclosing double-quotes around parameters, but, as noted, in batch files you have to do it yourself (e.g., %~1 to remove enclosing double-quotes from the 1st parameter) and, sadly, there is no direct way that I know of to get echo to print a variable value faithfully without the enclosing double-quotes.
      • Neil offers a for-based workaround that works as long as the value has no embedded double quotes; e.g.:
        set "var=^&')|;,%!" for /f "delims=" %%v in ("%var%") do echo %%~v
  • cmd.exe does not recognize single-quotes as string delimiters - they are treated as literals and cannot generally be used to delimit strings with embedded whitespace; also, it follows that the tokens abutting the single-quotes and any tokens in between are treated as unquoted by cmd.exe and interpreted accordingly.

    • However, given that target programs ultimately perform their own argument parsing, some programs such as Ruby do recognize single-quoted strings even on Windows; by contrast, C/C++ executables, Perl and Python do not recognize them.
      Even if supported by the target program, however, it is not advisable to use single-quoted strings, given that their contents are not protected from potentially unwanted interpretation by cmd.exe.

Quoting from within PowerShell:

Windows PowerShell is a much more advanced shell than cmd.exe, and it has been a part of Windows for many years now (and PowerShell Core brought the PowerShell experience to macOS and Linux as well).

PowerShell works consistently internally with respect to quoting:

  • inside double-quoted strings, use `" or "" to escape double-quotes
  • inside single-quoted strings, use '' to escape single-quotes

This works on the PowerShell command line and when passing parameters to PowerShell scripts or functions from within PowerShell.

(As discussed above, passing an escaped double-quote to PowerShell from the outside requires \" or, more robustly, \"" - nothing else works).

Sadly, when invoking external programs from PowerShell, you're faced with the need to both accommodate PowerShell's own quoting rules and to escape for the target program:

This problematic behavior is also discussed and summarized in this answer

Double-quotes inside double-quoted strings:

Consider string "3`" of rain", which PowerShell-internally translates to literal 3" of rain.

If you want to pass this string to an external program, you have to apply the target program's escaping in addition to PowerShell's; say you want to pass the string to a C program, which expects embedded double-quotes to be escaped as \":

foo.exe "3\`" of rain"

Note how both `" - to make PowerShell happy - and the \ - to make the target program happy - must be present.

The same logic applies to invoking a batch file, where "" must be used:

foo.bat "3`"`" of rain"

By contrast, embedding single-quotes in a double-quoted string requires no escaping at all.

Single-quotes inside single-quoted strings do not require extra escaping; consider '2'' of snow', which is PowerShell' representation of 2' of snow.

foo.exe '2'' of snow'
foo.bat '2'' of snow'

PowerShell translates single-quoted strings to double-quoted ones before passing them to the target program.

However, double-quotes inside single-quoted strings, which do not need escaping for PowerShell, do still need to be escaped for the target program:

foo.exe '3\" of rain'
foo.bat '3"" of rain'

PowerShell v3 introduced the magic --% option, called the stop-parsing symbol, which alleviates some of the pain, by passing anything after it uninterpreted to the target program, save for cmd.exe-style environment-variable references (e.g., %USERNAME%), which are expanded; e.g.:

foo.exe --% "3\" of rain" -u %USERNAME%

Note how escaping the embedded " as \" for the target program only (and not also for PowerShell as \`") is sufficient.

However, this approach:

  • does not allow for escaping % characters in order to avoid environment-variable expansions.
  • precludes direct use of PowerShell variables and expressions; instead, the command line must be built in a string variable in a first step, and then invoked with Invoke-Expression in a second.

Thus, despite its many advancements, PowerShell has not made escaping much easier when calling external programs. It has, however, introduced support for single-quoted strings.

I wonder if it's fundamentally possible in the Windows world to ever switch to the Unix model of letting the shell do all the tokenization and quote removal predictably, up front, irrespective of the target program, and then invoke the target program by passing the resulting tokens.

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

Java division by zero doesnt throw an ArithmeticException - why?

There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.

If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.

Replacing objects in array

function getMatch(elem) {
    function action(ele, val) {
        if(ele === val){ 
            elem = arr2[i]; 
        }
    }

    for (var i = 0; i < arr2.length; i++) {
        action(elem.id, Object.values(arr2[i])[0]);
    }
    return elem;
}

var modified = arr1.map(getMatch);

Can I convert long to int?

Wouldn't

(int) Math.Min(Int32.MaxValue, longValue)

be the correct way, mathematically speaking?

Jenkins fails when running "service start jenkins"

I faced same issue while setting up jenkins, the problem is that java is not installed and hence not available in path.

The simplest way is to use scp here to copy jdk binaries to aws ec2 box, script won't work if you make one as they keep on updating download urls(Orale, i mean): scp -i C:/Users/key-pair.pem jdk-8u191-linux-x64.tar.gz ec2- [email protected]:~/

$cd /opt

$sudo cp /home/ec2-user/jdk* .

$sudo chmod +x jdk*

$sudo tar xzf jdk-8u191-linux-x64.tar.gz

$sudo tar xzf jdk-8u191-linux-x64.tar.gz

$cd jdk1.8.0_191/

$sudo alternatives --install /usr/bin/java java /opt/jdk1.8.0_191/bin/java 2

$sudo alternatives --config java

Here I download tar.gz file in loal windows and transferred over scp to AWS ec2-user, default dir. Hope it helps.

Description Box using "onmouseover"

This an old question but for people still looking. In JS you can now use the title property.

button.title = ("Popup text here");

iPhone App Minus App Store?

Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.

How to create jar file with package structure?

Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.
C:/workspace/MyProj/bin/classess/com/test/*.class

Go directory bin using command:

cd C:/workspace/MyProj/bin

Step 2: Use below command to generate jar file.

jar cvf helloworld.jar com\test\hello\Hello.class  com\test\orld\HelloWorld.class

Using the above command the classes will be placed in a jar in a directory structure.

How do I check OS with a preprocessor directive?

In most cases it is better to check whether a given functionality is present or not. For example: if the function pipe() exists or not.

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

How to run a makefile in Windows?

If you have Visual Studio, run the Visual Studio Command prompt from the Start menu, change to the directory containing Makefile.win and type this:

nmake -f Makefile.win

You can also use the normal command prompt and run vsvars32.bat (c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools for VS2008). This will set up the environment to run nmake and find the compiler tools.

spring data jpa @query and pageable

I had the same issue - without Pageable method works fine.
When added as method parameter - doesn't work.

After playing with DB console and native query support came up to decision that method works like it should. However, only for upper case letters.
Logic of my application was that all names of entity starts from upper case letters.

Playing a little bit with it. And discover that IgnoreCase at method name do the "magic" and here is working solution:

public interface EmployeeRepository 
                            extends PagingAndSortingRepository<Employee, Integer> {

    Page<Employee> findAllByNameIgnoreCaseStartsWith(String name, Pageable pageable);

}

Where entity looks like:

@Data
@Entity
@Table(name = "tblEmployees")
public class Employee {

    @Id
    @Column(name = "empID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotEmpty
    @Size(min = 2, max = 20)
    @Column(name = "empName", length = 25)
    private String name;

    @Column(name = "empActive")
    private Boolean active;

    @ManyToOne
    @JoinColumn(name = "emp_dpID")
    private Department department;
}

Getting unix timestamp from Date()

getTime() retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

How do I use a PriorityQueue?

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

Adding multiple columns AFTER a specific column in MySQL

Alternatively:

ALTER TABLE users
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `lastname`,
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`;

Will put them in the order you want while streamlining the AFTER statement.

git-diff to ignore ^M

Also see:

core.whitespace = cr-at-eol

or equivalently,

[core]
    whitespace = cr-at-eol

where whitespace is preceded by a tab character.

Enzyme - How to access and set <input> value?

I am using create-react-app which comes with jest by default and enzyme 2.7.0.

This worked for me:

const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
input.node.value = 'Change';
input.simulate('change', input);
done();

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

The ~30th answer :-)

In VS2015:

  • Right-click on Solution
  • Select Project Build Order
  • Look at the list of projects in Project Build Order
  • Build each of your projects in that order
  • Inspect the Output

In my case, doing it step-by-step helped discovered what my problem is without all those errors thrown left and right.

If you had to know, I added Entity Framework (EF) 6.1.3 via NuGet when the project was set for .NET 4.5.2. I later downgraded the .NET Framework down to 4, and then the error was more obvious. Via NuGet, I uninstalled EF and re-added it.

How to get all files under a specific directory in MATLAB?

I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.

I hope it is clear enough and someone will finds it beneficial.

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {dirData.name}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
    end
  end
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles
  end

end

Example for running the code:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

How to differ sessions in browser-tabs?

I see many implementations which have client side changes to manipulate session id cookies. But in general session id cookies should be HttpOnly so java-script cannot access otherwise it may lead to Session Hijack thru XSS

super() in Java

Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)

There is also a super keyword, that you can use in methods to invoke a method of the superclass

A quick google for "Java super" results in this

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

Call Python script from bash with argument

Embedded option:

Wrap python code in a bash function.

#!/bin/bash

function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}

# Call it
current_datetime

# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT

Use environment variables, to pass data into to your embedded python script.

#!/bin/bash

function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}

# Do it one way
line 80

# Do it another way
echo $(line 80)

http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html

jQuery replace one class with another

Sometimes when you have multiple classes and you really need to overwrite all of them, it's easiest to use jQuery's .attr() to overwrite the class attribute:

$('#myElement').attr('class', 'new-class1 new-class2 new-class3');

Count Vowels in String Python

string1='I love my India'

vowel='aeiou'

for i in vowel:
  print i + "->" + str(string1.count(i))

How to pass parameters to a Script tag?

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

Custom Date/Time formatting in SQL Server

in MS SQL Server you can do:

SET DATEFORMAT ymd

year, month, day,

Undoing a git rebase

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

git rebase -i HEAD~31

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

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

Use jQuery to get the file input's selected filename without the path

maybe some addition for avoid fakepath:

var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path 
alert('clean file name : '+ fileName);

Embedding Base64 Images

Can I use (http://caniuse.com/#feat=datauri) shows support across the major browsers with few issues on IE.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Print in new line, java

\n creates a new line in Java. Don't use spaces before or after \n.

Example: printing It creates\na new line outputs

It creates
a new line.

Determine the type of an object?

You can use type() or isinstance().

>>> type([]) is list
True

Be warned that you can clobber list or any other type by assigning a variable in the current scope of the same name.

>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'

Above we see that dict gets reassigned to a string, therefore the test:

type({}) is dict

...fails.

To get around this and use type() more cautiously:

>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

Ant task to run an Ant target only if a file exists?

This might make a little more sense from a coding perspective (available with ant-contrib: http://ant-contrib.sourceforge.net/):

<target name="someTarget">
    <if>
        <available file="abc.txt"/>
        <then>
            ...
        </then>
        <else>
            ...
        </else>
    </if>
</target>

How to find if an array contains a specific string in JavaScript/jQuery?

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_


Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern Javascript is Array.prototype.includes:

var found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_

What's the quickest way to multiply multiple cells by another number?

Put the number you want to multiply by in a cell that is not in your range. Select the cell and "Copy" it to the clipboard. Next, select the Range A1:D5, and from the menu choose Edit|Paste Special. A dialog box will appear. In the "Operation" area, select "Multiply" and click "OK".

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

How to reload .bash_profile from the command line?

. ~/.bash_profile

Just make sure you don't have any dependencies on the current state in there.

Turn Pandas Multi-Index into column

The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).

All you have to do add .reset_index(inplace=True) after the name of the DataFrame:

df.reset_index(inplace=True)  

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

How to add new contacts in android

These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

It's up to the user to save the newly created contact.

You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

contactIntent
        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

startActivityForResult() gives you the opportunity to see the result.

I've noticed the resultCode works on >5.0 devices,

but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

Which I understand is the default return if an activity doesn't expect to return anything.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
    {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
        }
    }
}

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

SQL Server - stop or break execution of a SQL script

I would suggest that you wrap your appropriate code block in a try catch block. You can then use the Raiserror event with a severity of 11 in order to break to the catch block if you wish. If you just want to raiserrors but continue execution within the try block then use a lower severity.

Make sense?

Cheers, John

[Edited to include BOL Reference]

http://msdn.microsoft.com/en-us/library/ms175976(SQL.90).aspx

Creating a simple configuration file and parser in C++

I was searching for a similar simple C++ config file parser and this tutorial website provided me with a basic yet working solution. Its quick and dirty soultion to get the job done.

myConfig.txt

gamma=2.8
mode  =  1
path = D:\Photoshop\Projects\Workspace\Images\

The following program reads the previous configuration file:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>

int main()
{
    double gamma = 0;
    int mode = 0;
    std::string path;

    // std::ifstream is RAII, i.e. no need to call close
    std::ifstream cFile("myConfig.txt");
    if (cFile.is_open())
    {
        std::string line;
        while (getline(cFile, line)) 
        {
            line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
            if (line[0] == '#' || line.empty()) continue;

            auto delimiterPos = line.find("=");
            auto name = line.substr(0, delimiterPos);
            auto value = line.substr(delimiterPos + 1);

            //Custom coding
            if (name == "gamma") gamma = std::stod(value);
            else if (name == "mode") mode = std::stoi(value);
            else if (name == "path") path = value;
        }
    }
    else 
    {
        std::cerr << "Couldn't open config file for reading.\n";
    }

    std::cout << "\nGamma=" << gamma;
    std::cout << "\nMode=" << mode;
    std::cout << "\nPath=" << path;
    std::getchar();
}

Cannot set some HTTP headers when using System.Net.WebRequest

I had the same exception when my code tried to set the "Accept" header value like this:

WebRequest request = WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Headers.Add("Accept", "application/json");

The solution was to change it to this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Accept = "application/json";

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

'React' must be in scope when using JSX react/react-in-jsx-scope?

Follow as in picture for removing that lint error and adding automatic fix by addin g--fix in package.json

enter image description here

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How do I profile memory usage in Python?

Below is a simple function decorator which allows to track how much memory the process consumed before the function call, after the function call, and what is the difference:

import time
import os
import psutil
 
 
def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
 
 
def get_process_memory():
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    return mem_info.rss
 
 
def profile(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

Here is my blog which describes all the details. (archived link)

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

Display a view from another controller in ASP.NET MVC

You can use:

return View("../Category/NotFound", model);

It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.

curl -GET and -X GET

By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com it will use GET. If you use -d or -F curl will use POST, -I will cause a HEAD and -T will make it a PUT.

If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]. This way you can for example send a DELETE by doing curl -X DELETE [URL].

It is thus pointless to do curl -X GET [URL] as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]... But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL].

Digging deeper

curl -GET (using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G, -E and -T options and that will do something completely different.

There's also a curl option called --get to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d into a GET request instead of a POST.

(I subsequently used my own answer here to populate the curl FAQ to cover this.)

Warnings

Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v) - to make users aware. Further explained and motivated in this blog post.

-G converts a POST + body to a GET + query

You can ask curl to convert a set of -d options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:

curl -d name=daniel -d grumpy=yes -G https://example.com/

How to get the current URL within a Django template?

Django 1.9 and above:

## template
{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

Old:

## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

## views.py
from django.template import *

def home(request):
    return render_to_response('home.html', {}, context_instance=RequestContext(request))

## template
{{ request.path }}

Angular/RxJs When should I unsubscribe from `Subscription`

I like the last two answers, but I experienced an issue if the the subclass referenced "this" in ngOnDestroy.

I modified it to be this, and it looks like it resolved that issue.

export abstract class BaseComponent implements OnDestroy {
    protected componentDestroyed$: Subject<boolean>;
    constructor() {
        this.componentDestroyed$ = new Subject<boolean>();
        let f = this.ngOnDestroy;
        this.ngOnDestroy = function()  {
            // without this I was getting an error if the subclass had
            // this.blah() in ngOnDestroy
            f.bind(this)();
            this.componentDestroyed$.next(true);
            this.componentDestroyed$.complete();
        };
    }
    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

How to represent a fix number of repeats in regular expression?

For Java:

Quantifiers documentation

X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}

What does --net=host option in Docker command really do?

The --net=host option is used to make the programs inside the Docker container look like they are running on the host itself, from the perspective of the network. It allows the container greater network access than it can normally get.

Normally you have to forward ports from the host machine into a container, but when the containers share the host's network, any network activity happens directly on the host machine - just as it would if the program was running locally on the host instead of inside a container.

While this does mean you no longer have to expose ports and map them to container ports, it means you have to edit your Dockerfiles to adjust the ports each container listens on, to avoid conflicts as you can't have two containers operating on the same host port. However, the real reason for this option is for running apps that need network access that is difficult to forward through to a container at the port level.

For example, if you want to run a DHCP server then you need to be able to listen to broadcast traffic on the network, and extract the MAC address from the packet. This information is lost during the port forwarding process, so the only way to run a DHCP server inside Docker is to run the container as --net=host.

Generally speaking, --net=host is only needed when you are running programs with very specific, unusual network needs.

Lastly, from a security perspective, Docker containers can listen on many ports, even though they only advertise (expose) a single port. Normally this is fine as you only forward the single expected port, however if you use --net=host then you'll get all the container's ports listening on the host, even those that aren't listed in the Dockerfile. This means you will need to check the container closely (especially if it's not yours, e.g. an official one provided by a software project) to make sure you don't inadvertently expose extra services on the machine.

How to post object and List using postman

{
    "preOrderData" : [
        {
            "pname": "xyz",
            "quantity": "1",
            "unit": "Peice",
            "description": "xyz 100 gram",
            "preferred_brand": "xyz",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        },
        {
            "productname": "abc cream",
            "quantity": "1",
            "unit": "Peice",
            "description": "abc 100 gram",
            "preferred_brand": "abccream",
            "entry_date": "2020-10-05 11:11:27",
            "creation_date": "2020-10-05 11:11:27",
            "updated_date": "2020-10-05 11:11:27",
            "user": "[email protected]",
            "user_type": "individual"
        }
    ]
}

In Git, how do I figure out what my current revision is?

What do you mean by "version number"? It is quite common to tag a commit with a version number and then use

$ git describe --tags

to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:

$ git rev-parse HEAD

or for the short revision hash:

$ git rev-parse --short HEAD

It is often sufficient to do:

$ cat .git/refs/heads/${branch-master}

but this is not reliable as the ref may be packed.

Best way to combine two or more byte arrays in C#

    public static byte[] Concat(params byte[][] arrays) {
        using (var mem = new MemoryStream(arrays.Sum(a => a.Length))) {
            foreach (var array in arrays) {
                mem.Write(array, 0, array.Length);
            }
            return mem.ToArray();
        }
    }

how to get the value of a textarea in jquery?

You can directly use

var message = $.trim($("#message").val());

Read more @ Get the Value of TextArea using the jQuery Val () Method

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Rotate axis text in python matplotlib

My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

Can two or more people edit an Excel document at the same time?

No, sadly:

The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps

From Co-authoring overview (SharePoint Server 2010)

...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.

What is sys.maxint in Python 3?

As pointed out by others, Python 3's int does not have a maximum size, but if you just need something that's guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float("inf").

How to link to apps on the app store

This worked for me perfectly using only APP ID:

 NSString *urlString = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@",YOUR_APP_ID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

The number of redirects is ZERO.

How do I compile and run a program in Java on my Mac?

Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -

Create a file name "run", in directory where your Java files are. And save this in your file -

javac "$1.java"
if [ $? -eq 0 ]; then
  echo "--------Run output-------"
  java "$1"
fi

give this file run permission by running -

chmod 777 

Now you can run any of your files by merely running -

./run <yourfilename> (don't add .java in filename)

How to urlencode a querystring in Python?

You need to pass your parameters into urlencode() as either a mapping (dict), or a sequence of 2-tuples, like:

>>> import urllib
>>> f = { 'eventName' : 'myEvent', 'eventDescription' : 'cool event'}
>>> urllib.urlencode(f)
'eventName=myEvent&eventDescription=cool+event'

Python 3 or above

Use:

>>> urllib.parse.urlencode(f)
eventName=myEvent&eventDescription=cool+event

Note that this does not do url encoding in the commonly used sense (look at the output). For that use urllib.parse.quote_plus.

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

no module named urllib.parse (How should I install it?)

pip install -U websocket 

I just use this to fix my problem

Calling a phone number in swift

Just try:

if let url = NSURL(string: "tel://\(busPhone)") where UIApplication.sharedApplication().canOpenURL(url) {
  UIApplication.sharedApplication().openURL(url)
}

assuming that the phone number is in busPhone.

NSURL's init(string:) returns an Optional, so by using if let we make sure that url is a NSURL (and not a NSURL? as returned by the init).


For Swift 3:

if let url = URL(string: "tel://\(busPhone)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}

We need to check whether we're on iOS 10 or later because:

'openURL' was deprecated in iOS 10.0