Programs & Examples On #Log4postsharp

Log4postsharp is a satellite project for PostSharp, the AOP framework.

Git ignore file for Xcode projects

gitignore.io: Create useful .gitignore files for your project

  • Example (macOS Objective-C Swift SwiftPackageManager Carthage)
  • Steps to use in Terminal (Refer to the YouTube Video)
    1. Create Git global config alias (One time only)

      git config --global alias.ignore '!gi() { curl -L -s https://www.gitignore.io/api/$@ ;}; gi'
      
    2. Enter the project directory

      cd <the project directory>
      
    3. Generate .gitignore file

      git ignore macOS,Objective-C,Swift,SwiftPackageManager,Carthage >.gitignore
      
    4. Add and commit .gitignore file

      git add .gitignore
      git commit -m "Add .gitignore file"
      

Create an empty data.frame

If you already have an existent data frame, let's say df that has the columns you want, then you can just create an empty data frame by removing all the rows:

empty_df = df[FALSE,]

Notice that df still contains the data, but empty_df doesn't.

I found this question looking for how to create a new instance with empty rows, so I think it might be helpful for some people.

You can't specify target table for update in FROM clause

Make a temporary table (tempP) from a subquery

UPDATE pers P 
SET P.gehalt = P.gehalt * 1.05 
WHERE P.persID IN (
    SELECT tempP.tempId
    FROM (
        SELECT persID as tempId
        FROM pers P
        WHERE
            P.chefID IS NOT NULL OR gehalt < 
                (SELECT (
                    SELECT MAX(gehalt * 1.05) 
                    FROM pers MA 
                    WHERE MA.chefID = MA.chefID) 
                    AS _pers
                )
    ) AS tempP
)

I've introduced a separate name (alias) and give a new name to 'persID' column for temporary table

Clone an image in cv2 python

You can simply use Python standard library. Make a shallow copy of the original image as follows:

import copy

original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

How to delete empty folders using windows command prompt?

Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

credit goes to the posting author

Store output of subprocess.Popen call in a string

The accepted answer is still good, just a few remarks on newer features. Since python 3.6, you can handle encoding directly in check_output, see documentation. This returns a string object now:

import subprocess 
out = subprocess.check_output(["ls", "-l"], encoding="utf-8")

In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :

import subprocess 
p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
p2.stdout

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

JavaScript/jQuery - "$ is not defined- $function()" error

Im using Asp.Net Core 2.2 with MVC and Razor cshtml My JQuery is referenced in a layout page I needed to add the following to my view.cshtml:

@section Scripts {
$script-here
}

Unable to connect with remote debugger

My case is that when I tap enable remote JS debugging, it will launch chrome, but can not connect to it.

I have tried to run:

adb reverse tcp:8081 tcp:8081 

, did but not work.

I uninstalled my chrome totally and install a new one. And it works.

Generate a Hash from string in Javascript

This is a refined and better performing variant:

String.prototype.hashCode = function() {
    var hash = 0, i = 0, len = this.length;
    while ( i < len ) {
        hash  = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
    }
    return hash;
};

This matches Java's implementation of the standard object.hashCode()

Here is also one that returns only positive hashcodes:

String.prototype.hashcode = function() {
    return (this.hashCode() + 2147483647) + 1;
};

And here is a matching one for Java that only returns positive hashcodes:

public static long hashcode(Object obj) {
    return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}

Enjoy!

Without prototype:

function hashCode(str) {
    var hash = 0, i = 0, len = str.length;
    while ( i < len ) {
        hash  = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
    }
    return hash;
}

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

Codeigniter unset session

Instead of use set_userdata you should use set_flashdata.

According to CI user guide:

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").

http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

Removing element from array in component state

You could make the code more readable with a one line helper function:

const removeElement = (arr, i) => [...arr.slice(0, i), ...arr.slice(i+1)];

then use it like so:

this.setState(state => ({ places: removeElement(state.places, index) }));

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected):

https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7

For general guidance on setting up a script in Google Sheets, see this quickstart guide.

To use this script:

  1. In your Google Sheet, set up data validation for a cell (or cells), using data from a range. In cell validation, do not select 'Reject input'.
  2. Go to Tools > Script editor...
  3. In the script editor, go to File > New > Script file
  4. Name the file multi-select.gs and paste in the contents of multi-select.gs. File > Save.
  5. In the script editor, go to File > New > Html file Name the file dialog.html and paste in the contents of dialog.html. File > Save.
  6. Back in your spreadsheet, you should now have a new menu called 'Scripts'. Refresh the page if necessary.
  7. Select the cell you want to fill with multiple items from your validation range.
  8. Go to Scripts > Multi-select for this cell... and the sidebar should open, showing a checklist of valid items.
  9. Tick the items you want and click the 'Set' button to fill your cell with those selected items, comma separated.

You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist.

The above mentioned steps are taken from this link

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

Variables as commands in bash scripts

Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.

It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.

With perl, as my example, I'd be able to do something like:

@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );

The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)

How do I convert a C# List<string[]> to a Javascript array?

Here's how you accomplish that:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>

Code line wrapping - how to handle long lines

I think that moving last operator to the beginning of the next line is a good practice. That way you know right away the purpose of the second line, even it doesn't start with an operator. I also recommend 2 indentation spaces (2 tabs) for a previously broken tab, to differ it from the normal indentation. That is immediately visible as continuing previous line. Therefore I suggest this:

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper 
            = new HashMap<Class<? extends Persistent>, PersistentHelper>();

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

how to delete the content of text file without deleting itself

All you have to do is open file in truncate mode. Any Java file out class will automatically do that for you.

calling another method from the main method in java

You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

public static void main(String[] args){
  new Foo().doSomething();
}

public void doSomething(){}

Alternatively, make doSomething() static as well, if that works for your design.

Check if a value exists in ArrayList

Better to use a HashSet than an ArrayList when you are checking for existence of a value. Java docs for HashSet says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"

ArrayList.contains() might have to iterate the whole list to find the instance you are looking for.

use current date as default value for a column

CREATE TABLE Orders(
    O_Id int NOT NULL,
    OrderNo int NOT NULL,
    P_Id int,
    OrderDate date DEFAULT GETDATE() // you can set default constraints while creating the table
)

XML Parser for C

For C++ I suggest using CMarkup.

Insert/Update/Delete with function in SQL Server

  CREATE FUNCTION dbo.UdfGetProductsScrapStatus
(
@ScrapComLevel INT
) 
RETURNS @ResultTable TABLE
( 
ProductName VARCHAR(50), ScrapQty FLOAT, ScrapReasonDef VARCHAR(100), ScrapStatus VARCHAR(50)
) AS BEGIN
        INSERT INTO @ResultTable
            SELECT PR.Name, SUM([ScrappedQty]), SC.Name, NULL
                FROM [Production].[WorkOrder] AS WO
                        INNER JOIN 
                        Production.Product AS PR
                        ON Pr.ProductID = WO.ProductID
                        INNER JOIN Production.ScrapReason AS SC
                        ON SC.ScrapReasonID = WO.ScrapReasonID
                WHERE WO.ScrapReasonID IS NOT NULL
                GROUP BY PR.Name, SC.Name
UPDATE @ResultTable
            SET ScrapStatus = 
            CASE WHEN ScrapQty > @ScrapComLevel THEN 'Critical'
            ELSE 'Normal'
            END
        
RETURN
END

Swift - How to convert String to Double

Swift 4.2+ String to Double

You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.

Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).

let lessPrecisePI = Float("3.14")

let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number

Unwrap the values to use them using if/let

if let cost = Double(textField.text!) {
    print("The user entered a value price of \(cost)")
} else {
    print("Not a valid number: \(textField.text!)")
}

You can convert formatted numbers and currency using the NumberFormatter class.

let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")

Currency formats

let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency

formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")

formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €

formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator

formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")

Read more on my blog post about converting String to Double types (and currency).

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

Is there a way to make a DIV unselectable?

I wrote a simple jQuery extension to disable selection some time back: Disabling Selection in jQuery. You can invoke it through $('.button').disableSelection();

Alternately, using CSS (cross-browser):

.button {
        user-select: none;
        -moz-user-select: none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -o-user-select: none;
} 

Transfer data between databases with PostgreSQL

Actually, there is some possibility to send a table data from one PostgreSQL database to another. I use the procedural language plperlu (unsafe Perl procedural language) for it.

Description (all was done on a Linux server):

  1. Create plperlu language in your database A

  2. Then PostgreSQL can join some Perl modules through series of the following commands at the end of postgresql.conf for the database A:

    plperl.on_init='use DBI;'
    plperl.on_init='use DBD::Pg;'
    
  3. You build a function in A like this:

    CREATE OR REPLACE FUNCTION send_data( VARCHAR )
    RETURNS character varying AS
    $BODY$
    my $command = $_[0] || die 'No SQL command!';
    my $connection_string =
    "dbi:Pg:dbname=your_dbase;host=192.168.1.2;port=5432;";
    $dbh = DBI->connect($connection_string,'user','pass',
    {AutoCommit=>0,RaiseError=>1,PrintError=>1,pg_enable_utf8=>1,}
    );
    my $sql = $dbh-> prepare( $command );
    eval { $sql-> execute() };
    my $error = $dbh-> state;
    $sql-> finish;
    if ( $error ) { $dbh-> rollback() } else {  $dbh-> commit() }
    $dbh-> disconnect();
    $BODY$
    LANGUAGE plperlu VOLATILE;
    

And then you can call the function inside database A:

