Programs & Examples On #Local security policy

Local security settings for Windows

How to save/restore serializable object to/from file?

**1. Convert the json string to base64string and Write or append it to binary file. 2. Read base64string from binary file and deserialize using BsonReader. **

 public static class BinaryJson
{
    public static string SerializeToBase64String(this object obj)
    {
        JsonSerializer jsonSerializer = new JsonSerializer();
        MemoryStream objBsonMemoryStream = new MemoryStream();
        using (BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream))
        {
            jsonSerializer.Serialize(bsonWriterObject, obj);
            return Convert.ToBase64String(objBsonMemoryStream.ToArray());
        }           
        //return Encoding.ASCII.GetString(objBsonMemoryStream.ToArray());
    }
    public static T DeserializeToObject<T>(this string base64String)
    {
        byte[] data = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(data);
        using (BsonReader reader = new BsonReader(ms))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }
    }
}

How to set app icon for Electron / Atom Shell App

Updated package.json:

"build": {
  "appId": "com.my-website.my-app",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "icon": "./public/icons/mac/icon.icns",     <---------- set Mac Icons
    "category": "public.app-category.utilities"
  },
  "win": {
    "icon": "./public/icons/png/256x256.png" <---------- set Win Icon
  },
  "files": [
    "./build/**/*",
    "./dist/**/*",
    "./node_modules/**/*",
    "./public/**/*",       <---------- need for get access to icons
    "*.js"
  ],
  "directories": {
    "buildResources": "public" <---------- folder where placed icons
  }
},

After build application you can see icons. This solution don't show icons in developer mode. I don't setup icons in new BrowserWindow().

Get ID from URL with jQuery

try this javascript

Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.

javascript

function getUrlParameters(parameter, staticURL, decode){

       var currLocation = (staticURL.length)? staticURL : window.location.search,
           parArr = currLocation.split("?")[1].split("&"),
           returnBool = true;

       for(var i = 0; i < parArr.length; i++){
            parr = parArr[i].split("=");
            if(parr[0] == parameter){
                return (decode) ? decodeURIComponent(parr[1]) : parr[1];
                returnBool = true;
            }else{
                returnBool = false;            
            }
       }

       if(!returnBool) return false;  
    }

To get the parameter “id” from above static URL, use the following:

var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);

or

var idParameter = getUrlParameters("id", "", true);

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

If you can produce a small demo showing the onMouseEnter / onMouseLeave or onMouseDown / onMouseUp bug, it would be worthwhile to post it to ReactJS's issues page or mailing list, just to raise the question and hear what the developers have to say about it.

In your use case, you seem to imply that CSS :hover and :active states would be enough for your purposes, so I suggest you use them. CSS is orders of magnitude faster and more reliable than Javascript, because it's directly implemented in the browser.

However, :hover and :active states cannot be specified in inline styles. What you can do is assign an ID or a class name to your elements and write your styles either in a stylesheet, if they are somewhat constant in your application, or in a dynamically generated <style> tag.

Here's an example of the latter technique: https://jsfiddle.net/ors1vos9/

HTML Drag And Drop On Mobile Devices

There is a new polyfill for translating touch events to drag-and-drop, such that HTML5 Drag And Drop is utilizable on mobile.

The polyfill was introduced by Bernardo Castilho on this post.

Here's a demo from that post.

The post also presents several considerations of the folyfill design.

Dump a NumPy array into a csv file

Writing record arrays as CSV files with headers requires a bit more work.

This example reads from a CSV file ('example.csv') and writes its contents to another CSV file (out.csv).

import numpy as np

# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
    fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')

# Read it as a Numpy record array
ar = np.recfromcsv('example.csv')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')], 
#           dtype=[('col1', '<i4'), ('col2', '<f8'), ('col3', 'S13')])

# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
    fp.write(','.join(ar.dtype.names) + '\n')
    np.savetxt(fp, ar, '%s', ',')

Note that the above example cannot handle values which are strings with commas. To always enclose non-numeric values within quotes, use the csv package:

import csv

with open('out2.csv', 'wb') as fp:
    writer = csv.writer(fp, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(ar.dtype.names)
    writer.writerows(ar.tolist())

When should I use curly braces for ES6 import?

The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment

A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?.

How to vertically center a <span> inside a div?

At your parent DIV add

display:table;

and at your child element add

 display:table-cell;
 vertical-align:middle;

String.equals versus ==

If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.

Example:

String a = "name";

String b = "name";

if(a == b) and (a.equals(b)) will return true.

But

String a = new String("a");

In this case if(a == b) will return false

So it's better to use the .equals operator...

How to "flatten" a multi-dimensional array to simple one in PHP?

Another method from PHP's user comments (simplified) and here:

function array_flatten_recursive($array) { 
   if (!$array) return false;
   $flat = array();
   $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
   foreach ($RII as $value) $flat[] = $value;
   return $flat;
}

The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:

$array = array( 
    'A' => array('B' => array( 1, 2, 3)), 
    'C' => array(4, 5) 
); 
print_r(array_flatten_recursive($array)); 

#Returns: 
Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)

What is a NullReferenceException, and how do I fix it?

On the matter of "what should I do about it", there can be many answers.

A more "formal" way of preventing such error conditions while developing is applying design by contract in your code. This means you need to set class invariants, and/or even function/method preconditions and postconditions on your system, while developing.

In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution of a bug-free program, therefore design by contract is checked in practice in debug mode, while being disabled in releases, to maximize the developed system performance.

This way, you can avoid NullReferenceException cases that are results of violation of the constraints set. For example, if you use an object property X in a class and later try to invoke one of its methods and X has a null value, then this will lead to NullReferenceException:

public X { get; set; }

public void InvokeX()
{
    X.DoSomething(); // if X value is null, you will get a NullReferenceException
}

But if you set "property X must never have a null value" as method precondition, then you can prevent the scenario described before:

//Using code contracts:
[ContractInvariantMethod]
protected void ObjectInvariant() 
{
    Contract.Invariant(X != null);
    //...
}

For this cause, Code Contracts project exists for .NET applications.

Alternatively, design by contract can be applied using assertions.

UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language.

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

Check if table exists in SQL Server

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END

ADB error: cannot connect to daemon

Go to windows task manager and end process tree of adb. It will make attempts to start adb.

Sometimes on Windows adb kill-server and adb start-server fail to start adb.

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

Generating Fibonacci Sequence

I've tried this: it might work:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fibonacci</title>
    <style>
        * {
            outline: 0px;
            margin: 0px;
        }

        input[type="number"] {
            color: blue;
            border: 2px solid black;
            width: 99.58vw;
        }
    </style>
</head>

<body>
    <div id="myDiv" style="color: white;background-color: blue;">Numbers Here</div>
    <input type="number" id="input1" oninput="fibonacciProgram(this.value)" placeholder="Type Some Numbers Here">
    <script>
        function fibonacciProgram(numberCount) {
            let resultElement = document.getElementById("myDiv");
            resultElement.innerHTML = " ";
            if (isNaN(numberCount) || numberCount <= 0) {
                resultElement.innerHTML = "please enter a number";
                return;
            }
            let firstBox = 0;
            let secondBox = 1;
            let swichBox;
            let entries = [];
            entries.push(secondBox);
            while (numberCount > 1) {
                swichBox = firstBox + secondBox;
                entries.push(swichBox);
                firstBox = secondBox;
                secondBox = swichBox;
                numberCount--;
            }
            resultElement.innerHTML = entries.join(', ');
        }
    </script>
</body>

</html>

SQL Server, division returns zero

In SQL Server direct division of two integer returns integer even if the result should be the float. There is an example below to get it across:

--1--
declare @weird_number_float float
set @weird_number_float=22/7
select @weird_number_float

--2--
declare @weird_number_decimal decimal(18,10)
set @weird_number_decimal=22/7 
select @weird_number_decimal

--3--
declare @weird_number_numeric numeric
set @weird_number_numeric=22/7 
select @weird_number_numeric

--Right way

declare @weird_number float
set @weird_number=cast(22 as float)/cast(7 as float)
select @weird_number

Just last block will return the 3,14285714285714. In spite of the second block defined with right precision the result will be 3.00000.

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

Assigning default values to shell variables with a single command in bash

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:-default}

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

I wanted to downgrade from API 23 to 22 and got this error. I had to change all build.gradle files in a project in order to compile.

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.yourapp.app"
        minSdkVersion 14
        targetSdkVersion 22
    }
...
dependencies {
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.android.support:support-v4:22.2.1'
    compile 'com.android.support:design:22.2.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
}

Session 'app': Error Installing APK

Try to remove the .idea folder and .gradle folder, then click Sync Project with Gradle Files, when the process finished, try to run app again.

Hope it works.

How to set TLS version on apache HttpClient

The solution is:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .build();

SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
    sslContext,
    new String[]{"TLSv1", "TLSv1.1"},   
    null,
    BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

httpClient = HttpClients.custom()
    .setSSLSocketFactory(f)
    .build();

This requires org.apache.httpcomponents.httpclient 4.3.x though.

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

ImportError: No module named 'pygame'

I was trying to figure this out for at least an hour. And you're right the problem is that the installation files are all for 32 bit.

Luckily I found a link to the 64 pygame download! Here it is: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Just pick the corresponding version according to your python version and it should work like magic. The installation feature will bring you to a bright-blue screen as the installation (at this point you know that the installation is correct for you.

Then go into the Python IDLE and type "import pygame" and you should not get any more errors.

Props go to @yuvi who shared the link with StackOverflow.

Replace all spaces in a string with '+'

You need to look for some replaceAll option

str = str.replace(/ /g, "+");

this is a regular expression way of doing a replaceAll.

function ReplaceAll(Source, stringToFind, stringToReplace) {
    var temp = Source;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

};

How to add a new object (key-value pair) to an array in javascript?

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

var postData = $('#yourform').serializeArray();

// postData (array with objects) : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

postData.push({"name": "phone", "value": "1234-123456"});

Result:

// postData : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

exception in thread 'main' java.lang.NoClassDefFoundError:

Easy & Simple solution: I solved this problem (NetBeans) by exporting the original project into zip file, deleting the original project directory and importing the project back from the zip file.

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

Proper way to rename solution (and directories) in Visual Studio

To rename a website:

http://www.c-sharpcorner.com/Blogs/46334/rename-website-project-in-visual-studio-2013.aspx

locate and edit IISExpress's applicationhost.config, found here: C:\Users{username}\Documents\IISExpress\config

How to add a new row to an empty numpy array

In this case you might want to use the functions np.hstack and np.vstack

arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]

arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]

You also can use the np.concatenate function.

Cheers

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

Unzip a file with php

I updated answer of @rdlowrey to a cleaner and better code, This will unzip a file into current directory using __DIR__.

<?php 
    // config
    // -------------------------------
    // only file name + .zip
    $zip_filename = "YOURFILENAME.zip";
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' >
    <title>Unzip</title>
    <style>
        body{
            font-family: arial, sans-serif;
            word-wrap: break-word;
        }
        .wrapper{
            padding:20px;
            line-height: 1.5;
            font-size: 1rem;
        }
        span{
            font-family: 'Consolas', 'courier new', monospace;
            background: #eee;
            padding:2px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php
        echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
        echo "current dir: <span>" . __DIR__ . "</span><br>";
        $zip = new ZipArchive;
        $res = $zip->open(__DIR__ . '/' .$zip_filename);
        if ($res === TRUE) {
          $zip->extractTo(__DIR__);
          $zip->close();
          echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
        } else {
          echo '<p style="color:red;">Zip file not found!</p><br>';
        }
        ?>
        End Script.
    </div>
</body>
</html> 

Django CSRF check failing with an Ajax POST request

It seems nobody has mentioned how to do this in pure JS using the X-CSRFToken header and {{ csrf_token }}, so here's a simple solution where you don't need to search through the cookies or the DOM:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

Find all controls in WPF Window by type

And this is how it works upwards

    private T FindParent<T>(DependencyObject item, Type StopAt) where T : class
    {
        if (item is T)
        {
            return item as T;
        }
        else
        {
            DependencyObject _parent = VisualTreeHelper.GetParent(item);
            if (_parent == null)
            {
                return default(T);
            }
            else
            {
                Type _type = _parent.GetType();
                if (StopAt != null)
                {
                    if ((_type.IsSubclassOf(StopAt) == true) || (_type == StopAt))
                    {
                        return null;
                    }
                }

                if ((_type.IsSubclassOf(typeof(T)) == true) || (_type == typeof(T)))
                {
                    return _parent as T;
                }
                else
                {
                    return FindParent<T>(_parent, StopAt);
                }
            }
        }
    }

When to use dynamic vs. static libraries

A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.

You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).

You would use a static library whenever you don't have a reason to use a dynamic library.

showing that a date is greater than current date

Assuming you have a field for DateTime, you could have your query look like this:

SELECT *
FROM TABLE
WHERE DateTime > (GetDate() + 90)

Adding a slide effect to bootstrap dropdown

Update 2018 Bootstrap 4

In Boostrap 4, the .open class has been replaced with .show. I wanted to implement this using only CSS transistions without the need for extra JS or jQuery...

.show > .dropdown-menu {
  max-height: 900px;
  visibility: visible;
}

.dropdown-menu {
  display: block;
  max-height: 0;
  visibility: hidden;
  transition: all 0.5s ease-in-out;
  overflow: hidden;
}

Demo: https://www.codeply.com/go/3i8LzYVfMF

Note: max-height can be set to any large value that's enough to accommodate the dropdown content.

Change window location Jquery

Assuming you want to change the url to another within the same domain, you can use this:

history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');

How to create a file name with the current date & time in Python?

Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.

# import time and OS modules to use to build file folder name
import time
import os 

# Build string for directory to hold files
# Output Configuration
#   drive_letter = Output device location (hard drive) 
#   folder_name = directory (folder) to receive and store PDF files

drive_letter = r'D:\\' 
folder_name = r'downloaded-files'
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
folder_to_save_files = drive_letter + folder_name + folder_time 

# IF no such folder exists, create one automatically
if not os.path.exists(folder_to_save_files):
    os.mkdir(folder_to_save_files)

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Insert all values of a table into another table in SQL

If you are transferring a lot data permanently, i.e not populating a temp table, I would recommend using SQL Server Import/Export Data for table-to-table mappings.

Import/Export tool is usually better than straight SQL when you have type conversions and possible value truncation in your mapping. Generally, the more complex your mapping, the more productive you are using an ETL tool like Integration Services (SSIS) instead of direct SQL.

Import/Export tool is actually an SSIS wizard, and you can save your work as a dtsx package.

What is the difference between DBMS and RDBMS?

Since this question become popular on Stack Overflow, I am posting an answer which answers this question for me. I found this answer on udemy website. Hope this will help future users and newbies searching for a good answer on this topic.


Key Difference between DBMS and RDBMS:

The key difference is that RDBMS (relational database management system) applications store data in a tabular form, while DBMS applications store data as files.

Does that mean there are no tables in a DBMS?

There can be, but there will be no “relation” between the tables, like in a RDBMS. In DBMS, data is generally stored in either a hierarchical form or a navigational form. This means that a single data unit will have one parent node and zero, one or more children nodes. It may even be stored in a graph form, which can be seen in the network model.

In a RDBMS, the tables will have an identifier called primary key. Data values will be stored in the form of tables. The relationships between these data values will be stored in the form of a table as well. Every value stored in the relational database is accessible. This value can be updated by the system. The data in this system is also physically and logically independent.

You can say that a RDBMS is an extension of a DBMS, even if there are many differences between the two. Most software products in the market today are both DBMS and RDBMS compliant. Essentially, they can maintain databases in a (relational) tabular form as well as a file form, or both. This means that today a RDBMS application is a DBMS application, and vice versa. However, there are still major differences between a relational database system for storing data and a plain database system.

PermissionError: [Errno 13] in python

I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module

How can I find the number of years between two dates?

Here's what I think is a better method:

public int getYearsBetweenDates(Date first, Date second) {
    Calendar firstCal = GregorianCalendar.getInstance();
    Calendar secondCal = GregorianCalendar.getInstance();

    firstCal.setTime(first);
    secondCal.setTime(second);

    secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

    return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}

EDIT

Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class YearsBetweenDates {
    public static int getYearsBetweenDates(Date first, Date second) {
        Calendar firstCal = GregorianCalendar.getInstance();
        Calendar secondCal = GregorianCalendar.getInstance();

        firstCal.setTime(first);
        secondCal.setTime(second);

        secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

        return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
    }

    private static class TestCase {
        public Calendar date1;
        public Calendar date2;
        public int expectedYearDiff;
        public String comment;

        public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
            this.date1 = date1;
            this.date2 = date2;
            this.expectedYearDiff = expectedYearDiff;
            this.comment = comment;
        }
    }

    private static TestCase[] tests = {
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2015, Calendar.JULY, 15),
                1,
                "exactly one year"),
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 14),
                2,
                "one day less than 3 years"),
        new TestCase(
                new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
                new GregorianCalendar(2017, Calendar.MAY, 3),
                1,
                "a year and a half"),
        new TestCase(
                new GregorianCalendar(2016, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 15),
                1,
                "leap years do not compare correctly"),
    };

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (TestCase t : tests) {
            int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
            String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
            System.out.println(t.comment + ": " +
                    df.format(t.date1.getTime()) + " -> " +
                    df.format(t.date2.getTime()) + " = " +
                    diff + ": " + result);
        }
    }
}

How to remove all .svn directories from my application directories

As an important issue, when you want to utilize shell to delete .svn folders You need -depth argument to prevent find command entering the directory that was just deleted and showing error messages like e.g.

"find: ./.svn: No such file or directory"

As a result, You can use find command like below:

cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

Redirect after Login on WordPress

add_action('wp_head','redirect_admin');
function redirect_admin(){
  if(is_admin()){
    wp_redirect(WP_HOME.'/news.php');
    die; // You have to die here
  }
}

Or if you only want to redirect other users:

add_action('wp_head','redirect_admin');
function redirect_admin(){
  if(is_admin()&&!current_user_can('level_10')){
    wp_redirect(WP_HOME.'/news.php');
    die; // You have to die here
  }
}

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

I've made a category from @Abizern answer

@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
    NSError *error;
    NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
    return (!json ? nil : json);
}
@end

Use it like this,

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

Get loop counter/index using for…of syntax in JavaScript

For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

loop over an Array:

var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

loop over an Object:

var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}

TimePicker Dialog from clicking EditText

In all of the above, the EditText still needs the focusable="false" attribute in the xml in order to prevent the keyboard from popping up.

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

How to retrieve Jenkins build parameters using the Groovy API?

If you are trying to get all parameters passed to Jenkins job you can use the global variable params in your groovy pipeline to fetch it.

http://jenkins_host:8080/pipeline-syntax/globals

params

Exposes all parameters defined in the build as a read-only map with variously typed values. Example:

if (params.BOOLEAN_PARAM_NAME) {doSomething()} or to supply a nontrivial default value:

if (params.get('BOOLEAN_PARAM_NAME', true)) {doSomething()} Note for multibranch (Jenkinsfile) usage: the properties step allows you to define job properties, but these take effect when the step is run, whereas build parameter definitions are generally consulted before the build begins. As a convenience, any parameters currently defined in the job which have default values will also be listed in this map. That allows you to write, for example:

properties([parameters([string(name: 'BRANCH', defaultValue: 'master')])]) git url: '…', branch: params.BRANCH and be assured that the master branch will be checked out even in the initial build of a branch project, or if the previous build did not specify parameters or used a different parameter name.

Use something like below.

def dumpParameter()
{
  params.each {
    println it.key + " = " + it.value
  }
}

how to change the dist-folder path in angular-cli after 'ng build'

Angular CLI now uses environment files to do this.

First, add an environments section to the angular-cli.json

Something like :