SELECT send_data( 'INSERT INTO jm (jm) VALUES (''zzzzzz'')' );

And the value "zzzzzz" will be added into table "jm" in database B.

'innerText' works in IE, but not in Firefox

A really simple line of Javascript can get the "non-taggy" text in all main browsers...

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);

How can I convert the "arguments" object to an array in JavaScript?

The Arguments object is only available inside a function body. Although you can index the Arguments Object like an array, it is not an array. It does not have any array properties other than length.

_x000D_
_x000D_
// function arguments length 5_x000D_
function properties(a,b,c,d,e){_x000D_
var function_name= arguments.callee.name_x000D_
var arguments_length= arguments.length;_x000D_
var properties_length=  properties.length; _x000D_
var function_from= properties.caller.name;_x000D_
console.log('I am the function name: '+ function_name);_x000D_
console.log('I am the function length, I am function spacific: '+ properties_length); _x000D_
console.log('I am the arguments length, I am context/excution spacific: '+ arguments_length);_x000D_
console.log('I am being called From: '+  function_from );_x000D_
}_x000D_
_x000D_
// arguments 3_x000D_
function parent(){_x000D_
properties(1,2,3);_x000D_
}_x000D_
_x000D_
//arguments length 3 because execution spacific_x000D_
parent();
_x000D_
_x000D_
_x000D_

Although it can be indexed like an array as you can see in this example:

_x000D_
_x000D_
function add(){_x000D_
_x000D_
var sum=0;_x000D_
_x000D_
for(var i=0; i< arguments.length;i++){_x000D_
_x000D_
sum = sum + arguments[i];_x000D_
_x000D_
}_x000D_
_x000D_
return sum;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(add(1,2,3));
_x000D_
_x000D_
_x000D_

However, the Arguments object is not an array and does not have any other properties other than length.

You can convert the arguments object into an array at which point you can access the Arguments object.

There are many ways you can access the arguments object inside a function body, and these include:

  1. you can call the Array.prototoype.slice.call method.

Array.prototype.slice.call(arguments)

_x000D_
_x000D_
function giveMeArgs(arg1,arg2){_x000D_
_x000D_
var args = Array.prototype.slice.call(arguments);_x000D_
return args_x000D_
}_x000D_
_x000D_
console.log( giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_

  1. you can use the array literal

[].slice.call(arguments).

_x000D_
_x000D_
function giveMeArgs(arg1,arg2){_x000D_
_x000D_
var args = [].slice.call(arguments);_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log( giveMeArgs(1,2) );
_x000D_
_x000D_
_x000D_

  1. you can use Rest ...

_x000D_
_x000D_
function giveMeArgs(...args){_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2))
_x000D_
_x000D_
_x000D_

  1. you can use spread [...]

_x000D_
_x000D_
function giveMeArgs(){_x000D_
_x000D_
var args = [...arguments];_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_

  1. you can use Array.from()

_x000D_
_x000D_
function giveMeArgs(){_x000D_
_x000D_
var args = Array.from(arguments);_x000D_
_x000D_
return args;_x000D_
_x000D_
}_x000D_
_x000D_
console.log(giveMeArgs(1,2));
_x000D_
_x000D_
_x000D_

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

How do I determine the size of my array in C?

"you've introduced a subtle way of shooting yourself in the foot"

C 'native' arrays do not store their size. It is therefore recommended to save the length of the array in a separate variable/const, and pass it whenever you pass the array, that is:

#define MY_ARRAY_LENGTH   15
int myArray[MY_ARRAY_LENGTH];

You SHOULD always avoid native arrays (unless you can't, in which case, mind your foot). If you are writing C++, use the STL's 'vector' container. "Compared to arrays, they provide almost the same performance", and they are far more useful!

// vector is a template, the <int> means it is a vector of ints
vector<int> numbers;  

// push_back() puts a new value at the end (or back) of the vector
for (int i = 0; i < 10; i++)
    numbers.push_back(i);

// Determine the size of the array
cout << numbers.size();

See: http://www.cplusplus.com/reference/stl/vector/

Basic HTTP authentication with Node and Express 4

I used the code for the original basicAuth to find the answer:

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

How to change Format of a Cell to Text using VBA

One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.

OR:

Could you try an autofit first:

Excel_Obj.Columns("A:V").EntireColumn.AutoFit

Calculate difference between 2 date / times in Oracle SQL

If You want get date defer from using table and column.

SELECT TO_DATE( TO_CHAR(COLUMN_NAME_1, 'YYYY-MM-DD'), 'YYYY-MM-DD') - 
       TO_DATE(TO_CHAR(COLUMN_NAME_2, 'YYYY-MM-DD') , 'YYYY-MM-DD')  AS DATEDIFF       
FROM TABLE_NAME;

How to copy data to clipboard in C#

For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:

  1. In Solution Explorer, expand your console project.
  2. Right-click References, then click Add Reference...
  3. In the Assemblies group, under Framework, select System.Windows.Forms.
  4. Click OK.

Then, add the following using statement in with the others at the top of your code:

using System.Windows.Forms;

Then, add either of the following Clipboard.SetText statements to your code:

Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);

And lastly, add STAThreadAttribute to your Main method as follows, to avoid a System.Threading.ThreadStateException:

[STAThreadAttribute]
static void Main(string[] args)
{
  // ...
}

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

I can see you have accepted an answer which doesn't solve your problem entirely:

android:screenOrientation="portrait" 

This will force your app to be portrait on both phones and tablets.

You can have the app forced in the device's "preferred" orientation by using

android:screenOrientation="nosensor"

This will lead to forcing your app to portrait on most phones phones and landscape on tablets. There are many phones with keypads which were designed for landscape mode. Forcing your app to portrait can make it almost unusable on such devices. Android is recently migrating to other types of devices as well. It is best to just let the device choose the preferred orientation.

How to get the mobile number of current sim card in real device?

Hi Actually this is my same question but I didn't get anything.Now I got mobile number and his email-Id from particular Android real device(Android Mobile).Now a days 90% people using what's App application on Android Mobile.And now I am getting Mobile no and email-ID Through this What's app API.Its very simple to use see this below code.

            AccountManager am = AccountManager.get(this);
            Account[] accounts = am.getAccounts();
      for (Account ac : accounts) 
       {
        acname = ac.name;

        if (acname.startsWith("91")) {
            mobile_no = acname;
        }else if(acname.endsWith("@gmail.com")||acname.endsWith("@yahoo.com")||acname.endsWith("@hotmail.com")){
            email = acname;
        }

        // Take your time to look at all available accounts
        Log.i("Accounts : ", "Accounts : " + acname);
    }

and import this API

    import android.accounts.Account;
    import android.accounts.AccountManager;

Syntax for a single-line Bash infinite while loop

If you want the while loop to stop after some condition, and your foo command returns non-zero when this condition is met then you can get the loop to break like this:

while foo; do echo 'sleeping...'; sleep 5; done;

For example, if the foo command is deleting things in batches, and it returns 1 when there is nothing left to delete.

This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1 when the condition is met and exit with 0 when it should be run again.

For example, say you have a python script batch_update.py which updates 100 rows in a database and returns 0 if there are more to update and 1 if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:

while batch_update.py; do echo 'sleeping...'; sleep 5; done;

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

Renaming files in a folder to sequential numbers

Here is what worked for me.
I Have used rename command so that if any file contains spaces in name of it then , mv command dont get confused between spaces and actual file.

Here i replaced spaces , ' ' in a file name with '_' for all jpg files
#! /bin/bash
rename 'y/ /_/' *jpg         #replacing spaces with _
let x=0;
for i in *.jpg;do
    let x=(x+1)
    mv $i $x.jpg
done

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Tensor.get_shape() from this post.

From documentation:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])

How to convert a table to a data frame

If you are using the tidyverse, you can use

as_data_frame(table(myvector))

to get a tibble (i.e. a data frame with some minor variations from the base class)

How do I concatenate two strings in Java?

You can concatenate Strings using the + operator:

String a="hello ";
String b="world.";
System.out.println(a+b);

Output:

hello world.

That's it

jQuery: Scroll down page a set increment (in pixels) on click?

You can do that using animate like in the following link:

http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery

If you want to do it using scrollTo plugin, then take a look the following:

How to scroll the window using JQuery $.scrollTo() function

Most efficient way to append arrays in C#?

If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.

How does lock work exactly?

Its simpler than you think.

According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. lock keyword actually handles Monitor class at back end.

For example:

private static readonly Object obj = new Object();

lock (obj)
{
    // critical section
}

In the above code, first the thread enters a critical section, and then it will lock obj. When another thread tries to enter, it will also try to lock obj, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj. When the first thread leaves, then another thread will lock obj and will enter the critical section.

how to configure hibernate config file for sql server

We also need to mention default schema for SQSERVER: dbo

<property name="hibernate.default_schema">dbo</property>

Tested with hibernate 4

Iterating through all the cells in Excel VBA or VSTO 2005

For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.

For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective

You'll basically need to do the following:

  • Start the Excel application.
  • Open the Excel workbook.
  • Retrieve the worksheet from the workbook by name or index.
  • Iterate through all the Cells in the worksheet which were retrieved as a range.
  • Sample (untested) code excerpt below for the last step.

    Excel.Range allCellsRng;
    string lowerRightCell = "IV65536";
    allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
    foreach (Range cell in allCellsRng)
    {
        if (null == cell.Value2 || isBlank(cell.Value2))
        {
          // Do something.
        }
        else if (isText(cell.Value2))
        {
          // Do something.
        }
        else if (isNumeric(cell.Value2))
        {
          // Do something.
        }
    }

For Excel 2007, try this MSDN reference.

How are iloc and loc different?

In my opinion, the accepted answer is confusing, since it uses a DataFrame with only missing values. I also do not like the term position-based for .iloc and instead, prefer integer location as it is much more descriptive and exactly what .iloc stands for. The key word is INTEGER - .iloc needs INTEGERS.

See my extremely detailed blog series on subset selection for more


.ix is deprecated and ambiguous and should never be used

Because .ix is deprecated we will only focus on the differences between .loc and .iloc.

Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each index. Let's take a look at a sample DataFrame:

df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
                   'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
                   'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
                   'height':[165, 70, 120, 80, 180, 172, 150],
                   'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
                   'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])

enter image description here

All the words in bold are the labels. The labels, age, color, food, height, score and state are used for the columns. The other labels, Jane, Nick, Aaron, Penelope, Dean, Christina, Cornelia are used for the index.


The primary ways to select particular rows in a DataFrame are with the .loc and .iloc indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.

.loc selects data only by labels

We will first talk about the .loc indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length of the DataFrame.

There are three different inputs you can use for .loc

  • A string
  • A list of strings
  • Slice notation using strings as the start and stop values

Selecting a single row with .loc with a string

To select a single row of data, place the index label inside of the brackets following .loc.

df.loc['Penelope']

This returns the row of data as a Series

age           4
color     white
food      Apple
height       80
score       3.3
state        AL
Name: Penelope, dtype: object

Selecting multiple rows with .loc with a list of strings

df.loc[['Cornelia', 'Jane', 'Dean']]

This returns a DataFrame with the rows in the order specified in the list:

enter image description here

Selecting multiple rows with .loc with slice notation

Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.

df.loc['Aaron':'Dean']

enter image description here

Complex slices can be taken in the same manner as Python lists.

.iloc selects data only by integer location

Let's now turn to .iloc. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.

There are three different inputs you can use for .iloc

  • An integer
  • A list of integers
  • Slice notation using integers as the start and stop values

Selecting a single row with .iloc with an integer

df.iloc[4]

This returns the 5th row (integer location 4) as a Series

age           32
color       gray
food      Cheese
height       180
score        1.8
state         AK
Name: Dean, dtype: object

Selecting multiple rows with .iloc with a list of integers

df.iloc[[2, -2]]

This returns a DataFrame of the third and second to last rows:

enter image description here

Selecting multiple rows with .iloc with slice notation

df.iloc[:5:3]

enter image description here


Simultaneous selection of rows and columns with .loc and .iloc

One excellent ability of both .loc/.iloc is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.

For example, we can select rows Jane, and Dean with just the columns height, score and state like this:

df.loc[['Jane', 'Dean'], 'height':]

enter image description here

This uses a list of labels for the rows and slice notation for the columns

We can naturally do similar operations with .iloc using only integers.

df.iloc[[1,4], 2]
Nick      Lamb
Dean    Cheese
Name: food, dtype: object

Simultaneous selection with labels and integer location

.ix was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.

For instance, if we want to select rows Nick and Cornelia along with columns 2 and 4, we could use .loc by converting the integers to labels with the following:

col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names] 

Or alternatively, convert the index labels to integers with the get_loc index method.

labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]

Boolean Selection

The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows wher age is above 30 and return just the food and score columns we can do the following:

df.loc[df['age'] > 30, ['food', 'score']] 

You can replicate this with .iloc but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:

df.iloc[(df['age'] > 30).values, [2, 4]] 

Selecting all rows

It is possible to use .loc/.iloc for just column selection. You can select all the rows by using a colon like this:

df.loc[:, 'color':'score':2]

enter image description here


The indexing operator, [], can select rows and columns too but not simultaneously.

Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.

df['food']

Jane          Steak
Nick           Lamb
Aaron         Mango
Penelope      Apple
Dean         Cheese
Christina     Melon
Cornelia      Beans
Name: food, dtype: object

Using a list selects multiple columns

df[['food', 'score']]

enter image description here

What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.

df['Penelope':'Christina'] # slice rows by label

enter image description here

df[2:6:2] # slice rows by integer location

enter image description here

The explicitness of .loc/.iloc for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.

df[3:5, 'color']
TypeError: unhashable type: 'slice'

How to use JavaScript with Selenium WebDriver Java

Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.

The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.

If you want to run JavaScript code in Java WebDriver, do this instead:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
    throw new IllegalStateException("This driver does not support JavaScript!");
}

I like to do this, also:

WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor)driver;
} // else throw...

// later on...
js.executeScript("return document.getElementById('someId');");

You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.

The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:

  1. // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");
    
  2. // draws a border around WebElement
    WebElement element = driver.findElement(By.anything("tada"));
    js.executeScript("arguments[0].style.border='3px solid red'", element);
    
  3. // changes all input elements on the page to radio buttons
    js.executeScript(
            "var inputs = document.getElementsByTagName('input');" +
            "for(var i = 0; i < inputs.length; i++) { " +
            "    inputs[i].type = 'radio';" +
            "}" );
    

How to get the Facebook user id using the access token

If you want to use Graph API to get current user ID then just send a request to:

https://graph.facebook.com/me?access_token=...

Making sure at least one checkbox is checked

You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.

Reference Link

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

How to set 00:00:00 using moment.js

Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.

Try the following code:

var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()

What does LINQ return when the results are empty

It will return an empty enumerable. It wont be null. You can sleep sound :)

Xcode 4 - "Archive" is greyed out?

see the picture. but I have to type enough chars to post the picture.:)

enter image description here

Using a scanner to accept String input and storing in a String Array

Would this work better?

import java.util.Scanner;

public class Work {

public static void main(String[] args){

    System.out.println("Please enter the following information");

    String name = "0";
    String num = "0";
    String address = "0";

    int i = 0;

    Scanner input = new Scanner(System.in);

    //The Arrays
    String [] contactName = new String [7];
    String [] contactNum = new String [7];
    String [] contactAdd = new String [7];

    //I set these as the Array titles
    contactName[0] = "Name";
    contactNum[0] = "Phone Number";
    contactAdd[0] = "Address";

    //This asks for the information and builds an Array for each
    //i -= i resets i back to 0 so the arrays are not 7,14,21+
    while (i < 6){

        i++;
        System.out.println("Enter contact name." + i);
        name = input.nextLine();
        contactName[i] = name;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact number." + i);
        num = input.nextLine();
        contactNum[i] = num;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact address." + i);
        num = input.nextLine();
        contactAdd[i] = num;
    }


    //Now lets print out the Arrays
    i -= i;
    while(i < 6){
    i++;
    System.out.print( i + " " + contactName[i] + " / " );
    }

    //These are set to print the array on one line so println will skip a line
    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
    i++;

    System.out.print( i + " " + contactNum[i] + " / " );
    }

    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
        i++;

    System.out.print( i + " " + contactAdd[i] + " / " );
    }

    System.out.println();

    System.out.println("End of program");

}

}

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

What is the command to truncate a SQL Server log file?

For SQL 2008 you can backup log to nul device:

BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10

And then use DBCC SHRINKFILE to truncate the log file.

send checkbox value in PHP form

replace:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

with:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

then replace this line of code:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"

with:

$email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

JavaScript: Create and destroy class instance through class method

No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.

Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I think it simple to change your Apache server port

  1. Go to C:\xampplite\apache\conf
  2. Open httpd.conf files
  3. Search for Listen 80
  4. Change 80 to any other like 9080
  5. Now XAMPP restart try to start server

NB I am using Server version: 5.1.41 with windows 10

Loop through Map in Groovy?

When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value

How do I print out the value of this boolean? (Java)

There are a couple of ways to address your problem, however this is probably the most straightforward:

Your main method is static, so it does not have access to instance members (isLeapYear field and isLeapYear method. One approach to rectify this is to make both the field and the method static as well:

static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
  /* (snip) */
}

Lastly, you're not actually calling your isLeapYear method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();:

isLeapYear(year);

That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.

How to append new data onto a new line

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

SQL multiple columns in IN clause

It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

However, if you want to code the names directly into your query, here is a cleaner way to do it:

with names (fname,lname) as (
    values
        ('John','Smith'),
        ('Mary','Jones')
)
select city from user
    inner join names on
        fname=firstName and
        lname=lastName;

The advantage of this is that it separates your data out of the query somewhat.

(This is DB2 syntax; it may need a bit of tweaking on your system).

Register .NET Framework 4.5 in IIS 7.5

You can find the aspnet_regiis in the following directory:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Go to the directory and run the command form there. I guess the path is missing in your PATH variable.

What are best practices for multi-language database design?

I recommend the answer posted by Martin.

But you seem to be concerned about your queries getting too complex:

To create localized table for every table is making design and querying complex...

So you might be thinking, that instead of writing simple queries like this:

SELECT price, name, description FROM Products WHERE price < 100

...you would need to start writing queries like that:

SELECT
  p.price, pt.name, pt.description
FROM
  Products p JOIN ProductTranslations pt
  ON (p.id = pt.id AND pt.lang = "en")
WHERE
  price < 100

Not a very pretty perspective.

But instead of doing it manually you should develop your own database access class, that pre-parses the SQL that contains your special localization markup and converts it to the actual SQL you will need to send to the database.

Using that system might look something like this:

db.setLocale("en");
db.query("SELECT p.price, _(p.name), _(p.description)
          FROM _(Products p) WHERE price < 100");

And I'm sure you can do even better that that.

The key is to have your tables and fields named in uniform way.

Oracle timestamp data type

Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:

SQL> create table t23
  2  (ts0 timestamp(0)
  3   , ts3 timestamp(3)
  4  , ts6 timestamp(6)
  5  )
  6  /

Table created.

SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
  2  /

1 row created.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM


SQL> 

If we don't specify a precision then the timestamp defaults to six places.

SQL> alter table t23 add ts_def timestamp;

Table altered.

SQL> update t23      
  2  set ts_def = systimestamp
  3  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM


SQL> 

Note that I'm running on Linux so my TIMESTAMP column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).

As might be expected, the documentation covers this. Find out more.


"when you create timestamp(9) this gives you nanos right"

Only if the OS supports it. As you can see, my OEL appliance does not:

SQL> alter table t23 add ts_nano timestamp(9)
  2  /

Table altered.

SQL> update t23 set ts_nano = systimestamp(9)
  2  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM


SQL> 

(Those trailing zeroes could be a coincidence but they aren't.)

Return HTTP status code 201 in flask

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:

return {"data": {"username": "test","id":"fdsf345"}}, 201

Note the postfixed number is the status code returned.

Alternatively, you may want to send a message to the client such as:

return {"msg": "Created Successfully"}, 201

IntelliJ cannot find any declarations

Ensure that the directory which contains your compiled classes and libraries is marked as sources Root.

How to create full path with node's fs.mkdirSync?

You can simply check folder exist or not in path recursively and make the folder as you check if they are not present. (NO EXTERNAL LIBRARY)

function checkAndCreateDestinationPath (fileDestination) {
    const dirPath = fileDestination.split('/');
    dirPath.forEach((element, index) => {
        if(!fs.existsSync(dirPath.slice(0, index + 1).join('/'))){
            fs.mkdirSync(dirPath.slice(0, index + 1).join('/')); 
        }
    });
}

How to horizontally center a floating element of a variable width?

Can't you just use display: inline block and align to center?

Example.

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

Angularjs: Get element in controller

I dont know what do you exactly mean but hope it help you.
by this directive you can access the DOM element inside controller
this is sample that help you to focus element inside controller

.directive('scopeElement', function () {
    return {
        restrict:"A", // E-Element A-Attribute C-Class M-Comments
        replace: false,
        link: function($scope, elem, attrs) {
            $scope[attrs.scopeElement] = elem[0];
        }
    };
})

now, inside HTML

<input scope-element="txtMessage" >

then, inside controller :

.controller('messageController', ['$scope', function ($scope) {
    $scope.txtMessage.focus();
}])

sweet-alert display HTML code in text

All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true ,

    var hh = "<b>test</b>"; 
swal({
        title: "" + txt + "", 
        text: "Testno  sporocilo za objekt " + hh + "",  
        html: true,  
        confirmButtonText: "V redu", 
        allowOutsideClick: "true"  
});

Note: html : "Testno sporocilo za objekt " + hh + "",
may not work as html porperty is only use to active this feature by assign true / false value in the Sweetalert.
this html : "Testno sporocilo za objekt " + hh + "", is used in SweetAlert2

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

"SSL certificate verify failed" using pip to install packages

 pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org <app>

What is ToString("N0") format?

You can find the list of formats here (in the Double.ToString()-MSDN-Article) as comments in the example section.

Convert Enum to String

In my tests, Enum.GetName was faster and by decent margin. Internally ToString calls Enum.GetName. From source for .NET 4.0, the essentials:

public override String ToString()
{
     return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
}

private static String InternalFormat(RuntimeType eT, Object value)
{
    if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
    {
        String retval = GetName(eT, value); //<== the one
        if (retval == null)
            return value.ToString();
        else
            return retval;
    }
    else
    {
        return InternalFlagsFormat(eT, value);
    }
}

I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.

Test setup: enum with 8 values, no. of iterations = 1000000

Result: Enum.GetName => 700 ms, ToString => 2000 ms

If speed isn't noticeable, I wouldn't care and use ToString since it offers a much cleaner call. Contrast

Enum.GetName(typeof(Bla), value)

with

value.ToString()

How to configure Docker port mapping to use Nginx as an upstream proxy?

@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.

If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:

Link Your Containers

When you docker run your containers, typically by inputting a shell script into User Data, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:

#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx

So in this example, the API container isn't linked to any others, but the App container is linked to API and Nginx is linked to both API and App.

The result of this is changes to the env vars and the /etc/hosts files that reside within the API and App containers. The results look like so:

/etc/hosts

Running cat /etc/hosts within your Nginx container will produce the following:

172.17.0.5  0fd9a40ab5ec
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3  App
172.17.0.2  API



ENV Vars

Running env within your Nginx container will produce the following:

API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2

APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3

I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.

To obtain a shell to run the above commands within a running container, use the following:

sudo docker exec -i -t Nginx bash

You can see that you now have both /etc/hosts file entries and env vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx within your Nginx container.



Configuring Nginx

This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts file that docker created, or you can utilize the ENV vars and run a string replacement (I used sed) on your nginx.conf and any other conf files that may be in your /etc/nginx/sites-enabled folder to insert the IP values.



OPTION A: Configure Nginx Using ENV Vars

This is the option that I went with because I couldn't get the /etc/hosts file option to work. I'll be trying Option B soon enough and update this post with any findings.

The key difference between this option and using the /etc/hosts file option is how you write your Dockerfile to use a shell script as the CMD argument, which in turn handles the string replacement to copy the IP values from ENV to your conf file(s).

Here's the set of configuration files I ended up with:

Dockerfile

FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>

RUN apt-get update && apt-get install -y nano htop git nginx

ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh

EXPOSE 80 443

CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]

nginx.conf

daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;


events {
    worker_connections 1024;
}


http {

    # Basic Settings

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 33;
    types_hash_max_size 2048;

    server_tokens off;
    server_names_hash_bucket_size 64;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;


    # Logging Settings
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    # Gzip Settings

gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 3;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/xml text/css application/x-javascript application/json;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    # Virtual Host Configs  
    include /etc/nginx/sites-enabled/*;

    # Error Page Config
    #error_page 403 404 500 502 /srv/Splash;


}

NOTE: It's important to include daemon off; in your nginx.conf file to ensure that your container doesn't exit immediately after launching.

api.myapp.conf

upstream api_upstream{
    server APP_IP:3000;
}

server {
    listen 80;
    server_name api.myapp.com;
    return 301 https://api.myapp.com/$request_uri;
}

server {
    listen 443;
    server_name api.myapp.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }

}

Nginx-Startup.sh

#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com

service nginx start

I'll leave it up to you to do your homework about most of the contents of nginx.conf and api.myapp.conf.

The magic happens in Nginx-Startup.sh where we use sed to do string replacement on the APP_IP placeholder that we've written into the upstream block of our api.myapp.conf and app.myapp.conf files.

This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands

GOTCHA On OSX, sed handles options differently, the -i flag specifically. On Ubuntu, the -i flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the -i flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i flag.

GOTCHA To use ENV vars within the regex that sed uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.

So docker has launched our container and triggered the Nginx-Startup.sh script to run, which has used sed to change the value APP_IP to the corresponding ENV variable we provided in the sed command. We now have conf files within our /etc/nginx/sites-enabled directory that have the IP addresses from the ENV vars that docker set when starting up the container. Within your api.myapp.conf file you'll see the upstream block has changed to this:

upstream api_upstream{
    server 172.0.0.2:3000;
}

The IP address you see may be different, but I've noticed that it's usually 172.0.0.x.

You should now have everything routing appropriately.

GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx will have already set the first IP into its conf files, or in its /etc/hosts file, so it won't be able to determine the new IP for api.myapp.com. The solution to this is likely to use CoreOS and its etcd service which, in my limited understanding, acts like a shared ENV for all machines registered into the same CoreOS cluster. This is the next toy I'm going to play with setting up.



OPTION B: Use /etc/hosts File Entries

This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts entry into your api.myapp.conf and app.myapp.conf files, but I couldn't get this method to work.

UPDATE: See @Wes Tod's answer for instructions on how to make this method work.

Here's the attempt that I made in api.myapp.conf:

upstream api_upstream{
    server API:3000;
}

Considering that there's an entry in my /etc/hosts file like so: 172.0.0.2 API I figured it would just pull in the value, but it doesn't seem to be.

I also had a couple of ancillary issues with my Elastic Load Balancer sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

You can use org.modeshape.common.text.Inflector.

Specifically:

String camelCase(String lowerCaseAndUnderscoredWord,
    boolean uppercaseFirstLetter, char... delimiterChars) 

By default, this method converts strings to UpperCamelCase.

Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final

on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases

Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

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

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

Here is code to set default radio button set to true

@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = "checked", id = "rdGender", name = "rbGender" })

Check if application is installed - Android

If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify

val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")

and the call the following method to check if the app is installed

fun isInstalled(intent:Intent) :Boolean{
    val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return list.isNotEmpty()
}

Python MySQLdb TypeError: not all arguments converted during string formatting

cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )

I do not why, but this works for me . rather than use '%s'.

Create a unique number with javascript time

A better approach would be:

new Date().valueOf();

instead of

new Date().getUTCMilliseconds();

valueOf() is "most likely" a unique number. http://www.w3schools.com/jsref/jsref_valueof_date.asp.

Service Reference Error: Failed to generate code for the service reference

Restarting Visual Studio did the trick for me. I am using VS 2015.

How to host google web fonts on my own server?

As you want to host all fonts (or some of them) at your own server, you a download fonts from this repo and use it the way you want: https://github.com/praisedpk/Local-Google-Fonts

If you just want to do this to fix the leverage browser caching issue that comes with Google Fonts, you can use alternative fonts CDN, and include fonts as:

<link href="https://pagecdn.io/lib/easyfonts/fonts.css" rel="stylesheet" />

Or a specific font, as:

<link href="https://pagecdn.io/lib/easyfonts/lato.css" rel="stylesheet" />

Create a one to many relationship using SQL Server

  1. Define two tables (example A and B), with their own primary key
  2. Define a column in Table A as having a Foreign key relationship based on the primary key of Table B

This means that Table A can have one or more records relating to a single record in Table B.

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 
  • fk_b: Name of the foreign key constraint, must be unique to the database
  • b_id: Name of column in Table A you are creating the foreign key relationship on
  • b: Name of table, in this case b
  • id: Name of column in Table B

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Removing Java 8 JDK from Mac

Use /usr/libexec/java_home ; I found these alias and function to be pretty useful in my ~/.profile:

alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    java -version
}

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

Authorize attribute in ASP.NET MVC

It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.

BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.

How can I set multiple CSS styles in JavaScript?

Use CSSStyleDeclaration.setProperty() method inside the Object.entries of styles object.
We can also set the priority ("important") for CSS property with this.
We will use "hypen-case" CSS property names.

_x000D_
_x000D_
const styles = {_x000D_
  "font-size": "18px",_x000D_
  "font-weight": "bold",_x000D_
  "background-color": "lightgrey",_x000D_
  color: "red",_x000D_
  "padding": "10px !important",_x000D_
  margin: "20px",_x000D_
  width: "100px !important",_x000D_
  border: "1px solid blue"_x000D_
};_x000D_
_x000D_
const elem = document.getElementById("my_div");_x000D_
_x000D_
Object.entries(styles).forEach(([prop, val]) => {_x000D_
  const [value, pri = ""] = val.split("!");_x000D_
  elem.style.setProperty(prop, value, pri);_x000D_
});
_x000D_
<div id="my_div"> Hello </div>
_x000D_
_x000D_
_x000D_

Expanding a parent <div> to the height of its children

For those who can not figure out this in instructions from this answer there:

Try to set padding value more then 0, if child divs have margin-top or margin-bottom you can replace it with padding

For example if you have

#childRightCol
{
    margin-top: 30px;
}
#childLeftCol
{
    margin-bottom: 20px;
}

it'll be better to replace it with:

#parent
{
    padding: 30px 0px 20px 0px;
}

Text on image mouseover?

This is using the :hover pseudoelement in CSS3.

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

#wrapper:hover .text {
visibility:visible;
}

?Demo HERE.


This instead is a way of achieving the same result by using jquery:

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

jquery code:

$('.hover').mouseover(function() {
  $('.text').css("visibility","visible");
});

$('.hover').mouseout(function() {
  $('.text').css("visibility","hidden");
});

You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

You can see the demo HERE.

When you want to use it on your website, just change the <img src /> value and you can add multiple images and captions, just copy the format i used: insert image with class="hover" and p with class="text"

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If it's a PHP issue, you could simply alter the configuration file php.ini wherever it's located and update the settings for PORT/SOCKET-PATH etc to make it connect to the server.

In my case, I opened the file php.ini and did

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock

And it worked straight away. I have to admit, I took hint from the accepted answer by @Joni

Creating an index on a table variable

If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.

 CREATE TABLE #Table(C1 int,       
  C2 NVarchar(100) , C3 varchar(100)
  UNIQUE CLUSTERED (c1) 
 ); 
  1. Create table with unique clustered index

  2. Insert data into Temp "#Table" table

  3. Create non clustered indexes.

     CREATE NONCLUSTERED INDEX IX1  ON #Table (C2,C3);
    

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Actually, the Form Submission subsection of the current HTML5 draft does not allow action="". It is against the spec.

The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces. (emphasis added)

The quoted section in mercator's answer is a requirement on implementations, not authors. Authors must follow the author requirements. To quote How to read this specification:

In particular, there are conformance requirements that apply to producers, for example authors and the documents they create, and there are conformance requirements that apply to consumers, for example Web browsers. They can be distinguished by what they are requiring: a requirement on a producer states what is allowed, while a requirement on a consumer states how software is to act.

The change from HTML4—which did allow an empty URL—was made because “browsers do weird things with an empty action="" attribute”. Considering the reason for the change, its probably best not to do that in HTML4 either.

How can I stop float left?

add style="clear:both;" to the "adm" div.

Sublime Text 2 multiple line edit

Worked for me on OS X + Sublime build 3083:

OPTION (ALT) + select lines

Count the number of Occurrences of a Word in a String

If you just want the count of "male cat" then I would just do it like this:

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:

int c = str.split("\\bmale cat\\b").length - 1;

How to store arbitrary data for some HTML tags

A hack that's going to work with pretty much every possible browser is to use open classes like this: <a class='data\_articleid\_5' href="link/for/non-js-users.html>;

This is not all that elegant to the purists, but it's universally supported, standard-compliant, and very easy to manipulate. It really seems like the best possible method. If you serialize, modify, copy your tags, or do pretty much anything else, data will stay attached, copied etc.

The only problem is that you cannot store non-serializable objects that way, and there might be limits if you put something really huge there.

A second way is to use fake attributes like: <a articleid='5' href="link/for/non-js-users.html">

This is more elegant, but breaks standard, and I'm not 100% sure about support. Many browsers support it fully, I think IE6 supports JS access for it but not CSS selectors (which doesn't really matter here), maybe some browsers will be completely confused, you need to check it.

Doing funny things like serializing and deserializing would be even more dangerous.

Using ids to pure JS hash mostly works, except when you try to copy your tags. If you have tag <a href="..." id="link0">, copy it via standard JS methods, and then try to modify data attached to just one copy, the other copy will be modified.

It's not a problem if you don't copy tags, or use read only data. If you copy tags and they're modified you'll need to handle that manually.

Reading and writing binary file

If you want to do this the C++ way, do it like this:

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}

If you need that data in a buffer to modify it or something, do this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );

    // copies all data into buffer
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

}

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle module is:

# save data to a file
with open('myfile.pickle','wb') as fout:
    pickle.dump([1,2,3],fout)

# read data from a file
with open('myfile.pickle') as fin:
    print pickle.load(fin)

# output
>> [1, 2, 3]

If you dumped a list, you'll load a list, there's no need to load each item individually.

you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.

If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.

How can I select an element by name with jQuery?

You can use any attribute as selector with [attribute_name=value].

$('td[name=tcol1]').hide();

in_array() and multidimensional array

You could always serialize your multi-dimensional array and do a strpos:

$arr = array(array("Mac", "NT"), array("Irix", "Linux"));

$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');

if($in_arr){
    echo "Got Irix!";
}

Various docs for things I used:

Spring schemaLocation fails when there is no internet connection

I had ran into this similar problem as well. In my case, my resolution is quite different. Here's my spring context xml file:

...
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">
...

I'm not specifying any xsd version as I want spring to use the latest xsd version inside spring dependencies. The spring version my application used was spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE and when I assembly my application into jar, all spring dependencies exist in my classpath. However, I received following error during startup of my spring application context:

org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-beans.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

After some hard time troubleshooting, I found the issue is due to the index.list inside the META-INF folder of my jar file. With index.list file, spring namespace handlers cannot be located to parse the spring application context xml correctly. You can read more about this spring issue SPR-5705

By removing indexing from my maven-jar-plugin, I manage to resolve the issue. Hope this will save some times for people having the same problem.

How to handle a lost KeyStore password in Android?

SOLUTION 2019 (Windows, Android Studio 3.3, gradle 4.10):

This solution only works if "Remember password" checkbox was previously marked.

First of all taskArtifacts.bin don't exist for this version of gradle and idea.log shows asterisks for passwords. This was old days solutions that doesn't worked to me.

Where I found the clear text passwords: C:\Users\{username}\AndroidStudioProjects\{project}\app\build\intermediates\signing_config\release\out\signing-config.json

Keys: mStorePassword and mKeyPassword.

I really hope it helps someone else.

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Remove values from select list based on condition

As some mentioned the length of the select element decreases when removing an option. If you just want to remove one option this is not an issue but if you intend to remove several options you could get into problems. Some suggested to decrease the index manually when removing an option. In my opinion manually decreasing an index inside a for loop is not a good idea. This is why I would suggest a slightly different for loop where we iterate through all options from behind.

var selectElement = document.getElementById("selectId");

for (var i = selectElement.length - 1; i >= 0; i--){
  if (someCondition) {
    selectElement.remove(i);
  }
}

If you want to remove all options you can do something like this.

var selectElement = document.getElementById("selectId");

while (selectElement.length > 0) {
  selectElement.remove(0);
}

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

How do you remove an invalid remote branch reference from Git?

The accepted answer didn't work for me when the ref was packed. This does however:

$ git remote add public http://anything.com/bogus.git
$ git remote rm public

How can I deploy an iPhone application from Xcode to a real iPhone device?

It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph

Also be sure that the binary is marked as executable: chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph

Convert unix time to readable date in pandas dataframe

These appear to be seconds since epoch.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

Subclipse svn:ignore

This is quite frustrating, but it's a containment issue (the .svn folders keep track also of ignored files). Any item that needs to be ignored is to be added to the ignore list of the immediate parent folder.

So, I had a new sub-folder with a new file in it and wanted to ignore that file but I couldn't do it because the option was grayed out. I solved it by committing the new folder first, which I wanted to (it was a cache folder), and then adding that file to the ignore list (of the newly added folder ;-), having the chance to add a pattern instead of a single file.

What is in your .vimrc?

A lot of this comes from the wiki btw.

set nocompatible
source $VIMRUNTIME/mswin.vim
behave mswin
set nobackup
set tabstop=4
set nowrap

set guifont=Droid_Sans_Mono:h9:cANSI
colorscheme torte
set shiftwidth=4
set ic
syn off
set nohls
set acd
set autowrite
noremap \c "+yy
noremap \x "+dd
noremap \t :tabnew<CR>
noremap \2 I"<Esc>A"<Esc>
noremap \3 bi'<Esc>ea'<Esc>
noremap \" i"<Esc>ea"<Esc>
noremap ?2 Bi"<Esc>Ea"<Esc>
set matchpairs+=<:>
nnoremap <C-N> :next<CR>
nnoremap <C-P> :prev<CR>
nnoremap <Tab> :bnext<CR>
nnoremap <S-Tab> :bprevious<CR>
nnoremap \w :let @/=expand("<cword>")<Bar>split<Bar>normal n<CR>
nnoremap \W :let @/='\<'.expand("<cword>").'\>'<Bar>split<Bar>normal n<CR>

autocmd FileType xml exe ":silent %!xmllint --format --recover - "
autocmd FileType cpp set tabstop=2 shiftwidth=2 expandtab autoindent smarttab
autocmd FileType sql set tabstop=2 shiftwidth=2 expandtab autoindent smarttab

" Map key to toggle opt
function MapToggle(key, opt)
  let cmd = ':set '.a:opt.'! \| set '.a:opt."?\<CR>"
  exec 'nnoremap '.a:key.' '.cmd
  exec 'inoremap '.a:key." \<C-O>".cmd
endfunction
command -nargs=+ MapToggle call MapToggle(<f-args>)

map <F6> :if exists("syntax_on") <Bar> syntax off <Bar> else <Bar> syntax enable <Bar> endif <CR>

" Display-altering option toggles
MapToggle <F7> hlsearch
MapToggle <F8> wrap
MapToggle <F9> list

" Behavior-altering option toggles
MapToggle <F10> scrollbind
MapToggle <F11> ignorecase
MapToggle <F12> paste
set pastetoggle=<F12>

Extracting text OpenCV

this is a VB.NET version of the answer from dhanushka using EmguCV.

A few functions and structures in EmguCV need different consideration than the C# version with OpenCVSharp

Imports Emgu.CV
Imports Emgu.CV.Structure
Imports Emgu.CV.CvEnum
Imports Emgu.CV.Util

        Dim input_file As String = "C:\your_input_image.png"
        Dim large As Mat = New Mat(input_file)
        Dim rgb As New Mat
        Dim small As New Mat
        Dim grad As New Mat
        Dim bw As New Mat
        Dim connected As New Mat
        Dim morphanchor As New Point(0, 0)

        '//downsample and use it for processing
        CvInvoke.PyrDown(large, rgb)
        CvInvoke.CvtColor(rgb, small, ColorConversion.Bgr2Gray)

        '//morphological gradient
        Dim morphKernel As Mat = CvInvoke.GetStructuringElement(ElementShape.Ellipse, New Size(3, 3), morphanchor)
        CvInvoke.MorphologyEx(small, grad, MorphOp.Gradient, morphKernel, New Point(0, 0), 1, BorderType.Isolated, New MCvScalar(0))

        '// binarize
        CvInvoke.Threshold(grad, bw, 0, 255, ThresholdType.Binary Or ThresholdType.Otsu)

        '// connect horizontally oriented regions
        morphKernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, New Size(9, 1), morphanchor)
        CvInvoke.MorphologyEx(bw, connected, MorphOp.Close, morphKernel, morphanchor, 1, BorderType.Isolated, New MCvScalar(0))

        '// find contours
        Dim mask As Mat = Mat.Zeros(bw.Size.Height, bw.Size.Width, DepthType.Cv8U, 1)  '' MatType.CV_8UC1
        Dim contours As New VectorOfVectorOfPoint
        Dim hierarchy As New Mat

        CvInvoke.FindContours(connected, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple, Nothing)

        '// filter contours
        Dim idx As Integer
        Dim rect As Rectangle
        Dim maskROI As Mat
        Dim r As Double
        For Each hierarchyItem In hierarchy.GetData
            rect = CvInvoke.BoundingRectangle(contours(idx))
            maskROI = New Mat(mask, rect)
            maskROI.SetTo(New MCvScalar(0, 0, 0))

            '// fill the contour
            CvInvoke.DrawContours(mask, contours, idx, New MCvScalar(255), -1)

            '// ratio of non-zero pixels in the filled region
            r = CvInvoke.CountNonZero(maskROI) / (rect.Width * rect.Height)

            '/* assume at least 45% of the area Is filled if it contains text */
            '/* constraints on region size */
            '/* these two conditions alone are Not very robust. better to use something 
            'Like the number of significant peaks in a horizontal projection as a third condition */
            If r > 0.45 AndAlso rect.Height > 8 AndAlso rect.Width > 8 Then
                'draw green rectangle
                CvInvoke.Rectangle(rgb, rect, New MCvScalar(0, 255, 0), 2)
            End If
            idx += 1
        Next
        rgb.Save(IO.Path.Combine(Application.StartupPath, "rgb.jpg"))

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

How to deploy a war file in JBoss AS 7?

Just copy war file to standalone/deployments/ folder, it should deploy it automatically. It'll also create your_app_name.deployed file, when your application is deployed. Also be sure that you start server with bin/standalone.sh script.

How does "FOR" work in cmd batch file?

None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:

echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set MAX_TRIES=100
set P=%PATH%
for /L %%a in (1, 1, %MAX_TRIES%) do (
  for /F "delims=;" %%g in ("!P!") do (
    echo %%g
    set P=!P:%%g;=!
    if "!P!" == "%%g" goto :eof
  )
)

Oh ! I hate batch file programming !!

Updated

Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution

echo off
setlocal enabledelayedexpansion
set NonBlankPath=%PATH: =#%
set TabbedPath=%NonBlankPath:;= %
for %%g in (%TabbedPath%) do (
  set GG=%%g
  echo !GG:#= !
)

Add an element to an array in Swift

If the array is NSArray you can use the adding function to add any object at the end of the array, like this:

Swift 4.2

var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"

// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)

Result:

print(myArray) 
// ["First element", "Second element"]

That is a very simple way, regards!

How to retrieve the current version of a MySQL database management system (DBMS)?

SHOW VARIABLES LIKE "%version%";
+-------------------------+------------------------------------------+
| Variable_name           | Value                                    |
+-------------------------+------------------------------------------+
| protocol_version        | 10                                       |
| version                 | 5.0.27-standard                          |
| version_comment         | MySQL Community Edition - Standard (GPL) |
| version_compile_machine | i686                                     |
| version_compile_os      | pc-linux-gnu                             |
+-------------------------+------------------------------------------+
5 rows in set (0.04 sec)

MySQL 5.0 Reference Manual (pdf) - Determining Your Current MySQL Version - page 42

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

How to redirect to previous page in Ruby On Rails?

Why does redirect_to(:back) not work for you, why is it a no go?

redirect_to(:back) works like a charm for me. It's just a short cut for redirect_to(request.env['HTTP_REFERER'])

http://apidock.com/rails/ActionController/Base/redirect_to (pre Rails 3) or http://apidock.com/rails/ActionController/Redirecting/redirect_to (Rails 3)

Please note that redirect_to(:back) is being deprecated in Rails 5. You can use

redirect_back(fallback_location: 'something') instead (see http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)

make *** no targets specified and no makefile found. stop

Delete your source tree that was gunzipped or gzipped and extracted to folder and reextract again. Supply your options again

./configure --with-option=/path/etc ...

Then if all libs are present, your make should succeed.

How to save a new sheet in an existing excel file, using Pandas?

A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).

When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")

import pandas as pd 
from openpyxl import load_workbook

df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])