{
  "apps": [{
      "environments": {
        "prod": "environments/environment.prod.ts"
      }
    }]
}

And then inside the environment file (environments/environment.prod.ts in this case), add something like :

export const environment = {
  production: true,
  "output-path": "./whatever/dist/"
};

now when you run :

ng build --prod

it will output to the ./whatever/dist/ folder.

ASP.NET MVC Global Variables

You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

Replacing blank values (white space) with NaN in pandas

How about:

d = d.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)

The applymap function applies a function to every cell of the dataframe.

What is the { get; set; } syntax in C#?

Such { get; set; } syntax is called automatic properties, C# 3.0 syntax

You must use Visual C# 2008 / csc v3.5 or above to compile. But you can compile output that targets as low as .NET Framework 2.0 (no runtime or classes required to support this feature).

Rails: Why "sudo" command is not recognized?

That you are running Windows. Read:

http://en.wikipedia.org/wiki/Sudo

It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.

That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.

Laravel 5.2 - pluck() method returns array

In Laravel 5.1+, you can use the value() instead of pluck.

To get first occurence, You can either use

DB::table('users')->value('name');

or use,

DB::table('users')->where('id', 1)->pluck('name')->first();

How set background drawable programmatically in Android

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

How to check if a file exists in a folder?

if (File.Exists(localUploadDirectory + "/" + fileName))
{                        
    `Your code here`
}

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

CSS Styling for a Button: Using <input type="button> instead of <button>

In your .button CSS, try display:inline-block. See this JSFiddle

Real escape string and PDO

You should use PDO Prepare

From the link:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:

if(jQuery && !jQuery.fn.live) {
    jQuery.fn.live = function(evt, func) {
        $('body').on(evt, this.selector, func);
    }
}

Just include it after you load jQuery and before you call live().

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

Java: how to represent graphs?

class Vertex {
    private String name;
    private int score; // for path algos
    private boolean visited; // for path algos
    List<Edge> connections;
}

class Edge {
    private String vertex1Name; // same as Vertex.name
    private String vertex2Name;
    private int length;
}

class Graph {
    private List<Edge> edges;
}

Cut Java String at a number of character

Use substring and concatenate:

if(str.length() > 50)
    strOut = str.substring(0,7) + "...";

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

How do I put a border around an Android textview?

You can create custom background for your text view. Steps 1. Go to your project. 2. Go to resources and right click to drawable. 3. Click on New -> Drawable Resource File 4. Give name to you file 5. Paste following code in the file

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="@color/colorBlack" />
<padding android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp" />
<corners android:radius="6dp" />
<solid android:color="#ffffffff" />

  1. For your text view where you want to use it as backgroud,

    android:background="@drawable/your_fileName"

React-Native Button style not work

React Native buttons are very limited in the option they provide.You can use TouchableHighlight or TouchableOpacity by styling these element and wrapping your buttons with it like this

             <TouchableHighlight 
                style ={{
                    height: 40,
                    width:160,
                    borderRadius:10,
                    backgroundColor : "yellow",
                    marginLeft :50,
                    marginRight:50,
                    marginTop :20
                }}>
            <Button onPress={this._onPressButton}            
            title="SAVE"
            accessibilityLabel="Learn more about this button"
          /> 
          </TouchableHighlight> 

You can also use react library for customised button .One nice library is react-native-button (https://www.npmjs.com/package/react-native-button)

How to solve '...is a 'type', which is not valid in the given context'? (C#)

Change

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS = new CERas.CERAS(); 
    } 

to

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS c = new CERas.CERAS(); 
    } 

Or if you wish to use it later again

change it to

using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WinApp_WMI2 
{ 
    public partial class Form1 : Form 
    { 
        CERas.CERAS m_CERAS;

        public Form1() 
        { 
            InitializeComponent(); 
        } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
        m_CERAS = new CERas.CERAS(); 
    } 
} 


}

MSIE and addEventListener Problem in Javascript?

As of IE11, you need to use addEventListener. attachEvent is deprecated and throws an error.

Call fragment from fragment

Just do that: getTabAt(index of your tab)

        ActionBar actionBar = getSupportActionBar();
        actionBar.selectTab(actionBar.getTabAt(0));

A div with auto resize when changing window width\height

  <!DOCTYPE html>
    <html>
  <head>
  <style> 
   div {

   padding: 20px; 

   resize: both;
  overflow: auto;
   }
    img{
   height: 100%;
    width: 100%;
 object-fit: contain;
 }
 </style>
  </head>
  <body>
 <h1>The resize Property</h1>

 <div>
 <p>Let the user resize both the height and the width of this 1234567891011 div 
   element. 
  </p>
 <p>To resize: Click and drag the bottom right corner of this div element.</p>
  <img src="images/scenery.jpg" alt="Italian ">
  </div>

   <p><b>Note:</b> Internet Explorer does not support the resize property.</p>

 </body>
 </html>

How do you iterate through every file/directory recursively in standard C++?

You need to call OS-specific functions for filesystem traversal, like open() and readdir(). The C standard does not specify any filesystem-related functions.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!

To install tmux in MSYS2:

run command pacman -S tmux

To run tmux on Git Bash:

install MSYS2 and copy tmux.exe and msys-event-2-1-6.dll from MSYS2 folder C:\msys64\usr\bin to your Git Bash directory C:\Program Files\Git\usr\bin.

Trim a string based on the string length

s = s.length() > 10 ? s.substring(0, 9) : s;

How to add a custom button to the toolbar that calls a JavaScript function?

You can add the button image as follows:

CKEDITOR.plugins.add('showtime',   //name of our plugin
{    
    requires: ['dialog'], //requires a dialog window
    init:function(a) {
  var b="showtime";
  var c=a.addCommand(b,new CKEDITOR.dialogCommand(b));
  c.modes={wysiwyg:1,source:1}; //Enable our plugin in both modes
  c.canUndo=true;
 
  //add new button to the editor
  a.ui.addButton("showtime",
  {
   label:'Show current time',
   command:b,
   icon:this.path+"showtime.png"   //path of the icon
  });
  CKEDITOR.dialog.add(b,this.path+"dialogs/ab.js") //path of our dialog file
 }
});

Here is the actual plugin with all steps described.

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

How do I initialize an empty array in C#?

If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.

Use a List<string> instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray() on the variable.

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

If you must create an empty array you can do this:

string[] emptyStringArray = new string[0]; 

pandas: merge (join) two data frames on multiple columns

Another way of doing this: new_df = A_df.merge(B_df, left_on=['A_c1','c2'], right_on = ['B_c1','c2'], how='left')

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How to convert hashmap to JSON object in Java

You can convert Map to JSON using Jackson as follows:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using JSONObject library, you can convert map to JSON as follows:

Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);

JSONObject json = new JSONObject(map);
System.out.println(json);

Maven Dependencies for JSONObject :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Hope this will help. Happy coding.

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Populating a data frame in R in a loop

You could do it like this:

 iterations = 10
 variables = 2

 output <- matrix(ncol=variables, nrow=iterations)

 for(i in 1:iterations){
  output[i,] <- runif(2)

 }

 output

and then turn it into a data.frame

 output <- data.frame(output)
 class(output)

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.

Set UILabel line spacing

My solution was to patch the font file itself and fix its line height definitely. http://mbauman.net/geek/2009/03/15/minor-truetype-font-editing-on-a-mac/

I had to modify 'lineGap', 'ascender', 'descender' in the 'hhea' block (as in the blog example).

Python 3 Building an array of bytes

Here is a solution to getting an array (list) of bytes:

I found that you needed to convert the Int to a byte first, before passing it to the bytes():

bytes(int('0xA2', 16).to_bytes(1, "big"))

Then create a list from the bytes:

list(frame)

So your code should look like:

frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)

The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

Find document with array that contains a specific value

There is no $contains operator in mongodb.

You can use the answer from JohnnyHK as that works. The closest analogy to contains that mongo has is $in, using this your query would look like:

PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);

ListView item background via custom selector

The article "Why is my list black? An Android optimization" in the Android Developers Blog has a thorough explanation of why the list background turns black when scrolling. Simple answer: set cacheColorHint on your list to transparent (#00000000).

How to write an async method with out parameter?

The limitation of the async methods not accepting out parameters applies only to the compiler-generated async methods, these declared with the async keyword. It doesn't apply to hand-crafted async methods. In other words it is possible to create Task returning methods accepting out parameters. For example lets say that we already have a ParseIntAsync method that throws, and we want to create a TryParseIntAsync that doesn't throw. We could implement it like this:

public static Task<bool> TryParseIntAsync(string s, out Task<int> result)
{
    var tcs = new TaskCompletionSource<int>();
    result = tcs.Task;
    return ParseIntAsync(s).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            tcs.SetException(t.Exception.InnerException);
            return false;
        }
        tcs.SetResult(t.Result);
        return true;
    }, default, TaskContinuationOptions.None, TaskScheduler.Default);
}

Using the TaskCompletionSource and the ContinueWith method is a bit awkward, but there is no other option since we can't use the convenient await keyword inside this method.

Usage example:

if (await TryParseIntAsync("-13", out var result))
{
    Console.WriteLine($"Result: {await result}");
}
else
{
    Console.WriteLine($"Parse failed");
}

Update: If the async logic is too complex to be expressed without await, then it could be encapsulated inside a nested asynchronous anonymous delegate. A TaskCompletionSource would still be needed for the out parameter. It is possible that the out parameter could be completed before the completion of the main task, as in the example bellow:

public static Task<string> GetDataAsync(string url, out Task<int> rawDataLength)
{
    var tcs = new TaskCompletionSource<int>();
    rawDataLength = tcs.Task;
    return ((Func<Task<string>>)(async () =>
    {
        var response = await GetResponseAsync(url);
        var rawData = await GetRawDataAsync(response);
        tcs.SetResult(rawData.Length);
        return await FilterDataAsync(rawData);
    }))();
}

This example assumes the existence of three asynchronous methods GetResponseAsync, GetRawDataAsync and FilterDataAsync that are called in succession. The out parameter is completed on the completion of the second method. The GetDataAsync method could be used like this:

var data = await GetDataAsync("http://example.com", out var rawDataLength);
Console.WriteLine($"Data: {data}");
Console.WriteLine($"RawDataLength: {await rawDataLength}");

Awaiting the data before awaiting the rawDataLength is important in this simplified example, because in case of an exception the out parameter will never be completed.

Why is there an unexplainable gap between these inline-block div elements?

simply add a border: 2px solid #e60000; to your 2nd div tag CSS.

Definitely it works

#Div2Id {
    border: 2px solid #e60000; --> color is your preference
}

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

How does one extract each folder name from a path?

There are a few ways that a file path can be represented. You should use the System.IO.Path class to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:

string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                              Path.DirectorySeparatorChar);

This should work regardless of the number of folders or the names.

What does the Excel range.Rows property really do?

I'm not sure, but I think the second parameter is a red herring.

Both .Rows and .Columns take two optional parameters: RowIndex and ColumnIndex. Try to use ColumnIndex, e.g. Rows(ColumnIndex:=2), generates an error for both .Rows and .Columns.

My feeling it's inherited in some sense from the Cells(RowIndex,ColumnIndex) Property but only the first parameter is appropriate.

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

How to lose margin/padding in UITextView?

Here is an updated version of Fattie's very helpful answer. It adds 2 important lines that helped me get the layout working on iOS 10 and 11 (and probably on lower ones, too):

@IBDesignable class UITextViewFixed: UITextView {
    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
    func setup() {
        translatesAutoresizingMaskIntoConstraints = true
        textContainerInset = UIEdgeInsets.zero
        textContainer.lineFragmentPadding = 0
        translatesAutoresizingMaskIntoConstraints = false
    }
}

The important lines are the two translatesAutoresizingMaskIntoConstraints = <true/false> statements!

This surprisingly removes all margins in all my circumstances!

While the textView is not the first responder it could happen that there is some strange bottom margin that could not be solved using the sizeThatFits method that is mentioned in the accepted answer.

When tapping into the textView suddenly the strange bottom margin disappeared and everything looked like it should, but only as soon as the textView has got firstResponder.

So I read here on SO that enabling and disabling translatesAutoresizingMaskIntoConstraints does help when setting the frame/bounds manually in between the calls.

Fortunately this not only works with frame setting but with the 2 lines of setup() sandwiched between the two translatesAutoresizingMaskIntoConstraints calls!

This for example is very helpful when calculating the frame of a view using systemLayoutSizeFitting on a UIView. Gives back the correct size (which previously it didn't)!

As in the original answer mentioned:
Don't forget to turn off scrollEnabled in the Inspector!
That solution does work properly in storyboard, as well as at runtime.

That's it, now you're really done!

Typescript: How to extend two classes?

If you don't like using multi-inheritance, use extends and implements together to stay safe.

class C extends B implements A {
  // implements A here
}

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

ALTER COLUMN in sqlite

While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT 
NULL);**  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
Error: BOOKS.publication_date may not be NULL  
sqlite> **PRAGMA writable_schema = 1;**  
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT 
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**  
sqlite> **PRAGMA writable_schema = 0;**  
sqlite> **.q**  

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
sqlite> **.q**  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

How to break out or exit a method in Java?

To add to the other answers, you can also exit a method by throwing an exception manually:

throw new Exception();

enter image description here

Why is sed not recognizing \t as a tab?

@sedit was on the right path, but it's a bit awkward to define a variable.

Solution (bash specific)

The way to do this in bash is to put a dollar sign in front of your single quoted string.

$ echo -e '1\n2\n3'
1
2
3

$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3

$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
    1
    2
    3

If your string needs to include variable expansion, you can put quoted strings together like so:

$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958  1
1491237958  2
1491237958  3

Explanation

In bash $'string' causes "ANSI-C expansion". And that is what most of us expect when we use things like \t, \r, \n, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...

The expanded result is single-quoted, as if the dollar sign had not been present.

Solution (if you must avoid bash)

I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu than if you try to avoid bash and use sh [unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.

$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
    1
    2
    3

* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t' as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.

Percentage width in a RelativeLayout

You can accomplish this via layout weights. A weight dictates how the unclaimed portions of the screen are divided up. Give each EditText a layout_width of 0, and some proportional weight. I.e., give one a weight of 2, and the other a weight of 1 if you want the first to take up twice as much space.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

In C#, can a class inherit from another class and an interface?

Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.

.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.


In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:

public interface ITwo : IOne

The technical answer is that ITwo does inherit IOne for a few reasons:

  • Interfaces never have an implementation, so arguing that ITwo implements IOne is flat wrong
  • ITwo inherits IOne methods, if MethodOne() exists on IOne then it is also accesible from ITwo. i.e: ((ITwo)someObject).MethodOne()) is valid, even though ITwo does not explicitly contain a definition for MethodOne()
  • ...because the runtime says so! typeof(IOne).IsAssignableFrom(typeof(ITwo)) returns true

We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)

Invalid argument supplied for foreach()

More concise extension of @Kris's code

function secure_iterable($var)
{
    return is_iterable($var) ? $var : array();
}

foreach (secure_iterable($values) as $value)
{
     //do stuff...
}

especially for using inside template code

<?php foreach (secure_iterable($values) as $value): ?>
    ...
<?php endforeach; ?>

Can't install via pip because of egg_info error

I was trying to install pyautogui and followed instructions from the first answer but was unsuccessful. The difference for me was running pip install pillow and then running pip install pyautogui

I don't know what this means, but I hope this helps some people out.

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

Most efficient way to increment a Map value in Java

The simple and easy way in java 8 is the following:

final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();
    map.computeIfAbsent("foo", key -> new AtomicLong(0)).incrementAndGet();

How can I permanently enable line numbers in IntelliJ?

I add this response for IntelliJ IDEA 2018.2 - Ultimate.

Using menu

IntelliJ Idea > Preferences > Editor > General > Appearance > Show Line Numbers

enter image description here

Using Shortcuts - First way

For Windows : Ctrl+Shift+a
For Mac : Cmd+shift+a

enter image description here

Using Shortcuts - Seconde way

Touch Shift twice

enter image description here

These three methods exist since the last 4 versions of Intellij and I think they remain valid for a long time.

How do I set up NSZombieEnabled in Xcode 4?

Jano's answer is the easiest way to find it.. another way would be if you click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column...

How do I use Bash on Windows from the Visual Studio Code integrated terminal?


You no longer need to type in bash.exe path manually. This answer is deprecated. Now you can switch to bash directly, if you have git installed in the default path. If you installed git to a different path you need to use the below solution.


Install Git from https://git-scm.com/download/win.

Then open Visual Studio Code and open the command palette using Ctrl + Shift + P. Then type "open user setting", and then select "Open User Settings" from the drop down menu.

Visual Studio Code command palate

Then this tab will open up with default settings on left and your settings on the right:

enter image description here

Now copy this line of code to your own settings page (the pane on the right hand side) and save - "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"

Note: "C:\\Program Files\Git\bin\bash.exe" is the path where the bash.exe file is located from the Git installation. If you are using the Windows Subsystem for Linux (WSL) Bash shell, the path would be "C:\Windows\System32\bash.exe"