excel_dir = "my/excel/dir"

with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, '1st_sheet')   
    df2.to_excel(writer, '2nd_sheet')   
    writer.save()    

After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".

book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)    

    ## Your dataframe to append. 
    df3.to_excel(writer, '3rd_sheet')  

    writer.save()     

Be noted that excel format must not be xls, you may use xlsx one.

What is "android.R.layout.simple_list_item_1"?

Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.

From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).

C# Reflection: How to get class reference from string?

Via Type.GetType you can get the type information. You can use this class to get the method information and then invoke the method (for static methods, leave the first parameter null).

You might also need the Assembly name to correctly identify the type.

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Access: Move to next record until EOF

If (Not IsNull(Me.id.Value)) Then
DoCmd.GoToRecord , , acNext
End If

Hi, you need to put this in form activate, and have an id field named id...

this way it passes until it reaches the one without id (AKA new one)...

Moment js date time comparison

I believe you are looking for the query functions, isBefore, isSame, and isAfter.

But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff. For example:

moment().diff(date_time, 'minutes')

A few other things:

  • There's an error in the first line:

      var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
    

    That's not going to work. I think you meant:

      var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
    

    Of course, you might as well:

      var date_time = '2013-03-24T10:15:20:12Z';
    
  • You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.

    If you want to parse a value as UTC, then use:

      moment.utc(theStringToParse)
    

    Or, if you want to parse a local value and convert it to UTC, then use:

      moment(theStringToParse).utc()
    

    Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.

  • You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().