Now press Ctrl + ` to open up the terminal from Visual Studio Code. And you will have Bash -

Enter image description here

How to display a Windows Form in full screen on top of the taskbar?

My simple fix it turned out to be calling the form's Activate() method, so there's no need to use TopMost (which is what I was aiming at).

Add spaces between the characters of a string in Java?

  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

How to use OrderBy with findAll in Spring Data

I try in this example to show you a complete example to personalize your OrderBy sorts

 import java.util.List;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.jpa.repository.*;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 import org.springframework.data.domain.Sort;
 /**
 * Spring Data  repository for the User entity.
 */
 @SuppressWarnings("unused")
 @Repository
 public interface UserRepository extends JpaRepository<User, Long> {
 List <User> findAllWithCustomOrderBy(Sort sort);
 }

you will use this example : A method for build dynamically a object that instance of Sort :

import org.springframework.data.domain.Sort;
public class SampleOrderBySpring{
 Sort dynamicOrderBySort = createSort();
     public static void main( String[] args )
     {
       System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
       Sort defaultSort = createStaticSort();
       System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));


       String[] orderBySortedArray = {"name", "firstName"};
       System.out.println("default sort ,\"name\",\"firstName\" ");
       Sort dynamicSort = createDynamicSort(orderBySortedArray );
       System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
      }
      public Sort createDynamicSort(String[] arrayOrdre) {
        return  Sort.by(arrayOrdre);
        }

   public Sort createStaticSort() {
        String[] arrayOrdre  ={"firstName","name","age","size");
        return  Sort.by(arrayOrdre);
        }
}

Copy a git repo without history

Deleting the .git folder is probably the easiest path since you don't want/need the history (as Stephan said).

So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)

git clone <git_url>

then delete .git, and afterwards run

git init

Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?

Follow the above steps then:

git add .
git commit -m "Initial commit"

Push to your repo.

git remote add origin <github-uri>
git push -u --force origin master

Why am I getting "IndentationError: expected an indented block"?

There are in fact multiples things you need to know about indentation in Python:

Python really cares about indention.

In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.

This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.

There are different indention errors and you reading them helps a lot:

1. "IndentationError: expected an indented block"

They are two main reasons why you could have such an error:

- You have a ":" without an indented block behind.

Here are two examples:

Example 1, no indented block:

Input:

if 3 != 4:
    print("usual")
else:

Output:

  File "<stdin>", line 4

    ^
IndentationError: expected an indented block

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

Input:

if 3 != 4:
print("usual")

Output

  File "<stdin>", line 2
    print("usual")
        ^
IndentationError: expected an indented block

The output states that you need to have an indented block line 2, after the if 3 != 4: statement

- You are using Python2.x and have a mix of tabs and spaces:

Input

def foo():
    if 1:
        print 1

Please note that before if, there is a tab, and before print there is 8 spaces.

Output:

  File "<stdin>", line 3
    print 1
      ^
IndentationError: expected an indented block

It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.

  • You can get some info here.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.

2. "IndentationError: unexpected indent"

It is important to indent blocks, but only blocks that should be indent. So basically this error says:

- You have an indented block without a ":" before it.

Example:

Input:

a = 3
  a += 3

Output:

  File "<stdin>", line 2
    a += 3
    ^
IndentationError: unexpected indent

The output states that he wasn't expecting an indent block line 2, then you should remove it.

3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)

  • You can get some info here.
  • But basically it's, you are using tabs and spaces in your code.
  • You don't want that.
  • Remove all tabs and replaces them by four spaces.
  • And configure your editor to do that automatically.


Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

What does functools.wraps do?

this is the source code about wraps:

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')

WRAPPER_UPDATES = ('__dict__',)

def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):

    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    """Decorator factory to apply update_wrapper() to a wrapper function

   Returns a decorator that invokes update_wrapper() with the decorated
   function as the wrapper argument and the arguments to wraps() as the
   remaining arguments. Default arguments are as for update_wrapper().
   This is a convenience function to simplify applying partial() to
   update_wrapper().
    """
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

req.body empty on posts

A similar problem happened to me, I simply mixed the order of the callback params. Make sure your are setting up the callback functions in the correct order. At least for anyone having the same problem.

router.post('/', function(req, res){});

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

JavaScript for detecting browser language preference

Update of year 2014.

Now there is a way to get Accept-Languages in Firefox and Chrome using navigator.languages (works in Chrome >= 32 and Firefox >= 32)

Also, navigator.language in Firefox these years reflects most preferred language of content, not language of UI. But since this notion is yet to be supported by other browsers, it is not very useful.

So, to get most preferred content language when possible, and use UI language as fallback:

navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)

Accessing dict_keys element by index in Python3

I wanted "key" & "value" pair of a first dictionary item. I used the following code.

 key, val = next(iter(my_dict.items()))

Remove part of string in Java

// Java program to remove a substring from a string
public class RemoveSubString {

    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";

        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

        System.out.println(master);
        System.out.println(new_string);

    }
}

String concatenation: concat() vs "+" operator

Basically, there are two important differences between + and the concat method.

  1. If you are using the concat method then you would only be able to concatenate strings while in case of the + operator, you can also concatenate the string with any data type.

    For Example:

    String s = 10 + "Hello";
    

    In this case, the output should be 10Hello.

    String s = "I";
    String s1 = s.concat("am").concat("good").concat("boy");
    System.out.println(s1);
    

    In the above case you have to provide two strings mandatory.

  2. The second and main difference between + and concat is that:

    Case 1: Suppose I concat the same strings with concat operator in this way

    String s="I";
    String s1=s.concat("am").concat("good").concat("boy");
    System.out.println(s1);
    

    In this case total number of objects created in the pool are 7 like this:

    I
    am
    good
    boy
    Iam
    Iamgood
    Iamgoodboy
    

    Case 2:

    Now I am going to concatinate the same strings via + operator

    String s="I"+"am"+"good"+"boy";
    System.out.println(s);
    

    In the above case total number of objects created are only 5.

    Actually when we concatinate the strings via + operator then it maintains a StringBuffer class to perform the same task as follows:-

    StringBuffer sb = new StringBuffer("I");
    sb.append("am");
    sb.append("good");
    sb.append("boy");
    System.out.println(sb);
    

    In this way it will create only five objects.

So guys these are the basic differences between + and the concat method. Enjoy :)

How to convert a huge list-of-vector to a matrix more efficiently?

you can use as.matrix as below:

output <- as.matrix(z)

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

Creating a very simple 1 username/password login in php

Firstly, you need to put session_start(); before any output to the browser, normally at the top of the page. Have a look at the manual.

Second, this won't affect your results, but these lines aren't being used anywhere and should be removed:

$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';

...and the last two lines there wouldn't work, you need to put the quotes inside the square brackets:

$username = $_POST['username'];

If you put session_start() at the top of your page (i.e. before the <html> tag etc), this should work fine.

Background thread with QThread in PyQt

Based on the Worker objects methods mentioned in other answers, I decided to see if I could expand on the solution to invoke more threads - in this case the optimal number the machine can run and spin up multiple workers with indeterminate completion times. To do this I still need to subclass QThread - but only to assign a thread number and to 'reimplement' the signals 'finished' and 'started' to include their thread number.

I've focused quite a bit on the signals between the main gui, the threads, and the workers.

Similarly, others answers have been a pains to point out not parenting the QThread but I don't think this is a real concern. However, my code also is careful to destroy the QThread objects.

However, I wasn't able to parent the worker objects so it seems desirable to send them the deleteLater() signal, either when the thread function is finished or the GUI is destroyed. I've had my own code hang for not doing this.

Another enhancement I felt was necessary was was reimplement the closeEvent of the GUI (QWidget) such that the threads would be instructed to quit and then the GUI would wait until all the threads were finished. When I played with some of the other answers to this question, I got QThread destroyed errors.

Perhaps it will be useful to others. I certainly found it a useful exercise. Perhaps others will know a better way for a thread to announce it identity.

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  To demonstrate creation of multiple threads and identify the receipt of thread results
# Created: 19/12/15

import sys


from PyQt4.QtCore import QThread, pyqtSlot, pyqtSignal
from PyQt4.QtGui import QApplication, QLabel, QWidget, QGridLayout

import sys
import worker

class Thread(QThread):
    #make new signals to be able to return an id for the thread
    startedx = pyqtSignal(int)
    finishedx = pyqtSignal(int)

    def __init__(self,i,parent=None):
        super().__init__(parent)
        self.idd = i

        self.started.connect(self.starttt)
        self.finished.connect(self.finisheddd)

    @pyqtSlot()
    def starttt(self):
        print('started signal from thread emitted')
        self.startedx.emit(self.idd) 

    @pyqtSlot()
    def finisheddd(self):
        print('finished signal from thread emitted')
        self.finishedx.emit(self.idd)

class Form(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

        self.worker={}
        self.threadx={}
        self.i=0
        i=0

        #Establish the maximum number of threads the machine can optimally handle
        #Generally relates to the number of processors

        self.threadtest = QThread(self)
        self.idealthreadcount = self.threadtest.idealThreadCount()

        print("This machine can handle {} threads optimally".format(self.idealthreadcount))

        while i <self.idealthreadcount:
            self.setupThread(i)
            i+=1

        i=0
        while i<self.idealthreadcount:
            self.startThread(i)
            i+=1

        print("Main Gui running in thread {}.".format(self.thread()))


    def setupThread(self,i):

        self.worker[i]= worker.Worker(i)  # no parent!
        #print("Worker object runningt in thread {} prior to movetothread".format(self.worker[i].thread()) )
        self.threadx[i] = Thread(i,parent=self)  #  if parent isn't specified then need to be careful to destroy thread 
        self.threadx[i].setObjectName("python thread{}"+str(i))
        #print("Thread object runningt in thread {} prior to movetothread".format(self.threadx[i].thread()) )
        self.threadx[i].startedx.connect(self.threadStarted)
        self.threadx[i].finishedx.connect(self.threadFinished)

        self.worker[i].finished.connect(self.workerFinished)
        self.worker[i].intReady.connect(self.workerResultReady)

        #The next line is optional, you may want to start the threads again without having to create all the code again.
        self.worker[i].finished.connect(self.threadx[i].quit)

        self.threadx[i].started.connect(self.worker[i].procCounter)

        self.destroyed.connect(self.threadx[i].deleteLater)
        self.destroyed.connect(self.worker[i].deleteLater)

        #This is the key code that actually get the worker code onto another processor or thread.
        self.worker[i].moveToThread(self.threadx[i])

    def startThread(self,i):
        self.threadx[i].start()

    @pyqtSlot(int)
    def threadStarted(self,i):
        print('Thread {}  started'.format(i))
        print("Thread priority is {}".format(self.threadx[i].priority()))        


    @pyqtSlot(int)
    def threadFinished(self,i):
        print('Thread {} finished'.format(i))




    @pyqtSlot(int)
    def threadTerminated(self,i):
        print("Thread {} terminated".format(i))

    @pyqtSlot(int,int)
    def workerResultReady(self,j,i):
        print('Worker {} result returned'.format(i))
        if i ==0:
            self.label1.setText("{}".format(j))
        if i ==1:
            self.label2.setText("{}".format(j))
        if i ==2:
            self.label3.setText("{}".format(j))
        if i ==3:
            self.label4.setText("{}".format(j)) 

        #print('Thread {} has started'.format(self.threadx[i].currentThreadId()))    

    @pyqtSlot(int)
    def workerFinished(self,i):
        print('Worker {} finished'.format(i))

    def initUI(self):
        self.label1 = QLabel("0")
        self.label2= QLabel("0")
        self.label3= QLabel("0")
        self.label4 = QLabel("0")
        grid = QGridLayout(self)
        self.setLayout(grid)
        grid.addWidget(self.label1,0,0)
        grid.addWidget(self.label2,0,1) 
        grid.addWidget(self.label3,0,2) 
        grid.addWidget(self.label4,0,3) #Layout parents the self.labels

        self.move(300, 150)
        self.setGeometry(0,0,300,300)
        #self.size(300,300)
        self.setWindowTitle('thread test')
        self.show()

    def closeEvent(self, event):
        print('Closing')

        #this tells the threads to stop running
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].quit()
            i+=1

         #this ensures window cannot be closed until the threads have finished.
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].wait() 
            i+=1        


        event.accept()


if __name__=='__main__':
    app = QApplication(sys.argv)
    form = Form()
    sys.exit(app.exec_())

And the worker code below

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  Stack Overflow
# Created: 19/12/15

import sys
import unittest


from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
import random


class Worker(QObject):
    finished = pyqtSignal(int)
    intReady = pyqtSignal(int,int)

    def __init__(self, i=0):
        '''__init__ is called while the worker is still in the Gui thread. Do not put slow or CPU intensive code in the __init__ method'''

        super().__init__()
        self.idd = i



    @pyqtSlot()
    def procCounter(self): # This slot takes no params
        for j in range(1, 10):
            random_time = random.weibullvariate(1,2)
            time.sleep(random_time)
            self.intReady.emit(j,self.idd)
            print('Worker {0} in thread {1}'.format(self.idd, self.thread().idd))

        self.finished.emit(self.idd)


if __name__=='__main__':
    unittest.main()

VB.NET - If string contains "value1" or "value2"

You have to do it like this:

If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
    '[Put Code Here]
End if

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

HTML button calling an MVC Controller and Action method

This is how you can submit your form to a specific controller and action method in Razor.

 <input type="submit" value="Upload" onclick="location.href='@Url.Action("ActionName", "ControllerName")'" />

ImportError: No module named sqlalchemy

I just experienced the same problem using the virtual environment. For me installing the package using python from the venv worked:
.\venv\environment\Scripts\python.exe -m pip install flask-sqlalchemy

Constructor overloading in Java - best practice

I think the best practice is to have single primary constructor to which the overloaded constructors refer to by calling this() with the relevant parameter defaults. The reason for this is that it makes it much clearer what is the constructed state of the object is - really you can think of the primary constructor as the only real constructor, the others just delegate to it

One example of this might be JTable - the primary constructor takes a TableModel (plus column and selection models) and the other constructors call this primary constructor.

For subclasses where the superclass already has overloaded constructors, I would tend to assume that it is reasonable to treat any of the parent class's constructors as primary and think it is perfectly legitimate not to have a single primary constructor. For example,when extending Exception, I often provide 3 constructors, one taking just a String message, one taking a Throwable cause and the other taking both. Each of these constructors calls super directly.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

Make sure that the database is created. I got the same error when I applied the migration to the wrong project in the solution. When I applied the migration to the right project, it created the database and that solved the error.

When to throw an exception?

There are two main classes of exception:

1) System exception (eg Database connection lost) or 2) User exception. (eg User input validation, 'password is incorrect')

I found it helpful to create my own User Exception Class and when I want to throw a user error I want to be handled differently (ie resourced error displayed to the user) then all I need do in my main error handler is check the object type:

            If TypeName(ex) = "UserException" Then
               Display(ex.message)
            Else
               DisplayError("An unexpected error has occured, contact your help  desk")                   
               LogError(ex)
            End If

pop/remove items out of a python tuple

The best solution is the tuple applied to a list comprehension, but to extract one item this could work:

def pop_tuple(tuple, n): return tuple[:n]+tuple[n+1:], tuple[n]

How to indent a few lines in Markdown markup?

Please use hard (non-breaking) spaces

Why use another markup language? (I Agree with @c z above).
One goal of Markdown is to make the documents readable even in a plain text editor.

Same result two approaches

The code

Sample code
&nbsp;&nbsp;&nbsp;&nbsp;5th position in an really ugly code  
    5th position in a clear an readable code  
    Again using non-breaking spaces :)

The result

Sample code
    5th position in an really ugly code
    5th position in a clear an readable code
    Again using non-breaking spaces :)

The visual representation of a non-breaking space (or hard space) is usually a normal space " ", however, its Unicode representation is U+00A0.
The Unicode representation of the ordinary space is U+0020 (32 in the ASCII Table).
Thus, text processors may behave differently while the visual representation remains the same.

Insert a hard space

| OS        | Input method                      |
|===========| ==================================|
| macOS     | OPTION+SPACE (ALT+SPACE)          |
| Linux     | Compose Space Space or AltGr+Space|
| Windows   | Alt+0+1+6+0                       |

Some text editor use Ctrl+Shift+Space.

Issue

Some text editors can convert hard spaces to common spaces in copying and pasting operations, so be careful.

Correct way to delete cookies server-side

Sending the same cookie value with ; expires appended will not destroy the cookie.

Invalidate the cookie by setting an empty value and include an expires field as well:

Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT

Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem.

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

Laravel 5: Display HTML with Blade

To add further explanation, code inside Blade {{ }} statements are automatically passed through the htmlspecialchars() function that php provides. This function takes in a string and will find all reserved characters that HTML uses. Reserved characters are & < > and ". It will then replace these reserved characters with their HTML entity variant. Which are the following:

|---------------------|------------------|
|      Character      |       Entity     |
|---------------------|------------------|
|          &          |       &amp;      |
|---------------------|------------------|
|          <          |       &lt;       |
|---------------------|------------------|
|          >          |       &gt;       |
|---------------------|------------------|
|          "          |       &quot;     |
|---------------------|------------------|

For example, assume we have the following php statement:

$hello = "<b>Hello</b>";

Passed into blade as {{ $hello }} would yield the literal string you passed:

<b>Hello</b>

Under the hood, it would actually echo as &lt;b&gt;Hello&lt;b&gt

If we wanted to bypass this and actually render it as a bold tag, we escape the htmlspecialchars() function by adding the escape syntax blade provides:

{!! $hello !!}

Note that we only use one curly brace.

The output of the above would yield:

Hello

We could also utilise another handy function that php provides, which is the html_entity_decode() function. This will convert HTML entities to their respected HTML characters. Think of it as the reverse of htmlspecialchars()

For example say we have the following php statement:

$hello = "&lt;b&gt; Hello &lt;b&gt;";

We could now add this function to our escaped blade statement:

{!! html_entity_decode($hello) !!}

This will take the HTML entity &lt; and parse it as HTML code <, not just a string.

The same will apply with the greater than entity &gt;

which would yield

Hello

The whole point of escaping in the first place is to avoid XSS attacks. So be very careful when using escape syntax, especially if users in your application are providing the HTML themselves, they could inject their own code as they please.

Setting selected option in laravel form

Setting selected option is very simple in laravel form :

{{ Form::select('number', [0, 1, 2], 2) }}

Output will be :

<select name="number">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
</select>

javascript regex - look behind alternative?

^(?!filename).+\.js works for me

tested against:

  • test.js match
  • blabla.js match
  • filename.js no match

A proper explanation for this regex can be found at Regular expression to match string not containing a word?

Look ahead is available since version 1.5 of javascript and is supported by all major browsers

Updated to match filename2.js and 2filename.js but not filename.js

(^(?!filename\.js$).).+\.js

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

You need to have everything in the hpp file. The problem is that the classes aren't actually created until the compiler sees that they're needed by some OTHER cpp file - so it has to have all the code available to compile the templated class at that time.

One thing that I tend to do is to try to split my templates into a generic non-templated part (which can be split between cpp/hpp) and the type-specific template part which inherits the non-templated class.

Maven Installation OSX Error Unsupported major.minor version 51.0

The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

In my case my JDK installation is jdk1.8.0_40, make sure you type yours.

Then you can use maven commands.

Regards!

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

Python - Get Yesterday's date as a string in YYYY-MM-DD format

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

jQuery: how to trigger anchor link's click event

$(":button").click(function () {                
                $("#anchor_google")[0].click();
            });
  1. First, find the button by type(using ":") if id is not given.
  2. Second,find the anchor tag by id or in some other tag like div and $("#anchor_google")[0] returns the DOM object.

How to send a model in jQuery $.ajax() post request to MVC controller method

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I don't have enough reputation points to comment on @greg's answer above, so will add my observations here. I have a Swift project for both iPad and iPhone. I have a method inside my main view controller (relevant bit below). When I test this on a phone, everything works properly and no warnings are generated. When I run it on an iPad, everything works properly but I see the warning about snapshotting the view. The interesting bit, however, is that when I run on an iPad without using the popover controller, everything works properly with no warning. Unfortunately, Apple mandates that the image picker must be used within a popover on iPad, if the camera is not being used.

    dispatch_async(dispatch_get_main_queue(), {
        let imagePicker: UIImagePickerController = UIImagePickerController();
        imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        imagePicker.mediaTypes = [kUTTypeImage];
        imagePicker.allowsEditing = false;
        imagePicker.delegate = self;

        if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){ // on a tablet, the image picker is supposed to be in a popover
            let popRect: CGRect = buttonRect;
            let popover: UIPopoverController = UIPopoverController(contentViewController: imagePicker);
            popover.presentPopoverFromRect(popRect, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true);
        }else{
            self.presentViewController(imagePicker, animated: true, completion: nil);
        }
    });

How to search for an element in a golang slice

With a simple for loop:

for _, v := range myconfig {
    if v.Key == "key1" {
        // Found!
    }
}

Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

It would be faster to use a range loop just on the index, this avoids copying the elements:

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
    }
}

Notes:

It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
        break
    }
}

Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
    confMap[v.Key] = v.Value
}

// And then to find values by key:
if v, ok := confMap["key1"]; ok {
    // Found
}

How to get a string between two characters?

By using regular expression :

 String s = "test string (67)";
 Pattern p = Pattern.compile("\\(.*?\\)");
 Matcher m = p.matcher(s);
 if(m.find())
    System.out.println(m.group().subSequence(1, m.group().length()-1)); 

Simple dictionary in C++

If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:

char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }

It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.

Lombok annotations do not compile under Intellij idea

If you're using Intellij on Mac, this setup finally worked for me.

Installations: Intellij

  1. Go to Preferences, search for Plugins.
  2. Type "Lombok" in the plugin search box. Lombok is a non-bundled plugin, so it won't show at first.
  3. Click "Browse" to search for non-bundled plugins
  4. The "Lombok Plugin" should show up. Select it.
  5. Click the green "Install" button.
  6. Click the "Restart Intellij IDEA" button.

Settings:

  1. Enable Annotation processor

    • Go to Preferences -> Build, Execution,Deployment -->Preferences -> Compiler -> Annotation Processors
    • File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors
  2. Check if Lombok plugin is enabled

    • IntelliJ IDEA-> Preferences -> Other Settings -> Lombok plugin -> Enable Lombok
  3. Add Lombok jar in Global Libraries and project dependencies.

    • File --> Project Structure --> Global libraries (Add lombok.jar)
  4. File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok

  5. Restart Intellij

Unlink of file Failed. Should I try again?

If you're using Docker and running Windows 10, you may want to stop the container(s) where the file may be running at. To show the statuses of your containers, run

docker ps -a

To stop them, simply run

docker stop <container name or container id>

This worked for me as I am running my local files using a .sh file

What is the difference between smoke testing and sanity testing?

Smoke testing

Suppose a new build of an app is ready from the development phase.

We check if we are able to open the app without a crash. We login to the app. We check if the user is redirected to the proper URL and that the environment is stable. If the main aim of the app is to provide a "purchase" functionality to the user, check if the user's ID is redirected to the buying page.

After the smoke testing we confirm the build is in a testable form and is ready to go through sanity testing.

Sanity testing

In this phase, we check the basic functionalities, like

  1. login with valid credentials,
  2. login with invalid credentials,
  3. user's info are properly displayed after logging in,
  4. making a purchase order with a certain user's id,
  5. the "thank you" page is displayed after the purchase

redirect COPY of stdout to log file from within bash script itself

Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:

# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe

# Rest of my script

This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.

Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.

Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

PySpark: multiple conditions in when clause

You get SyntaxError error exception because Python has no && operator. It has and and & where the latter one is the correct choice to create boolean expressions on Column (| for a logical disjunction and ~ for logical negation).

Condition you created is also invalid because it doesn't consider operator precedence. & in Python has a higher precedence than == so expression has to be parenthesized.

(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>

On a side note when function is equivalent to case expression not WHEN clause. Still the same rules apply. Conjunction:

df.where((col("foo") > 0) & (col("bar") < 0))

Disjunction:

df.where((col("foo") > 0) | (col("bar") < 0))

You can of course define conditions separately to avoid brackets:

cond1 = col("Age") == "" 
cond2 = col("Survived") == "0"

cond1 & cond2

Linking to an external URL in Javadoc?

Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java:

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT = "Accept";

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT_CHARSET = "Accept-Charset";

Maintain model of scope when changing between views in AngularJS

Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons

UI Router & UI Router Extras

These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.

Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.

How to reload a page using JavaScript

This should work:

window.location.href = window.location.href.split( '#' )[0];

or

var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];

I prefer this for the following reasons:

  • Removes the part after the #, ensuring the page reloads on browsers that won't reload content that has it.
  • It doesn't ask you if want to repost last content if you recently submit a form.
  • It should work even on most recent browsers. Tested on Lasted Firefox and Chrome.

Alternatively, you may use the most recent official method for this task

window.location.reload()

Create a folder if it doesn't already exist

I need the same thing for a login site. I needed to create a directory with a two variables. The $directory is the main folder where I wanted to create another sub-folder with the users license number.

include_once("../include/session.php");
$lnum = $session->lnum; //Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in

if (!file_exists($directory."/".$lnum)) {
mkdir($directory."/".$lnum, 0777, true);
}

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

Responsive width Facebook Page Plugin

Hi everybody!

My version with a live demonstration(native JavaScript):

1). Javascript code in a separate file (the best solution):

Codepen

_x000D_
_x000D_
/* Vanilla JS */_x000D_
function setupFBframe(frame) {_x000D_
  var container = frame.parentNode;_x000D_
_x000D_
  var containerWidth = container.offsetWidth;_x000D_
  var containerHeight = container.offsetHeight;_x000D_
_x000D_
  var src =_x000D_
    "https://www.facebook.com/plugins/page.php" +_x000D_
    "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
    "&tabs=timeline" +_x000D_
    "&width=" +_x000D_
    containerWidth +_x000D_
    "&height=" +_x000D_
    containerHeight +_x000D_
    "&small_header=false" +_x000D_
    "&adapt_container_width=false" +_x000D_
    "&hide_cover=true" +_x000D_
    "&hide_cta=true" +_x000D_
    "&show_facepile=true" +_x000D_
    "&appId";_x000D_
_x000D_
  frame.width = containerWidth;_x000D_
  frame.height = containerHeight;_x000D_
  frame.src = src;_x000D_
}_x000D_
_x000D_
/* begin Document Ready                                _x000D_
############################################ */_x000D_
_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  var facebookIframe = document.querySelector('#facebook_iframe');_x000D_
  setupFBframe(facebookIframe);_x000D_
 _x000D_
  /* begin Window Resize                                _x000D_
  ############################################ */_x000D_
  _x000D_
  // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
  (function() {_x000D_
    window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
    var resizeTimeout;_x000D_
_x000D_
    function resizeThrottler() {_x000D_
      if (!resizeTimeout) {_x000D_
        resizeTimeout = setTimeout(function() {_x000D_
          resizeTimeout = null;_x000D_
          actualResizeHandler();_x000D_
        }, 66);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function actualResizeHandler() {_x000D_
      document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
      setupFBframe(facebookIframe);_x000D_
    }_x000D_
  })();_x000D_
  /* end Window Resize_x000D_
  ############################################ */_x000D_
});_x000D_
/* end Document Ready                                _x000D_
############################################ */
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
    ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2). Javascript code is written in HTML:

Codepen

_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');_x000D_
body {_x000D_
  font-family: 'Indie Flower', cursive;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  max-width: 1170px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.left_sidebar {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 30%;_x000D_
  max-width: 300px;_x000D_
}_x000D_
_x000D_
.main_content {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 70%;_x000D_
  background-color: #DDEFF7;_x000D_
}_x000D_
_x000D_
_x000D_
/* ------- begin Widget Facebook -------------- */_x000D_
_x000D_
.widget--facebook--container {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.widget-facebook {_x000D_
  height: 500px;_x000D_
}_x000D_
_x000D_
.widget-facebook .facebook_iframe {_x000D_
  border: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* ---------- end Widget Facebook---------------- */_x000D_
_x000D_
_x000D_
/* ----------------- no need -------------------- */_x000D_
_x000D_
.block {_x000D_
  color: #fff;_x000D_
  height: 300px;_x000D_
  background-color: #00A7F7;_x000D_
  border: 1px solid #005dff;_x000D_
}_x000D_
_x000D_
.block h3 {_x000D_
  line-height: 300px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<!-- Vanilla JS -->_x000D_
<!-- Min. responsive 180px -->_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <div class="left_sidebar">_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
      <!-- begin Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="widget--facebook--container">_x000D_
        <div class="widget-facebook">_x000D_
          <script>_x000D_
            function setupFBframe(frame) {_x000D_
              if (frame.src) return; // already set up_x000D_
_x000D_
              var container = frame.parentNode;_x000D_
              console.log(frame.parentNode);_x000D_
_x000D_
              var containerWidth = container.offsetWidth;_x000D_
              var containerHeight = container.offsetHeight;_x000D_
_x000D_
              var src =_x000D_
                "https://www.facebook.com/plugins/page.php" +_x000D_
                "?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook" +_x000D_
                "&tabs=timeline" +_x000D_
                "&width=" +_x000D_
                containerWidth +_x000D_
                "&height=" +_x000D_
                containerHeight +_x000D_
                "&small_header=false" +_x000D_
                "&adapt_container_width=false" +_x000D_
                "&hide_cover=true" +_x000D_
                "&hide_cta=true" +_x000D_
                "&show_facepile=true" +_x000D_
                "&appId";_x000D_
_x000D_
              frame.width = containerWidth;_x000D_
              frame.height = containerHeight;_x000D_
              frame.src = src;_x000D_
            }_x000D_
_x000D_
            var facebookIframe;_x000D_
_x000D_
            /* begin Window Resize                                _x000D_
            ############################################ */_x000D_
_x000D_
            // Why resizeThrottler? See more : https://developer.mozilla.org/ru/docs/Web/Events/resize_x000D_
            (function() {_x000D_
              window.addEventListener("resize", resizeThrottler, false);_x000D_
_x000D_
              var resizeTimeout;_x000D_
_x000D_
              function resizeThrottler() {_x000D_
                if (!resizeTimeout) {_x000D_
                  resizeTimeout = setTimeout(function() {_x000D_
                    resizeTimeout = null;_x000D_
                    actualResizeHandler();_x000D_
                  }, 66);_x000D_
                }_x000D_
              }_x000D_
_x000D_
              function actualResizeHandler() {_x000D_
                document.querySelector('#facebook_iframe').removeAttribute('src');_x000D_
                setupFBframe(facebookIframe);_x000D_
              }_x000D_
            })();_x000D_
            /* end Window Resize_x000D_
            ############################################ */_x000D_
          </script>_x000D_
          <iframe id="facebook_iframe" class="facebook_iframe" onload="facebookIframe = this; setupFBframe(facebookIframe)"></iframe>_x000D_
        </div>_x000D_
      </aside>_x000D_
      <!-- end Widget Facebook_x000D_
      ========================================= -->_x000D_
      <aside class="block">_x000D_
        <h3>Content</h3>_x000D_
      </aside>_x000D_
    </div>_x000D_
    <div class="main_content">_x000D_
      <h1>Responsive width Facebook Page Plugin</h1>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum earum, temporibus, maxime repudiandae obcaecati veritatis, odio dolore provident tenetur perferendis ipsam, rem esse vitae laudantium voluptatem iste aliquam optio ab.</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Thanks storsoc!

All the best to you all and have a nice day!

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

This code worked for me

public static void main(String[] args) {
    try {
        java.net.URL myUr = new java.net.URL("http://path");
        System.out.println("Instantiated new URL: " + connection_url);
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

Instantiated new URL: http://path

UTF-8 encoded html pages show ? (questions marks) instead of characters

Check if any of your .php files which printing some text, also is correctly encoding in utf-8.

CSS Div stretch 100% page height

I want to cover the whole web page before prompting a modal popup. I tried many methods using CSS and Javascript but none of them help until I figure out the following solution. It works for me, I hope it helps you too.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
 <head>_x000D_
  <style>_x000D_
   html, body {_x000D_
       margin: 0px 0px;_x000D_
       height 100%;_x000D_
   }_x000D_
          _x000D_
            div.full-page {_x000D_
                position: fixed;_x000D_
                top: 0;_x000D_
                bottom: 0;_x000D_
                width: 100%;_x000D_
                height: 100%;_x000D_
                background-color: #000;_x000D_
                opacity:0.8;_x000D_
                overflow-y: hidden;_x000D_
                overflow-x: hidden;_x000D_
            }_x000D_
          _x000D_
            div.full-page div.avoid-content-highlight {_x000D_
                position: relative;_x000D_
                width: 100%;_x000D_
                height: 100%;_x000D_
            }_x000D_
          _x000D_
            div.modal-popup {_x000D_
                position: fixed;_x000D_
                top: 20%;_x000D_
                bottom: 20%;_x000D_
                left: 30%;_x000D_
                right: 30%;_x000D_
                background-color: #FFF;_x000D_
                border: 1px solid #000;_x000D_
            }_x000D_
  </style>_x000D_
  <script>_x000D_
  _x000D_
   // Polling for the sake of my intern tests_x000D_
   var interval = setInterval(function() {_x000D_
    if(document.readyState === 'complete') {_x000D_
     clearInterval(interval);_x000D_
     isReady();_x000D_
    }    _x000D_
   }, 1000);_x000D_
   _x000D_
   function isReady() {_x000D_
    document.getElementById('btn1').disabled = false;_x000D_
    document.getElementById('btn2').disabled = false;_x000D_
    _x000D_
    // disable scrolling_x000D_
                document.getElementsByTagName('body')[0].style.overflow = 'hidden';_x000D_
   }_x000D_
   _x000D_
   function promptModalPopup() {_x000D_
                document.getElementById("div1").style.visibility = 'visible';_x000D_
                document.getElementById("div2").style.visibility = 'visible';_x000D_
    _x000D_
    // disable scrolling_x000D_
                document.getElementsByTagName('body')[0].style.overflow = 'hidden';_x000D_
            }_x000D_
          _x000D_
            function closeModalPopup() {_x000D_
                document.getElementById("div2").style.visibility = 'hidden';  _x000D_
                document.getElementById("div1").style.visibility = 'hidden';_x000D_
    _x000D_
    // enable scrolling_x000D_
                document.getElementsByTagName('body')[0].style.overflow = 'scroll';_x000D_
            }_x000D_
  </script>_x000D_
  _x000D_
 </head>_x000D_
 <body id="body">_x000D_
  <div id="div1" class="full-page">_x000D_
   <div class="avoid-content-highlight">_x000D_
                _x000D_
            </div>_x000D_
  </div>_x000D_
        <button id="btn1" onclick="promptModalPopup()" disabled>Prompt Modal Popup</button>_x000D_
  <div id="demo">_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
   <h2>Original content</h2>_x000D_
  </div>_x000D_
        <div id="div2" class="modal-popup">_x000D_
            I am on top of all other containers_x000D_
            <button id="btn2" onclick="closeModalPopup()" disabled>Close</button>_x000D_
        <div>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Good luck ;-)

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Answer

You need to create a header with a proper formatted User agent String, it server to communicate client-server.

You can check your own user agent Here.

Example

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0

Third party Package user_agent 0.1.9

I found this module very simple to use, in one line of code it randomly generates a User agent string.

from user_agent import generate_user_agent, generate_navigator
from pprint import pprint

print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'

print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'

pprint(generate_navigator())

# {'app_code_name': 'Mozilla',
#  'app_name': 'Netscape',
#  'appversion': '5.0',
#  'name': 'firefox',
#  'os': 'linux',
#  'oscpu': 'Linux i686 on x86_64',
#  'platform': 'Linux i686 on x86_64',
#  'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
#  'version': '41.0'}

pprint(generate_navigator_js())

# {'appCodeName': 'Mozilla',
#  'appName': 'Netscape',
#  'appVersion': '38.0',
#  'platform': 'MacIntel',
#  'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}

Facebook development in localhost

Edit: 2-15-2012 This is how to use FB authentication for a localhost website.

I find it more scalable and convenient to set up a second Facebook app. If I'm building MyApp, then I'll make a second one called MyApp-dev.

  • Create a new app at https://developers.facebook.com/apps
  • (New 2/15/2012) Click the Website checkbox under 'Select how your application integrates with Facebook' (In the recent Facebook version you can find this under Settings > Basic > Add Platform - Then select website)
  • Set the Site URL field (NOT the App Domains field) to http://www.localhost:3000 (this address is for Ruby on Rails, change as needed)

enter image description here

  • In your application initializer, put in code to detect the environment
    • Sample Rails 3 code
      if Rails.env == 'development' || Rails.env == 'test'
        Rails.application.config.middleware.use OmniAuth::Builder do
          provider :facebook, 'DEV_APP_ID', 'DEV_APP_SECRET'
        end
      else
        # Production
        Rails.application.config.middleware.use OmniAuth::Builder do
          provider :facebook, 'PRODUCTION_APP_ID', 'PRODUCTION_APP_SECRET'
        end
      end
      

I prefer this method because once it's set up, coworkers and other machines don't have additional setup.

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

Storing database records into array

$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;
  $c++;
}

for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}

Python Script Uploading files via FTP

You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.

import ftplib
import os

def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
    myFTP = ftplib.FTP(server, username, password)
    if destinationDirectory in [name for name, data in list(remote.mlsd())]:
        print "Destination Directory does not exist. Creating it first"
        myFTP.mkd(destinationDirectory)
    # Changing Working Directory
    myFTP.cwd(destinationDirectory)
    if os.path.isfile(sourceFilePath):
        fh = open(sourceFilePath, 'rb')
        myFTP.storbinary('STOR %s' % f, fh)
        fh.close()
    else:
        print "Source File does not exist"

How to set maximum height for table-cell?

By CSS 2.1 rules, the height of a table cell is “the minimum height required by the content”. Thus, you need to restrict the height indirectly using inner markup, normally a div element (<td><div>content</div></td>), and set height and overflow properties on the the div element (without setting display: table-cell on it, of course, as that would make its height obey CSS 2.1 table cell rules).

Why do we have to override the equals() method in Java?

.equals() doesn't perform an intelligent comparison for most classes unless the class overrides it. If it's not defined for a (user) class, it behaves the same as ==.

Reference: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html http://www.leepoint.net/data/expressions/22compareobjects.html

Java compiler level does not match the version of the installed Java project facet

Assuming that you are using the m2e plugin in Eclipse, you'll need to specify the source and target versions as 1.6 for maven-compiler-plugin. m2e uses these values to determine the project's Java compiler level. A snippet of the POM is shown below:

<build>
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
    </plugin>
  </plugins>
</build>

Alternatively, you can specify the maven.compiler.source and maven.compiler.target properties with values of 1.6, that happen to be the equivalent:

<properties>
    <maven.compiler.target>1.6</maven.compiler.target>
    <maven.compiler.source>1.6</maven.compiler.source>
</properties>

How do I prevent an Android device from going to sleep programmatically?

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

Get difference between 2 dates in JavaScript?

Here is one way:

_x000D_
_x000D_
const date1 = new Date('7/13/2010');_x000D_
const date2 = new Date('12/15/2010');_x000D_
const diffTime = Math.abs(date2 - date1);_x000D_
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); _x000D_
console.log(diffTime + " milliseconds");_x000D_
console.log(diffDays + " days");
_x000D_
_x000D_
_x000D_

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

How to debug Lock wait timeout exceeded on MySQL?

The big problem with this exception is that its usually not reproducible in a test environment and we are not around to run innodb engine status when it happens on prod. So in one of the projects I put the below code into a catch block for this exception. That helped me catch the engine status when the exception happened. That helped a lot.

Statement st = con.createStatement();
ResultSet rs =  st.executeQuery("SHOW ENGINE INNODB STATUS");
while(rs.next()){
    log.info(rs.getString(1));
    log.info(rs.getString(2));
    log.info(rs.getString(3));
}

Jquery: how to trigger click event on pressing enter key

Try This

$('#twitterSearch').keydown(function(event){ 
    var keyCode = (event.keyCode ? event.keyCode : event.which);   
    if (keyCode == 13) {
        $('#startSearch').trigger('click');
    }
});

Hope it helps you

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Codeigniter displays a blank page instead of error messages

If you're using CI 2.0 or newer, you could change ENVIRONMENT type in your index.php to define('ENVIRONMENT', 'testing');.
Alternatively, you could add php_flag display_errors on to your .htaccess file.

Threads vs Processes in Linux

Threads -- > Threads shares a memory space,it is an abstraction of the CPU,it is lightweight. Processes --> Processes have their own memory space,it is an abstraction of a computer. To parallelise task you need to abstract a CPU. However the advantages of using a process over a thread is security,stability while a thread uses lesser memory than process and offers lesser latency. An example in terms of web would be chrome and firefox. In case of Chrome each tab is a new process hence memory usage of chrome is higher than firefox ,while the security and stability provided is better than firefox. The security here provided by chrome is better,since each tab is a new process different tab cannot snoop into the memory space of a given process.

Should import statements always be at the top of a module?

I have adopted the practice of putting all imports in the functions that use them, rather than at the top of the module.

The benefit I get is the ability to refactor more reliably. When I move a function from one module to another, I know that the function will continue to work with all of its legacy of testing intact. If I have my imports at the top of the module, when I move a function, I find that I end up spending a lot of time getting the new module's imports complete and minimal. A refactoring IDE might make this irrelevant.

There is a speed penalty as mentioned elsewhere. I have measured this in my application and found it to be insignificant for my purposes.

It is also nice to be able to see all module dependencies up front without resorting to search (e.g. grep). However, the reason I care about module dependencies is generally because I'm installing, refactoring, or moving an entire system comprising multiple files, not just a single module. In that case, I'm going to perform a global search anyway to make sure I have the system-level dependencies. So I have not found global imports to aid my understanding of a system in practice.

I usually put the import of sys inside the if __name__=='__main__' check and then pass arguments (like sys.argv[1:]) to a main() function. This allows me to use main in a context where sys has not been imported.

new Date() is working in Chrome but not Firefox

In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

.do extension in web pages?

".do" is the "standard" extension mapped to for Struts Java platform. See http://struts.apache.org/ .