Updated

Based on your edit, I think you can just do this:

var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');

Or, if you would like to ensure that your fields are validated to be in the correct format:

var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD  HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');

How do I make a "div" button submit the form its sitting in?

Are you aware of <button> elements? <button> elements can be styled just like <div> elements and can have type="submit" so they submit the form without javascript:

<form action="whatever.html" method="post">  
    <button name="mysubmitbutton" id="mysubmitbutton" type="submit" class="customButton">  
    Button Text
    </button>  
</form>  

Using a <button> is also more semantic, whereas <div> is very generic. You get the following benefits for free:

  • JavaScript is not necessary to submit the form
  • Accessibility tools, e.g. screen readers, will (correctly) treat it as a button and not part of the normal text flow
  • <button type="submit"> becomes a "default" button, which means the return key will automatically submit the form. You can't do this with a <div>, you'd have to add a separate keydown handler to the <form> element.

There's one (non-) caveat: a <button> can only have phrasing content, though it's unlikely anyone would need any other type of content when using the element to submit a form.

How to use glyphicons in bootstrap 3.0

There you go:

<i class="glyphicon glyphicon-search"></i>

More information:

http://getbootstrap.com/components/#glyphicons

Btw. you can use this conversion tool, this will also update the code for the icons:

Read a zipped file as a pandas DataFrame

If you want to read a zipped or a tar.gz file into pandas dataframe, the read_csv methods includes this particular implementation.

df = pd.read_csv('filename.zip')

Or the long form:

df = pd.read_csv('filename.zip', compression='zip', header=0, sep=',', quotechar='"')

Description of the compression argument from the docs:

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.

New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.

Get cart item name, quantity all details woocommerce

Note on product price

The price of the product in the cart may be different from that of the product.

This can happen when you use some plugins that change the price of the product when it is added to the cart or if you have added a custom function in the functions.php of your active theme.

If you want to be sure you get the price of the product added to the cart you will have to get it like this:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

}

Instead of:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the product object
    $product            = $cart_item['data'];
    // gets the product prices
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
}

Other data you can get:

foreach ( WC()->cart->get_cart() as $cart_item ) {

    // get the data of the cart item
    $product_id         = $cart_item['product_id'];
    $variation_id       = $cart_item['variation_id'];

    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

    // gets the product object
    $product            = $cart_item['data'];
    // get the data of the product
    $sku                = $product->get_sku();
    $name               = $product->get_name();
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
    $stock_qty          = $product->get_stock_quantity();
    // attributes
    $attributes         = $product->get_attributes();
    $attribute          = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
    // custom meta
    $custom_meta        = $product->get_meta( '_custom_meta_key', true );
    // product categories
    $categories         = wc_get_product_category_list(  $product->get_id() ); // returns a string with all product categories separated by a comma
}

How can I save a base64-encoded image to disk?

Converting from file with base64 string to png image.

4 variants which works.

var {promisify} = require('util');
var fs = require("fs");

var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)

async function run () {

  // variant 1
  var d = await readFile('./1.txt', 'utf8')
  await writeFile("./1.png", d, 'base64')

  // variant 2
  var d = await readFile('./2.txt', 'utf8')
  var dd = new Buffer(d, 'base64')
  await writeFile("./2.png", dd)

  // variant 3
  var d = await readFile('./3.txt')
  await writeFile("./3.png", d.toString('utf8'), 'base64')

  // variant 4
  var d = await readFile('./4.txt')
  var dd = new Buffer(d.toString('utf8'), 'base64')
  await writeFile("./4.png", dd)

}

run();

AngularJs: Reload page

Angular 2+

I found this while searching for Angular 2+, so here is the way:

$window.location.reload();

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

How can I produce an effect similar to the iOS 7 blur view?

There is a rumor that Apple engineers claimed, to make this performant they are reading directly out of the gpu buffer which raises security issues which is why there is no public API to do this yet.

android set button background programmatically

Using setBackgroundColor() affects the style. So, declare a new style of the same properties with respect to the previous button, with a a different color.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>

Now, use OnClick method.

location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });

this changes the button but looks similar to changing the background.

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

What is the "-->" operator in C/C++?

This is exactly the same as

while (x--)
{
   printf("%d ", x);
}

for non-negative numbers

Oracle PL/SQL : remove "space characters" from a string

To remove any whitespaces you could use:

myValue := replace(replace(replace(replace(replace(replace(myValue, chr(32)), chr(9)),  chr(10)), chr(11)), chr(12)), chr(13));

Example: remove all whitespaces in a table:

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    length(t.myValue) > length(replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13)));

or

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    t.myValue like '% %'

SQL Insert Query Using C#

static SqlConnection myConnection;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myConnection = new SqlConnection("server=localhost;" +
                                                      "Trusted_Connection=true;" +
             "database=zxc; " +
                                                      "connection timeout=30");
        try
        {

            myConnection.Open();
            label1.Text = "connect successful";

        }
        catch (SqlException ex)
        {
            label1.Text = "connect fail";
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("insert successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

How to set an HTTP proxy in Python 2.7?

You can install pip (or any other package) with easy_install almost as described in the first answer. However you will need a HTTPS proxy, too. The full sequence of commands is:

set http_proxy=http://proxy.myproxy.com
set https_proxy=http://proxy.myproxy.com
easy_install pip

You might also want to add a port to the proxy, such as http{s}_proxy=http://proxy.myproxy.com:8080

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

apache ProxyPass: how to preserve original IP address

The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip

All what you must do is:

  1. May be you must install the mod_remoteip package
  2. Enable the module:

    LoadModule remoteip_module modules/mod_remoteip.so
    
  3. Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):

    RemoteIPHeader X-Forwarded-For
    

See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.

modify the page with the map:

<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
    directionsService,
    map;

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

</script>

For more details take a look at: https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834

Example: http://jsfiddle.net/doktormolle/zJ5em/

WPF button click in C# code

The following should do the trick:

btn.Click += btn1_Click;

How does one target IE7 and IE8 with valid CSS?

The answer to your question

A completely valid way to select all browsers but IE8 and below is using the :root selector. Since IE versions 8 and below do not support :root, selectors containing it are ignored. This means you could do something like this:

p {color:red;}
:root p {color:blue;}

This is still completely valid CSS, but it does cause IE8 and lower to render different styles.

Other tricks

Here's a list of all completely valid CSS browser-specific selectors I could find, except for some that seem quite redundant, such as ones that select for just 1 type of ancient browser (1, 2):

/******  First the hacks that target certain specific browsers  ******/
* html p                        {color:red;} /* IE 6- */
*+html p                        {color:red;} /* IE 7 only */
@media screen and (-webkit-min-device-pixel-ratio:0) {
    p                           {color:red;}
}                                            /* Chrome, Safari 3+ */
p, body:-moz-any-link           {color:red;} /* Firefox 1+ */
:-webkit-any(html) p            {color:red;} /* Chrome 12+, Safari 5.1.3+ */
:-moz-any(html) p               {color:red;} /* Firefox 4+ */

/****** And then the hacks that target all but certain browsers ******/
html> body p                  {color:green;} /* not: IE<7 */
head~body p                   {color:green;} /* not: IE<7, Opera<9, Safari<3 */
html:first-child p            {color:green;} /* not: IE<7, Opera<9.5, Safari&Chrome<4, FF<3 */
html>/**/body p               {color:green;} /* not: IE<8 */
body:first-of-type p          {color:green;} /* not: IE<9, Opera<9, Safari<3, FF<3.5 */
:not([ie8min]) p              {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
body:not([oldbrowser]) p      {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */

Credits & sources:

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

Ref 1 2

Best practices for copying files with Maven

I was able to piece together a number of different sources for this answer:

...
<repository>
    <id>atlassian</id>
    <name>Atlassian Repo</name>
    <url>https://maven.atlassian.com/content/repositories/atlassian-public</url>
</repository>
...
<dependency>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-upload-plugin</artifactId>
    <version>1.1</version>
</dependency>
...
<plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-upload-plugin</artifactId>
    <version>1.1</version>
    <configuration>
        <serverId>jira-repo</serverId>
        <resourceSrc>
            ${project.build.directory}/${project.build.finalName}.${project.packaging}
        </resourceSrc>
        <resourceDest>opt/jira/webapps</resourceDest> <!-- note: no leading slash -->
        <url>scp://root@jira</url>
    </configuration>
</plugin>
...

From ~/.m2/settings.xml:

...
<servers>
  <server>
    <id>jira-repo</id>
    <username>myusername</username>
    <password>mypassword</password>
  </server>
</servers>
...

Then run the command: (the -X is for debug)

mvn -X upload:upload

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

VC++ fatal error LNK1168: cannot open filename.exe for writing

The problem is probably that you forgot to close the program and that you instead have the program running in the background.

Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.

I know this posting is old, but I am answering for the other people like me who find this through the search engines.

Importing JSON into an Eclipse project

Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.

To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download

I hope this will solve your problem

Read Excel File in Python

A somewhat late answer, but with pandas, it is possible to get directly a column of an excel file:

import pandas

df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]

Make sure you have installed xlrd and pandas:

pip install pandas xlrd

Find the files existing in one directory but not in the other

Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.

Meld comparing directories

How to output in CLI during execution of PHP Unit tests?

In short, phpunit supresses STDOUT. It writes to STDERR by default, unless you add --verbose or --debug . You can do one of those things:

  • print your debug output to STDERR instead
  • var_dump your debug as usual but add --verbose to the phpunit command line
  • var_dump your debug as usual but add a line ob_flush(); beneath it
  • use the correct commands in phpunit for testing exactly what you're trying to test here

Obviously, the last thing is the Good Thing to do, and the rest are quick temporary hacks.

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

Converting XDocument to XmlDocument and vice versa

If you need a Win 10 UWP compatible variant:

using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new DomXmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.LoadXml(xmlReader.ReadOuterXml());
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    xmlDocument.WriteContentTo(w);
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }

        public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
        {
            using (var memStream = new MemoryStream())
            {
                using (var w = XmlWriter.Create(memStream))
                {
                    w.WriteRaw(xmlDocument.GetXml());
                }
                memStream.Seek(0, SeekOrigin.Begin);
                using (var r = XmlReader.Create(memStream))
                {
                    return XDocument.Load(r);
                }
            }
        }
    }

What is the difference between Subject and BehaviorSubject?

It might help you to understand.

import * as Rx from 'rxjs';

const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.

const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);

const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.

const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2 

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Swift GET request with parameters

I am using this, try it in playground. Define the base urls as Struct in Constants

struct Constants {

    struct APIDetails {
        static let APIScheme = "https"
        static let APIHost = "restcountries.eu"
        static let APIPath = "/rest/v1/alpha/"
    }
}

private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {

    var components = URLComponents()
    components.scheme = Constants.APIDetails.APIScheme
    components.host   = Constants.APIDetails.APIHost
    components.path   = Constants.APIDetails.APIPath
    if let paramPath = pathparam {
        components.path = Constants.APIDetails.APIPath + "\(paramPath)"
    }
    if !parameters.isEmpty {
        components.queryItems = [URLQueryItem]()
        for (key, value) in parameters {
            let queryItem = URLQueryItem(name: key, value: "\(value)")
            components.queryItems!.append(queryItem)
        }
    }

    return components.url!
}

let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")

//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

You probably need an inner div. With css is:

.fixed {
   position: fixed;
   top: 0;
   left: 0;
   bottom: 0;
   overflow-y: auto;
   width: 200px; // your value
}
.inner {
   min-height: 100%;
}

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Encode a FileStream to base64 with c#

You may try something like that:

    public Stream ConvertToBase64(Stream stream)
    {
        Byte[] inArray = new Byte[(int)stream.Length];
        Char[] outArray = new Char[(int)(stream.Length * 1.34)];
        stream.Read(inArray, 0, (int)stream.Length);
        Convert.ToBase64CharArray(inArray, 0, inArray.Length, outArray, 0);
        return new MemoryStream(Encoding.UTF8.GetBytes(outArray));
    }

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

How to check for palindrome using Python logic

#!/usr/bin/python

str = raw_input("Enter a string ")
print "String entered above is %s" %str
strlist = [x for x in str ]
print "Strlist is %s" %strlist
strrev = list(reversed(strlist)) 
print "Strrev is %s" %strrev
if strlist == strrev :
   print "String is palindrome"
else :
   print "String is not palindrome"

Git merge develop into feature branch outputs "Already up-to-date" while it's not

git pull origin develop

Since pulling a branch into another directly merges them together

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Postgres sql has a way of doing it

pls refer: http://www.postgresonline.com/journal/archives/41-How-to-SELECT-ALL-EXCEPT-some-columns-in-a-table.html

The Information Schema Hack Way

SELECT 'SELECT ' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'officepark' 
            AND  c.column_name NOT IN('officeparkid', 'contractor')
    ), ',') || ' FROM officepark As o' As sqlstmt

The above for my particular example table - generates an sql statement that looks like this

SELECT o.officepark,o.owner,o.squarefootage FROM officepark As o

How to check which version of Keras is installed?

Python library authors put the version number in <module>.__version__. You can print it by running this on the command line:

python -c 'import keras; print(keras.__version__)'

If it's Windows terminal, enclose snippet with double-quotes like below

python -c "import keras; print(keras.__version__)"

How to find if a given key exists in a C++ std::map

template <typename T, typename Key>
bool key_exists(const T& container, const Key& key)
{
    return (container.find(key) != std::end(container));
}

Of course if you wanted to get fancier you could always template out a function that also took a found function and a not found function, something like this:

template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction>
void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function)
{
    auto& it = container.find(key);
    if (it != std::end(container))
    {
        found_function(key, it->second);
    }
    else
    {
        not_found_function(key);
    }
}

And use it like this:

    std::map<int, int> some_map;
    find_and_execute(some_map, 1,
        [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; },
        [](int key){ std::cout << "key " << key << " not found" << std::endl; });

The downside to this is coming up with a good name, "find_and_execute" is awkward and I can't come up with anything better off the top of my head...

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Typically you add a class selector to the :not() pseudo-class like so:

:not(.printable) {
    /* Styles */
}

:not([attribute]) {
    /* Styles */
}

But if you need better browser support (IE8 and older don't support :not()), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.

Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable, or otherwise affect them one way or another. For example, although display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

MySQL error 2006: mysql server has gone away

The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.

I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that is idle for more than 5 mins.

Once again, this is the unlikely scenario.

Correct way to load a Nib for a UIView subclass

In Swift:

For example, name of your custom class is InfoView

At first, you create files InfoView.xib and InfoView.swiftlike this:

import Foundation
import UIKit

class InfoView: UIView {
    class func instanceFromNib() -> UIView {
    return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}

Then set File's Owner to UIViewController like this:

enter image description here

Rename your View to InfoView:

enter image description here

Right-click to File's Owner and connect your view field with your InfoView:

enter image description here

Make sure that class name is InfoView:

enter image description here

And after this you can add the action to button in your custom class without any problem:

enter image description here

And usage of this custom class in your MainViewController:

func someMethod() {
    var v = InfoView.instanceFromNib()
    v.frame = self.view.bounds
    self.view.addSubview(v)
}

Sorting a tab delimited file

If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:

tr " " "\t" < <file> | sort <options>

Returning an empty array

There is no difference except the fact that foo performs 3 visible method calls to return empty array that is anyway created while bar() just creates this array and returns it.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

Load local HTML file in a C# WebBrowser

What worked for me was

<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />

from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

How to Create a circular progressbar in Android which rotates on it?

With the Material Components Library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
    app:indicatorColor="@color/...."
    app:trackColor="@color/...."
    app:circularRadius="64dp"/>

You can use these attributes:

  • circularRadius: defines the radius of the circular progress indicator
  • trackColor: the color used for the progress track. If not defined, it will be set to the indicatorColor and apply the android:disabledAlpha from the theme.
  • indicatorColor: the single color used for the indicator in determinate/indeterminate mode. By default it uses theme primary color

enter image description here

Use progressIndicator.setProgressCompat((int) value, true); to update the value in the indicator.

Note: it requires at least the version 1.3.0-alpha04.

Swift: How to get substring from start to last index of character

Swift 3, XCode 8

func lastIndexOfCharacter(_ c: Character) -> Int? {
    return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}

Since advancedBy(Int) is gone since Swift 3 use String's method index(String.Index, Int). Check out this String extension with substring and friends:

public extension String {

    //right is the first encountered string after left
    func between(_ left: String, _ right: String) -> String? {
        guard let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
        , leftRange.upperBound <= rightRange.lowerBound
            else { return nil }
    
        let sub = self.substring(from: leftRange.upperBound)
        let closestToLeftRange = sub.range(of: right)!
        return sub.substring(to: closestToLeftRange.lowerBound)
    }

    var length: Int {
        get {
            return self.characters.count
        }
    }

    func substring(to : Int) -> String {
        let toIndex = self.index(self.startIndex, offsetBy: to)
        return self.substring(to: toIndex)
    }

    func substring(from : Int) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: from)
        return self.substring(from: fromIndex)
    }

    func substring(_ r: Range<Int>) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        return self.substring(with: Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex)))
    }

    func character(_ at: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: at)]
    }

    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
        { return nil }
        return distance(from: startIndex, to: index)
    }
}

UPDATED extension for Swift 5

public extension String {
    
    //right is the first encountered string after left
    func between(_ left: String, _ right: String) -> String? {
        guard
            let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
            , leftRange.upperBound <= rightRange.lowerBound
            else { return nil }
        
        let sub = self[leftRange.upperBound...]
        let closestToLeftRange = sub.range(of: right)!            
        return String(sub[..<closestToLeftRange.lowerBound])
    }
    
    var length: Int {
        get {
            return self.count
        }
    }
    
    func substring(to : Int) -> String {
        let toIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[...toIndex])
    }
    
    func substring(from : Int) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: from)
        return String(self[fromIndex...])
    }
    
    func substring(_ r: Range<Int>) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
        return String(self[indexRange])
    }
    
    func character(_ at: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: at)]
    }
    
    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
        { return nil }
        return distance(from: startIndex, to: index)
    }
}

Usage:

let text = "www.stackoverflow.com"
let at = text.character(3) // .
let range = text.substring(0..<3) // www
let from = text.substring(from: 4) // stackoverflow.com
let to = text.substring(to: 16) // www.stackoverflow
let between = text.between(".", ".") // stackoverflow
let substringToLastIndexOfChar = text.lastIndexOfCharacter(".") // 17

P.S. It's really odd that developers forced to deal with String.Index instead of plain Int. Why should we bother about internal String mechanics and not just have simple substring() methods?

NSURLSession/NSURLConnection HTTP load failed on iOS 9

I have solved it with adding some key in info.plist. The steps I followed are:

I Opened my project's info.plist file

Added a Key called NSAppTransportSecurity as a Dictionary.

Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image. enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link: https://stackoverflow.com/a/32609970