Programs & Examples On #Reroute

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

You can change it by editing Globas.asax file (not Global.asax.cs). Find it in app folder in windows explorer then edit

<%@ Application Codebehind="Global.asax.cs" Inherits="YourAppName.Global" Language="C#" %>

to

<%@ Application Codebehind="Global.asax.cs" Inherits="YourAppName.MvcApplication" Language="C#" %>

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

AngularJS- Login and Authentication in each route and controller

All have suggested big solution why you are worrying of session on client side. I mean when state/url changes I suppose you are doing an ajax call to load the data for tempelate.

Note :- To Save user's data you may use `resolve` feature of `ui-router`.
 Check cookie if it exist load template , if even cookies doesn't exist than 
there is no chance of logged in , simply redirect to login template/page.

Now the ajax data is returned by server using any api. Now the point came into play , return standard return types using server according to logged in status of user. Check those return codes and process your request in controller. Note:- For controller which doesn't require an ajax call natively , you can call a blank request to server like this server.location/api/checkSession.php and this is checkSession.php

<?php/ANY_LANGUAGE
session_start();//You may use your language specific function if required
if(isset($_SESSION["logged_in"])){
set_header("200 OK");//this is not right syntax , it is just to hint
}
else{
set_header("-1 NOT LOGGED_IN");//you may set any code but compare that same       
//code on client side to check if user is logged in or not.
}
//thanks.....

On client side inside controller or through any service as shown in other answers

    $http.get(dataUrl)
    .success(function (data){
        $scope.templateData = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status);
if(status == CODE_CONFIGURED_ON_SERVER_SIDE_FOR_NON_LOGGED_IN){
//redirect to login
  });

Note :- I will update more tomorrow or in future

The view or its master was not found or no view engine supports the searched locations

In my case, I needed to use RedirectToAction to solve the problem.

[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
    try
    {
        // Validate
        if (output != "PDF")
        {
            throw new Exception("Invalid output.");
        }
        else
        {
            ...// code to generate report in PDF format
        }
    }
    catch (Exception ex)
    {
        return RedirectToAction("Error");
    }
}

[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
    return View();
}

Where do I put image files, css, js, etc. in Codeigniter?

This is how I handle the public assets. Here I use Phalcon PHP's Bootstrap method.

Folder Structure

|-.htaccess*
|-application/
|-public/
  |-.htaccess**
  |-index.php***
  |-css/
  |-js/
  |-img/
  |-font/
  |-upload/
|-system

Files to edit

  1. .htaccess*

    All requests to the project will be rewritten to the public/ directory making it the document root. This step ensures that the internal project folders remain hidden from public viewing and thus eliminates security threats of this kind. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  (.*) public/$1 [L]
    </IfModule>
    
  2. .htaccess**

    Rules will check if the requested file exists and, if it does, it doesn’t have to be rewritten by the web server module. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php/$1 [QSA,L]
    </IfModule>
    
  3. index.php***

    Modify the application path and the system path as,

    $system_path = '../system';
    $application_folder = '../application';
    

Now you use the public folder as base_url()."public/[YOUR ASSET FOLDER]"

Hope this helps :)

Serving favicon.ico in ASP.NET MVC

I think that favicon.ico should be in root folder. It just belongs there.

If you want to servere diferent icons - put it into controler. You can do that. If not - just leave it in the root folder.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Find the index of a dict within a list, by matching the dict's value

For a given iterable, more_itertools.locate yields positions of items that satisfy a predicate.

import more_itertools as mit


iterable = [
    {"id": "1234", "name": "Jason"},
    {"id": "2345", "name": "Tom"},
    {"id": "3456", "name": "Art"}
]

list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]

more_itertools is a third-party library that implements itertools recipes among other useful tools.

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

Counting the number of files in a directory using Java

In spring batch I did below

private int getFilesCount() throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("file:" + projectFilesFolder + "/**/input/splitFolder/*.csv");
        return resources.length;
    }

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

How to get browser width using JavaScript code?

It's a pain in the ass. I recommend skipping the nonsense and using jQuery, which lets you just do $(window).width().

Class JavaLaunchHelper is implemented in two places

I have found the other workaround: to exclude libinstrument.dylib from project path. To do so, go to the Preferences -> Build, Execution and Deployment -> Compiler -> Excludes -> + and here add file by the path in error message.

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

I have also faced the similar problem with the following details Java 1.8.0_121, Spark spark-1.6.1-bin-hadoop2.6, Windows 10 and Eclipse Oxygen.When I ran my WordCount.java in Eclipse using HADOOP_HOME as a system variable as mentioned in the previous post, it did not work, what worked for me is -

System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");

PATH/TO/THE/DIR/bin=winutils.exe whether you run within Eclipse as a Java application or by spark-submit from cmd using

spark-submit --class groupid.artifactid.classname --master local[2] /path to the jar file created using maven /path to a demo test file /path to output directory command

Example: Go to the bin location of Spark/home/location/bin and execute the spark-submit as mentioned,

D:\BigData\spark-2.3.0-bin-hadoop2.7\bin>spark-submit --class com.bigdata.abdus.sparkdemo.WordCount --master local[1] D:\BigData\spark-quickstart\target\spark-quickstart-0.0.1-SNAPSHOT.jar D:\BigData\spark-quickstart\wordcount.txt

What is the difference between MVC and MVVM?

I thought one of the main differences was that in MVC, your V reads your M directly, and goes via the C to manipulate the data, whereas in MVVM, your VM acts as an M proxy, as well as providing the available functionality to you V.

If I'm not full of junk, I'm surprised no one has created a hybrid, where your VM is merely a M proxy, and C provides all functionality.

Update index after sorting data-frame

You can set new indices by using set_index:

df2.set_index(np.arange(len(df2.index)))

Output:

   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

T-SQL: How to Select Values in Value List that are NOT IN the Table?

This Should work with all SQL versions.

SELECT  E.AccessCode ,
        CASE WHEN C.AccessCode IS NOT NULL THEN 'Exist'
             ELSE 'Not Exist'
        END AS [Status]
FROM    ( SELECT    '60552' AS AccessCode
          UNION ALL
          SELECT    '80630'
          UNION ALL
          SELECT    '1611'
          UNION ALL
          SELECT    '0000'
        ) AS E
        LEFT OUTER JOIN dbo.Credentials C ON E.AccessCode = c.AccessCode

How to restore SQL Server 2014 backup in SQL Server 2008

If you have both versions you can create a merge replication from new to old. Create a merge publication on your newer sql server and a subscription on the older version. After initializing the subscription you can create a backup of the database with the same structure and the same content but in an older version and restore it on your old target server. You can use this method also with sql server 2016 to target 2014, 2012 or 2008.

How does one parse XML files?

I have just recently been required to work on an application which involved the parsing of an XML document and I agree with Jon Galloway that the LINQ to XML based approach is, in my opinion, the best. I did however have to dig a little to find usable examples, so without further ado, here are a few!

Any comments welcome as this code works but may not be perfect and I would like to learn more about parsing XML for this project!

public void ParseXML(string filePath)  
{  
    // create document instance using XML file path
    XDocument doc = XDocument.Load(filePath);

    // get the namespace to that within of the XML (xmlns="...")
    XElement root = doc.Root;
    XNamespace ns = root.GetDefaultNamespace();

    // obtain a list of elements with specific tag
    IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;

    // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
    XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();

    // obtain an element from within an element, same as from doc
    XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();

    // obtain an attribute from an element
    XAttribute attribute = element.Attribute("exampleAttributeName");
}

With these functions I was able to parse any element and any attribute from an XML file no problem at all!

How do I count unique items in field in Access query?

Try this

SELECT Count(*) AS N
FROM
(SELECT DISTINCT Name FROM table1) AS T;

Read this for more info.

Generic Interface

If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.

The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.

In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?

Replacing a fragment with another fragment inside activity group

Please see this Question

You can only replace a "dynamically added fragment".

So, if you want to add a dynamic fragment, see this example.

Excel Date to String conversion

Couldnt get the TEXT() formula to work

Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back

Or you can do the same with a formula like this

=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)

identifier "string" undefined?

You forgot the namespace you're referring to. Add

using namespace std;

to avoid std::string all the time.

What precisely does 'Run as administrator' do?

Windows 7 requires that you intentionally ask for certain privileges so that a malicious program can't do bad things to you. If the free calculator you downloaded needed to be run as an administrator, you would know something is up. There are OS commands to elevate the privilege of your application (which will request confirmation from the user).

A good description can be found at:

http://msdn.microsoft.com/en-us/magazine/cc163486.aspx#S4

Insert line after first match using sed

The awk variant :

awk '1;/CLIENTSCRIPT=/{print "CLIENTSCRIPT2=\"hello\""}' file

How to avoid scientific notation for large numbers in JavaScript?

Use .toPrecision, .toFixed, etc. You can count the number of digits in your number by converting it to a string with .toString then looking at its .length.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

If you're sure you configure your aws correctly, just make sure the user of the project can read from ./aws or just run your project as a root

How to trim whitespace from a Bash variable?

Use:

trim() {
    local orig="$1"
    local trmd=""
    while true;
    do
        trmd="${orig#[[:space:]]}"
        trmd="${trmd%[[:space:]]}"
        test "$trmd" = "$orig" && break
        orig="$trmd"
    done
    printf -- '%s\n' "$trmd"
}
  • It works on all kinds of whitespace, including newline,
  • It does not need to modify shopt.
  • It preserves inside whitespace, including newline.

Unit test (for manual review):

#!/bin/bash

. trim.sh

enum() {
    echo "   a b c"
    echo "a b c   "
    echo "  a b c "
    echo " a b c  "
    echo " a  b c  "
    echo " a  b  c  "
    echo " a      b  c  "
    echo "     a      b  c  "
    echo "     a  b  c  "
    echo " a  b  c      "
    echo " a  b  c      "
    echo " a N b  c  "
    echo "N a N b  c  "
    echo " Na  b  c  "
    echo " a  b  c N "
    echo " a  b  c  N"
}

xcheck() {
    local testln result
    while IFS='' read testln;
    do
        testln=$(tr N '\n' <<<"$testln")
        echo ": ~~~~~~~~~~~~~~~~~~~~~~~~~ :" >&2
        result="$(trim "$testln")"
        echo "testln='$testln'" >&2
        echo "result='$result'" >&2
    done
}

enum | xcheck

How do I create a batch file timer to execute / call another batch throughout the day

@echo off
:Start
title timer
color EC
echo Type in an amount of time (Seconds)
set /p time=

color CE

:loop
cls
ping localhost -n 2 >nul
set /a time=%time%-1
echo %time%
if %time% EQU 0 goto Timesup
goto loop

:Timesup
title Time Is Up!
ping localhost -n 2 >nul
ping localhost -n 2 >nul
cls
echo The Time is up!
pause
cls
echo Thank you for using this software.
pause
goto Web
goto Exit

:Web
rem type ur command here

:Exit
Exit
goto Exit

How to get PHP $_GET array?

You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

Get textarea text with javascript or Jquery

You could use val().

var value = $('#area1').val();
$('#VAL_DISPLAY').html(value);

How to get a variable name as a string in PHP?

Lucas on PHP.net provided a reliable way to check if a variable exists. In his example, he iterates through a copy of the global variable array (or a scoped array) of variables, changes the value to a randomly generated value, and checks for the generated value in the copied array.

function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){
    if($scope) {
        $vals = $scope;
    } else {
        $vals = $GLOBALS;
    }
    $old = $var;
    $var = $new = $prefix.rand().$suffix;
    $vname = FALSE;
    foreach($vals as $key => $val) {
        if($val === $new) $vname = $key;
    }
    $var = $old;
    return $vname;
}

Then try:

$a = 'asdf';
$b = 'asdf';
$c = FALSE;
$d = FALSE;

echo variable_name($a); // a
echo variable_name($b); // b
echo variable_name($c); // c
echo variable_name($d); // d

Be sure to check his post on PHP.net: http://php.net/manual/en/language.variables.php

What's the difference between an Angular component and module

A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.

Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.

Receiving JSON data back from HTTP request

It's working fine for me by the following way -

public async Task<object> TestMethod(TestModel model)
    {
        try
        {
            var apicallObject = new
            {
                Id= model.Id,
                name= model.Name
            };

            if (apicallObject != null)
            {
                var bodyContent = JsonConvert.SerializeObject(apicallObject);
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(bodyContent.ToString(), Encoding.UTF8, "application/json");
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Add("access-token", _token); // _token = access token
                    var response = await client.PostAsync(_url, content); // _url =api endpoint url
                    if (response != null)
                    {
                        var jsonString = await response.Content.ReadAsStringAsync();

                        try
                        {
                            var result = JsonConvert.DeserializeObject<TestModel2>(jsonString); // TestModel2 = deserialize object
                        }
                        catch (Exception e){
                            //msg
                            throw e;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return null;
    }

Does functional programming replace GoF design patterns?

Some patterns are easier to implement in a language supporting FP. For example, Strategy can be implemented using nicely using closures. However depending on context, you may prefer to implement Strategy using a class-based approach, say where the strategies themselves are quite complicated and/or share structure that you want to model using Template Method.

In my experience developing in a multi-paradigm language (Ruby), the FP implementation works well in simple cases, but where the context is more complicated the GoF OOP based approach is a better fit.

The FP approach does not replace the OOP approach, it complements it.

How to send a "multipart/form-data" with requests in python?

I'm trying to send a request to URL_server with request module in python 3. This works for me:

# -*- coding: utf-8 *-*
import json, requests

URL_SERVER_TO_POST_DATA = "URL_to_send_POST_request"
HEADERS = {"Content-Type" : "multipart/form-data;"}

def getPointsCC_Function():
  file_data = {
      'var1': (None, "valueOfYourVariable_1"),
      'var2': (None, "valueOfYourVariable_2")
  }

  try:
    resElastic = requests.post(URL_GET_BALANCE, files=file_data)
    res = resElastic.json()
  except Exception as e:
    print(e)

  print (json.dumps(res, indent=4, sort_keys=True))

getPointsCC_Function()

Where:

  • URL_SERVER_TO_POST_DATA = Server where we going to send data
  • HEADERS = Headers sended
  • file_data = Params sended

Disable Buttons in jQuery Mobile

If I'm reading this question correctly, you may be missing that a jQuery mobile "button" widget is not the same thing as an HTML button element. I think this boils down to you can't call $('input').button('disable') unless you have previously called $('input').button(); to initialize a jQuery Mobile button widget on your input.

Of course, you may not want to be using jQuery button widget functionality, in which case Alexander's answer should set you right.

_tkinter.TclError: no display name and no $DISPLAY environment variable

I also met this problem while using Xshell to connect Linux server.

After seaching for methods, I find Xming + Xshell to solve image imshow problem with matplotlib.

If solutions aboved can't solve your problem, just try to download Xming under the condition you're using Xshell. Then set the attribute in Xshell, SSH->tunnel->X11transfer->choose X DISPLAY localhost:0.0

Make selected block of text uppercase

enter image description here

Select the text to transform.

Use Ctrl + L to selected the whole line

Open Show all commands.

Linux and Windows: Ctrl + Shift + P, Mac: ??P

Type in the command, e.g. lower, upper, title

Hit Enter

apache mod_rewrite is not working or not enabled

Try setting: "AllowOverride All".

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

How to get year/month/day from a date object?

new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"

How do I multiply each element in a list by a number?

A blazingly faster approach is to do the multiplication in a vectorized manner instead of looping over the list. Numpy has already provided a very simply and handy way for this that you can use.

>>> import numpy as np
>>> 
>>> my_list = np.array([1, 2, 3, 4, 5])
>>> 
>>> my_list * 5
array([ 5, 10, 15, 20, 25])

Note that this doesn't work with Python's native lists. If you multiply a number with a list it will repeat the items of the as the size of that number.

In [15]: my_list *= 1000

In [16]: len(my_list)
Out[16]: 5000

If you want a pure Python-based approach using a list comprehension is basically the most Pythonic way to go.

In [6]: my_list = [1, 2, 3, 4, 5]

In [7]: [5 * i for i in my_list]
Out[7]: [5, 10, 15, 20, 25]

Beside list comprehension, as a pure functional approach, you can also use built-in map() function as following:

In [10]: list(map((5).__mul__, my_list))
Out[10]: [5, 10, 15, 20, 25]

This code passes all the items within the my_list to 5's __mul__ method and returns an iterator-like object (in python-3.x). You can then convert the iterator to list using list() built in function (in Python-2.x you don't need that because map return a list by default).

benchmarks:

In [18]: %timeit [5 * i for i in my_list]
463 ns ± 10.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [19]: %timeit list(map((5).__mul__, my_list))
784 ns ± 10.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [20]: %timeit [5 * i for i in my_list * 100000]
20.8 ms ± 115 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [21]: %timeit list(map((5).__mul__, my_list * 100000))
30.6 ms ± 169 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


In [24]: arr = np.array(my_list * 100000)

In [25]: %timeit arr * 5
899 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Create space at the beginning of a UITextField

Here is Haagenti's answer updated to Swift 4.2:

class PaddedTextField: UITextField {

    func getPadding(plusExtraFor clearButtonMode: ViewMode) -> UIEdgeInsets {
        var padding = UIEdgeInsets(top: 11, left: 16, bottom: 11, right: 16)

        // Add additional padding on the right side when showing the clear button
        if self.clearButtonMode == .always || self.clearButtonMode == clearButtonMode {
            padding.right = 28
        }

        return padding
    }

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .whileEditing)
        return bounds.inset(by: padding)
    }

}

Reference: Upgrading To Swift 4.2.

Edit: Account for clear button.

Convert byte to string in Java

The string ctor is suitable for this conversion:

System.out.println("string " + new String(new byte[] {0x63}));

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

If the problem persists probably Hyper-V on your system is corrupted, so

Go in Control Panel -> [Programs] -> [Windows Features] and completely uncheck all Hyper-V related components. Restart the system.

Enable Hyper-V again. Restart.

How to add a new column to a CSV file?

I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:

import pandas as pd
csv_input = pd.read_csv('input.csv')
csv_input['Berries'] = csv_input['Name']
csv_input.to_csv('output.csv', index=False)

Check out Pandas Website for more information!

Contents of output.csv:

Name,Code,Berries
blackberry,1,blackberry
wineberry,2,wineberry
rasberry,1,rasberry
blueberry,1,blueberry
mulberry,2,mulberry

Android - shadow on text?

You should be able to add the style, like this (taken from source code for Ringdroid):

  <style name="AudioFileInfoOverlayText">
    <item name="android:paddingLeft">4px</item>
    <item name="android:paddingBottom">4px</item>
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12sp</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
  </style>

And in your layout, use the style like this:

 <TextView android:id="@+id/info"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       style="@style/AudioFileInfoOverlayText"
       android:gravity="center" />

Edit: the source code can be viewed here: https://github.com/google/ringdroid

Edit2: To set this style programmatically, you'd do something like this (modified from this example to match ringdroid's resources from above)

TextView infoTextView = (TextView) findViewById(R.id.info);
infoTextView.setTextAppearance(getApplicationContext(),  
       R.style.AudioFileInfoOverlayText);

The signature for setTextAppearance is

public void setTextAppearance (Context context, int resid)

Since: API Level 1
Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Compiling with g++ using multiple cores

distcc can also be used to distribute compiles not only on the current machine, but also on other machines in a farm that have distcc installed.

What is the equivalent of 'describe table' in SQL Server?

You can use the sp_columns stored procedure:

exec sp_columns MyTable

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

In my case, at the message of error was "version 6.0.0", but this version is not available to install, so i installed the "6.0.1 version" at my project and solved my problem.

install-package Newtonsoft.Json -Version 6.0.1 -Project MyProjectX

How can I convince IE to simply display application/json rather than offer to download it?

Changing IE's JSON mime-type settings will effect the way IE treats all JSON responses.

Changing the mime-type header to text/html will effectively tell any browser that the JSON response you are returning is not JSON but plain text.

Neither options are preferable.

Instead you would want to use a plugin or tool like the above mentioned Fiddler or any other network traffic inspector proxy where you can choose each time how to process the JSON response.

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

How to change the link color in a specific class for a div CSS

how about something like this ...

a.register:link{
    color:#FFFFFF;
}

How to export non-exportable private key from store

There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.

The code is based on a paper by the NCC Group. will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass process, in order to temporarily mark keys as exportable. This can be done using PsExec from SysInternals' PsTools:

  1. Spawn a new command prompt running as the local system user:

PsExec64.exe -s -i cmd

  1. In the new command prompt, run the tool:

exportrsa.exe

  1. It will loop over every Local Computer store, searching for certificates with a private key. For each one, it will prompt you for a password - this is the password you want to secure the exported PFX file with, so can be whatever you want

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Create a bare GIT repository

A small rant: git is unable to create a normal bare repository by itself. Stupid git indeed.

To be precise, it is not possible to clone empty repositories. So an empty repository is a useless repository. Indeed, you normally create an empty repository and immediately fill it:

git init
git add .

However, git add is not possible when you create a bare repository:

git --bare init
git add .

gives an error "fatal: This operation must be run in a work tree".

You can't check it out either:

Initialized empty Git repository in /home/user/myrepos/.git/
fatal: http://repository.example.org/projects/myrepos.git/info/refs not found: did you run git update-server-info on the server?

git --bare init
git update-server-info # this creates the info/refs file
chown -R <user>:<group> . # make sure others can update the repository

The solution is to create another repository elsewhere, add a file in that repository and, push it to the bare repository.

mkdir temp; cd temp
git init
touch .gitignore
git add .gitignore
git commit -m "Initial commit"
git push (url or path of bare repository) master
cd ..; rm -rf temp

hope this can help u

How to run (not only install) an android application using .apk file?

if you're looking for the equivalent of "adb run myapp.apk"

you can use the script shown in this answer

(linux and mac only - maybe with cygwin on windows)

linux/mac users can also create a script to run an apk with something like the following:

create a file named "adb-run.sh" with these 3 lines:

pkg=$(aapt dump badging $1|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$(aapt dump badging $1|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
adb shell am start -n $pkg/$act

then "chmod +x adb-run.sh" to make it executable.

now you can simply:

adb-run.sh myapp.apk

The benefit here is that you don't need to know the package name or launchable activity name. Similarly, you can create "adb-uninstall.sh myapp.apk"

Note: This requires that you have aapt in your path. You can find it under the new build tools folder in the SDK

Concatenate a vector of strings/character

For sdata:

gsub(", ","",toString(sdata))

For a vector of integers:

gsub(", ","",toString(c(1:10)))

AngularJS ng-click stopPropagation

I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".

You would use it like this:

<table>
  <tr ng-repeat="user in users" ng-click="showUser(user)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td isolate-click>
      <button class="btn" ng-click="deleteUser(user.id, $index);">
        Delete
      </button>
    </td>              
  </tr>
</table>

Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:

<span isolate-click>
    <button class="btn" ng-click="deleteUser(user.id, $index);">
        Delete
    </button>
</span>

Here is the directive's code:

angular.module('awesome', []).directive('isolateClick', function() {
    return {
        link: function(scope, elem) {
            elem.on('click', function(e){
                e.stopPropagation();
            });
        }
   };
});

How to allow http content within an iframe on a https site

Use your own HTTPS-to-HTTP reverse proxy.

If your use case is about a few, rarely changing URLs to embed into the iframe, you can simply set up a reverse proxy for this on your own server and configure it so that one https URL on your server maps to one http URL on the proxied server. Since a reverse proxy is fully serverside, the browser cannot discover that it is "only" talking to a proxy of the real website, and thus will not complain as the connection to the proxy uses SSL properly.

If for example you use Apache2 as your webserver, then see these instructions to create a reverse proxy.

Convert NSDate to NSString

there are a number of NSDate helpers on the web, I tend to use:

https://github.com/billymeltdown/nsdate-helper/

Readme extract below:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:

‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)

Using a custom typeface in Android

Although I am upvoting Manish's answer as the fastest and most targeted method, I have also seen naive solutions which just recursively iterate through a view hierarchy and update all elements' typefaces in turn. Something like this:

public static void applyFonts(final View v, Typeface fontToSet)
{
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                applyFonts(child, fontToSet);
            }
        } else if (v instanceof TextView) {
            ((TextView)v).setTypeface(fontToSet);
        }
    } catch (Exception e) {
        e.printStackTrace();
        // ignore
    }
}

You would need to call this function on your views both after inflating layout and in your Activity's onContentChanged() methods.

How to Convert Boolean to String

Another way to do : json_encode( booleanValue )

echo json_encode(true);  // string "true"

echo json_encode(false); // string "false"

// null !== false
echo json_encode(null);  // string "null"

OperationalError: database is locked

As others have told, there is another process that is using the SQLite file and has not closed the connection. In case you are using Linux, you can see which processes are using the file (for example db.sqlite3) using the fuser command as follows:

$ sudo fuser -v db.sqlite3
                     USER        PID ACCESS COMMAND
/path/to/db.sqlite3:
                     user        955 F....  apache2

If you want to stop the processes to release the lock, use fuser -k which sends the KILL signal to all processes accessing the file:

sudo fuser -k db.sqlite3

Note that this is dangerous as it might stop the web server process in a production server.

Thanks to @cz-game for pointing out fuser!

How can I get the root domain URI in ASP.NET?

string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"

How to view the roles and permissions granted to any database user in Azure SQL server instance?

Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:

SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
    ON pe.grantee_principal_id = pr.principal_id;

Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

append to url and refresh page

Please check the below code :

/*Get current URL*/    
var _url = location.href; 
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;

duplicate 'row.names' are not allowed error

Another possible reason for this error is that you have entire rows duplicated. If that is the case, the problem is solved by removing the duplicate rows.

Calling dynamic function with dynamic number of parameters

Couldn't you just pass the arguments array along?

function mainfunc (func){
    // remove the first argument containing the function name
    arguments.shift();
    window[func].apply(null, arguments);
}

function calledfunc1(args){
    // Do stuff here
}

function calledfunc2(args){
    // Do stuff here
}

mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');

Simple search MySQL database using php

If you do mysqli_fetch_array(), you must put integer in $row index ex.($row[3]).If you read $row['id'] or $row['example'], you must use mysqli_fetch_assoc.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

when do you need .ascx files and how would you use them?

We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...

For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.

So, thought user controls, one can avoid code repetition for each role and UI creation for each role.

How to align two elements on the same line without changing HTML

By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use display: inline-block; for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:

    white-space: nowrap;
    overflow-x: auto;

here a more formatted example to make it clear:

.parent {
    white-space: nowrap;
    overflow-x: auto;
}

.children {
   display: inline-block;
   margin-left: 20px; 
}

For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.

body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
        white-space: nowrap;
        overflow-x: auto;
 }

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
   display: inline-block;
   margin-left: 10px; 
}

keep in mind that white-space: nowrap; and overlow-x: auto; is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.

What is REST? Slightly confused

REST is an architectural style and a design for network-based software architectures.

REST concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML, JSON, and RDF. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET, PUT, POST, DELETE.

REST is typically used over HTTP, primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles. REST however is not tied to any specific protocol.

Fundamental REST Principles

Client-Server Communication

Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.

Stateless

Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.

Cacheable

Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.

Uniform Interface

All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!

The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.

See this blog post on REST Design Principals for more details on REST and the above principles.

Android Service Stops When App Is Closed

try this, it will keep the service running in the background.

BackServices.class

public class BackServices extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

in your MainActivity onCreate drop this line of code

startService(new Intent(getBaseContext(), BackServices.class));

Now the service will stay running in background.

T-SQL loop over query results

try this:

declare @i tinyint = 0,
    @count tinyint,
    @id int,
    @name varchar(max)

select @count = count(*) from table
while (@i < @count)
begin
    select @id = id, @name = name from table
    order by nr asc offset @i rows fetch next 1 rows only

    exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name

    set @i = @i + 1
end

How can I schedule a daily backup with SQL Server Express?

You can create a backup device in server object, let us say

BDTEST

and then create a batch file contain following command

sqlcmd -S 192.168.1.25 -E -Q "BACKUP DATABASE dbtest TO BDTEST"

let us say with name

backup.bat

then you can call

backup.bat

in task scheduler according to your convenience

Live video streaming using Java?

Yes if you want to stream live video you can use RTSP protoco this will allow you to create a video file, which can be play while creating, both operation will work simultaneously. RTSP-Client-Server

What is the T-SQL syntax to connect to another SQL Server?

In SQL Server Management Studio, turn on SQLCMD mode from the Query menu. Then at the top of your script, type in the command below

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]

If you are connecting to multiple servers, be sure to insert GO between connections; otherwise your T-SQL won't execute on the server you're thinking it will.

C++ correct way to return pointer to array from function

New answer to new question:

You cannot return pointer to automatic variable (int c[5]) from the function. Automatic variable ends its lifetime with return enclosing block (function in this case) - so you are returning pointer to not existing array.

Either make your variable dynamic:

int* test (int a[5], int b[5]) {
    int* c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

Or change your implementation to use std::array:

std::array<int,5> test (const std::array<int,5>& a, const std::array<int,5>& b) 
{
   std::array<int,5> c;
   for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
   return c;
}

In case your compiler does not provide std::array you can replace it with simple struct containing an array:

struct array_int_5 { 
   int data[5];
   int& operator [](int i) { return data[i]; } 
   int operator const [](int i) { return data[i]; } 
};

Old answer to old question:

Your code is correct, and ... hmm, well, ... useless. Since arrays can be assigned to pointers without extra function (note that you are already using this in your function):

int arr[5] = {1, 2, 3, 4, 5};
//int* pArr = test(arr);
int* pArr = arr;

Morever signature of your function:

int* test (int in[5])

Is equivalent to:

int* test (int* in)

So you see it makes no sense.

However this signature takes an array, not pointer:

int* test (int (&in)[5])

What is the default root pasword for MySQL 5.7

As of Ubuntu 20.04 with MySql 8.0 : you can set the password that way:

  1. login to mysql with sudo mysql -u root

  2. change the password:

USE mysql;
UPDATE user set authentication_string=NULL where User='root';
FLUSH privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'My-N7w_And.5ecure-P@s5w0rd';
FLUSH privileges;
QUIT

now you should be able to login with mysql -u root -p (or to phpMyAdmin with username root) and your chosen password.

P,S:

You can also login with user debian-sys-maint, the password is written in the file /etc/mysql/debian.cnf

How to embed images in email

Correct way of embedding images into Outlook and avoiding security problems is the next:

  1. Use interop for Outlook 2003;
  2. Create new email and set it save folder;
  3. Do not use base64 embedding, outlook 2007 does not support it; do not reference files on your disk, they won't be send; do not use word editor inspector because you will get security warnings on some machines;
  4. Attachment must have png/jpg extension. If it will have for instance tmp extension - Outlook will warn user;
  5. Pay attention how CID is generated without mapi;
  6. Do not access properties via getters or you will get security warnings on some machines.

    public static void PrepareEmail()
    {
        var attachFile = Path.Combine(
            Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
    
        Microsoft.Office.Interop.Outlook.Application outlook = null;
        NameSpace space = null;
        MAPIFolder folder = null;
        MailItem mail = null;
        Attachment attachment = null;
        try
        {
            outlook = new Microsoft.Office.Interop.Outlook.Application();
            space = outlook.GetNamespace("MAPI");
            space.Logon(null, null, true, true);
    
            folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
            mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
    
            mail.SaveSentMessageFolder = folder;
            mail.Subject = "Hi Everyone";
            mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing); 
            // Last Type.Missing - is for not to show attachment in attachments list.
    
            string attachmentId = Path.GetFileName(attachFile);
            mail.BodyFormat = OlBodyFormat.olFormatHTML;
    
             mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
    
            mail.Display(false);
        }
        finally
        {
            ReleaseComObject(outlook, space, folder, mail, attachment);
        }
    }
    

Multipart forms from C# client

Thanks for the answers, everybody! I recently had to get this to work, and used your suggestions heavily. However, there were a couple of tricky parts that did not work as expected, mostly having to do with actually including the file (which was an important part of the question). There are a lot of answers here already, but I think this may be useful to someone in the future (I could not find many clear examples of this online). I wrote a blog post that explains it a little more.

Basically, I first tried to pass in the file data as a UTF8 encoded string, but I was having problems with encoding files (it worked fine for a plain text file, but when uploading a Word Document, for example, if I tried to save the file that was passed through to the posted form using Request.Files[0].SaveAs(), opening the file in Word did not work properly. I found that if you write the file data directly using a Stream (rather than a StringBuilder), it worked as expected. Also, I made a couple of modifications that made it easier for me to understand.

By the way, the Multipart Forms Request for Comments and the W3C Recommendation for mulitpart/form-data are a couple of useful resources in case anyone needs a reference for the specification.

I changed the WebHelpers class to be a bit smaller and have simpler interfaces, it is now called FormUpload. If you pass a FormUpload.FileParameter you can pass the byte[] contents along with a file name and content type, and if you pass a string, it will treat it as a standard name/value combination.

Here is the FormUpload class:

// Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt
// http://www.briangrinstead.com/blog/multipart-form-post-in-c
public static class FormUpload
{
    private static readonly Encoding encoding = Encoding.UTF8;
    public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
    {
        string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
        string contentType = "multipart/form-data; boundary=" + formDataBoundary;

        byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);

        return PostForm(postUrl, userAgent, contentType, formData);
    }
    private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
    {
        HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

        if (request == null)
        {
            throw new NullReferenceException("request is not a http request");
        }

        // Set up the request properties.
        request.Method = "POST";
        request.ContentType = contentType;
        request.UserAgent = userAgent;
        request.CookieContainer = new CookieContainer();
        request.ContentLength = formData.Length;

        // You could add authentication here as well if needed:
        // request.PreAuthenticate = true;
        // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

        // Send the form data to the request.
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(formData, 0, formData.Length);
            requestStream.Close();
        }

        return request.GetResponse() as HttpWebResponse;
    }

    private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
    {
        Stream formDataStream = new System.IO.MemoryStream();
        bool needsCLRF = false;

        foreach (var param in postParameters)
        {
            // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
            // Skip it on the first parameter, add it to subsequent parameters.
            if (needsCLRF)
                formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));

            needsCLRF = true;

            if (param.Value is FileParameter)
            {
                FileParameter fileToUpload = (FileParameter)param.Value;

                // Add just the first part of this param, since we will write the file data directly to the Stream
                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                    boundary,
                    param.Key,
                    fileToUpload.FileName ?? param.Key,
                    fileToUpload.ContentType ?? "application/octet-stream");

                formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

                // Write the file data directly to the Stream, rather than serializing it to a string.
                formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
            }
            else
            {
                string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                    boundary,
                    param.Key,
                    param.Value);
                formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
            }
        }

        // Add the end of the request.  Start with a newline
        string footer = "\r\n--" + boundary + "--\r\n";
        formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));

        // Dump the Stream into a byte[]
        formDataStream.Position = 0;
        byte[] formData = new byte[formDataStream.Length];
        formDataStream.Read(formData, 0, formData.Length);
        formDataStream.Close();

        return formData;
    }

    public class FileParameter
    {
        public byte[] File { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
        public FileParameter(byte[] file) : this(file, null) { }
        public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
        public FileParameter(byte[] file, string filename, string contenttype)
        {
            File = file;
            FileName = filename;
            ContentType = contenttype;
        }
    }
}

Here is the calling code, which uploads a file and a few normal post parameters:

// Read file data
FileStream fs = new FileStream("c:\\people.doc", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();

// Generate post objects
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("filename", "People.doc");
postParameters.Add("fileformat", "doc");
postParameters.Add("file", new FormUpload.FileParameter(data, "People.doc", "application/msword"));

// Create request and receive response
string postURL = "http://localhost";
string userAgent = "Someone";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);

// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
webResponse.Close();
Response.Write(fullResponse);

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

_x000D_
_x000D_
.selectmenu{_x000D_
  _x000D_
 -webkit-appearance: none;  /*Removes default chrome and safari style*/_x000D_
 -moz-appearance: none; /* Removes Default Firefox style*/_x000D_
 background: #0088cc ;_x000D_
 width: 200px; /*Width of select dropdown to give space for arrow image*/_x000D_
 text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
 text-overflow: "";  /*Removes default arrow from firefox*/ /*My custom style for fonts*/_x000D_
 color: #FFF;_x000D_
 border-radius: 2px;_x000D_
 padding: 5px;_x000D_
    border:0 !important;_x000D_
 box-shadow: inset 0 0 5px rgba(000,000,000, 0.5);_x000D_
}_x000D_
.hideoption { display:none; visibility:hidden; height:0; font-size:0; }
_x000D_
Try this html_x000D_
_x000D_
<select class="selectmenu">_x000D_
<option selected disabled class="hideoption">Select language</option>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
<option>Option 3</option>_x000D_
<option>Option 4</option>_x000D_
<option>Option 5</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What is the Python equivalent of Matlab's tic and toc functions?

This can also be done using a wrapper. Very general way of keeping time.

The wrapper in this example code wraps any function and prints the amount of time needed to execute the function:

def timethis(f):
    import time

    def wrapped(*args, **kwargs):
        start = time.time()
        r = f(*args, **kwargs)
        print "Executing {0} took {1} seconds".format(f.func_name,  time.time()-start)
        return r
    return wrapped

@timethis
def thistakestime():
    for x in range(10000000):
        pass

thistakestime()

iTerm2 keyboard shortcut - split pane navigation

I was using Terminator before, so I found it convenient to re-map Alt + arrow-key to switch between the panes. This can be done in Preferences -> Keys -> Key Mappings - press the '+' button to add a mapping. Also, in my case such a mapping was already defined in Profiles, I simply removed it.

Convert python datetime to epoch with strftime

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

OrderBy descending in Lambda expression?

Use System.Linq.Enumerable.OrderByDescending()?

For example:

var items = someEnumerable.OrderByDescending();

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

Submit form using a button outside the <form> tag

if you can use jQuery you can use this

<form method="get" action="something.php" id="myForm">
    <input type="text" name="name" />

    <input type="submit" style="display:none" />
</form>

<input type="button" value="Submit" id="myButton" />

<script type="text/javascript">
    $(document).ready(function() {
       $("#myButton").click(function() {
           $("#myForm").submit();
       });
    });
</script>

So, the bottom line is to create a button like Submit, and put the real submit button in the form(of course hiding it), and submit form by jquery via clicking the 'Fake Submit' button. Hope it helps.

Passing an array/list into a Python function

Python lists (which are not just arrays because their size can be changed on the fly) are normal Python objects and can be passed in to functions as any variable. The * syntax is used for unpacking lists, which is probably not something you want to do now.

Android - Using Custom Font

Make sure to paste the above code into onCreate() after your call to the super and the call to setContentView(). This small detail kept my hung up for awhile.

Select columns from result set of stored procedure

For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.

The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first retrieving column names and types from the stored procedure.

Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use OPENROWSET. Use the below if you have no other way.

DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'
DECLARE @tempTableName VARCHAR(MAX) = '#tempTable'

-- might need to update this if your param value is a string and you need to escape quotes
DECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'

DECLARE @createTableCommand VARCHAR(MAX)

-- update this to select the columns you want
DECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName

DECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName

-- Generate command to create temp table
SELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +
    STUFF
    (
        (
            SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)
            FROM sys.dm_exec_describe_first_result_set_for_object
            (
              OBJECT_ID(@spName), 
              NULL
            )
            FOR XML PATH('')
        )
        ,1
        ,1
        ,''
    ) + ')'

EXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

I had a similar problem, and being the newbie that I am it took me a while to figure out but I learned the user must have a login in SSMS. I created the logins with the following parameters:

  • Under Server Roles - check sysadmin
  • Under User Mapping - I selected the database and the report server. For each I checked datareader and datawriter
  • Under Securables - I checked anything that would allow the user to connect to the database and view anything
  • I also found that one of the existing logins had denydatareader and denydatawriter checked. Once I removed these it worked.

I'm not saying this is the best way to do it, just what worked for me. Hope this helps

Showing an image from an array of images - Javascript

This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
  "_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];

var imageIndex = 0; 

function changeImage() {
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex = (imageIndex + 1) % imageArray.length;
}

setInterval(changeImage, 5000);

Which versions of SSL/TLS does System.Net.WebRequest support?

I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.

If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.

How to fire a button click event from JavaScript in ASP.NET

I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...

I mean ->

I have an html submit button and an asp button like these:

_x000D_
_x000D_
<input type="submit" value="Siparisi Gönder" onclick="SendEmail()" />_x000D_
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
_x000D_
_x000D_
_x000D_

SendToEmail() is a server side method in Default.aspx SendEmail() is a javascript method like this:

_x000D_
_x000D_
<script type="text/javascript" lang="javascript">_x000D_
   function SendEmail() {_x000D_
            document.getElementById('<%= sendEmailButton.UniqueID %>').click();_x000D_
            alert("Your message is sending...");_x000D_
        }_x000D_
</script>
_x000D_
_x000D_
_x000D_

And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.

Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.

Then suddenly I changed html submit button --> just html button like this and now it is working:

_x000D_
_x000D_
<input type="button" value="Siparisi Gönder" onclick="SendEmail()" />
_x000D_
_x000D_
_x000D_

Have a nice days...

How to make a whole 'div' clickable in html and css without JavaScript?

Without JS, I am doing it like this:

My HTML:

<div class="container">
  <div class="sometext">Some text here</div>
  <div class="someothertext">Some other text here</div>
  <a href="#" class="mylink">text of my link</a>
</div>

My CSS:

.container{
  position: relative;
}

.container.a{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-indent: -9999px; //these two lines are to hide my actual link text.
  overflow: hidden; //these two lines are to hide my actual link text.
}

Classes vs. Modules in VB.NET

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

Query to count the number of tables I have in MySQL

mysql> show tables;

it will show the names of the tables, then the count on tables.

source

Package opencv was not found in the pkg-config search path

I got the same error when trying to compile a Go package on Debian 9.8:

# pkg-config --cflags  -- libssl libcrypto
Package libssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libssl.pc'

The thing is that pkg-config searches for package meta-information in .pc files. Such files come from the dev package. So, even though I had libssl installed, I still got the error. It was resolved by running:

sudo apt-get install libssl-dev

What is the default username and password in Tomcat?

Look in your conf/tomcat-users.xml. If there is nothing there, you'd have to configure it.

Calling a function on bootstrap modal open

you can use show instead of shown for making the function to load just before modal open, instead of after modal open.

$('#code').on('show.bs.modal', function (e) {
  // do something...
})

How to get a MemoryStream from a Stream in .NET?

public static void Do(Stream in)
{
    _ms = new MemoryStream();
    byte[] buffer = new byte[65536];
    while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
        _ms.Write (buffer, 0, read);
}

How to easily initialize a list of Tuples?

    var colors = new[]
    {
        new { value = Color.White, name = "White" },
        new { value = Color.Silver, name = "Silver" },
        new { value = Color.Gray, name = "Gray" },
        new { value = Color.Black, name = "Black" },
        new { value = Color.Red, name = "Red" },
        new { value = Color.Maroon, name = "Maroon" },
        new { value = Color.Yellow, name = "Yellow" },
        new { value = Color.Olive, name = "Olive" },
        new { value = Color.Lime, name = "Lime" },
        new { value = Color.Green, name = "Green" },
        new { value = Color.Aqua, name = "Aqua" },
        new { value = Color.Teal, name = "Teal" },
        new { value = Color.Blue, name = "Blue" },
        new { value = Color.Navy, name = "Navy" },
        new { value = Color.Pink, name = "Pink" },
        new { value = Color.Fuchsia, name = "Fuchsia" },
        new { value = Color.Purple, name = "Purple" }
    };
    foreach (var color in colors)
    {
        stackLayout.Children.Add(
            new Label
            {
                Text = color.name,
                TextColor = color.value,
            });
        FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
    }

this is a Tuple<Color, string>

How can I remove file extension from a website address?

The problem with creating a directory and keeping index.php in it is that

  1. your links with menu will stop functioning
  2. There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow

The solutions are 1. MOD REWRITE (as suggested above) 2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/

How do I set a textbox's text to bold at run time?

 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

Specifying number of decimal places in Python

You don't show the code for display_data, but here's what you need to do:

print "$%0.02f" %amount

This is a format specifier for the variable amount.

Since this is beginner topic, I won't get into floating point rounding error, but it's good to be aware that it exists.

How do I move files in node.js?

Using nodejs natively

var fs = require('fs')

var oldPath = 'old/path/file.txt'
var newPath = 'new/path/file.txt'

fs.rename(oldPath, newPath, function (err) {
  if (err) throw err
  console.log('Successfully renamed - AKA moved!')
})

(NOTE: "This will not work if you are crossing partitions or using a virtual filesystem not supporting moving files. [...]" – Flavien Volken Sep 2 '15 at 12:50")

pip install failing with: OSError: [Errno 13] Permission denied on directory

You are trying to install a package on the system-wide path without having the permission to do so.

  1. In general, you can use sudo to temporarily obtain superuser permissions at your responsibility in order to install the package on the system-wide path:

     sudo pip install -r requirements.txt
    

    Find more about sudo here.

    Actually, this is a bad idea and there's no good use case for it, see @wim's comment.

  2. If you don't want to make system-wide changes, you can install the package on your per-user path using the --user flag.

    All it takes is:

     pip install --user runloop requirements.txt
    
  3. Finally, for even finer grained control, you can also use a virtualenv, which might be the superior solution for a development environment, especially if you are working on multiple projects and want to keep track of each one's dependencies.

    After activating your virtualenv with

    $ my-virtualenv/bin/activate

    the following command will install the package inside the virtualenv (and not on the system-wide path):

    pip install -r requirements.txt

How to use placeholder as default value in select2 framework

I tried all this and in the end, simply using a title="text here" worked for my system. Note there is no blank option

<select name="Restrictions" class="selectpicker show-tick form-control" 
        data-live-search="true" multiple="multiple" title="Choose Multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

Get IPv4 addresses from Dns.GetHostEntry()

To find all local IPv4 addresses:

IPAddress[] ipv4Addresses = Array.FindAll(
    Dns.GetHostEntry(string.Empty).AddressList,
    a => a.AddressFamily == AddressFamily.InterNetwork);

or use Array.Find or Array.FindLast if you just want one.

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

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

I hit this error ("stat /bin/bash: no such file or directory") when running the command:

docker exec -it 80372bc2c41e /bin/bash

The solution was to identify the kind of terminal (or shell) that is available on the container. To do so, I ran:

docker inspect 80372bc2c41e

In the output from that command, I saw:

"Cmd": [
    "/bin/sh",
    "-c",
    "gunicorn -b 0.0.0.0:7082 server.app:app"
],

This tells me that there's a /bin/sh command available, and I was able to connect with:

docker exec -it 80372bc2c41e /bin/sh

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

Auto detect mobile browser (via user-agent?)

Yes user-agent is used to detect mobile browsers. There are lots of free scripts available to check this. Here is one such php code which will help you redirect mobile users to different website.

Standard way to embed version into python package?

pbr with bump2version

This solution was derived from this article

The use case - python GUI package distributed via PyInstaller. Needs to show version info.

Here is the structure of the project packagex

packagex
+-- packagex
¦   +-- __init__.py
¦   +-- main.py
¦   +-- _version.py
+-- packagex.spec
+-- LICENSE
+-- README.md
+-- .bumpversion.cfg
+-- requirements.txt
+-- setup.cfg
+-- setup.py

where setup.py is

# setup.py
import os

import setuptools

about = {}
with open("packagex/_version.py") as f:
    exec(f.read(), about)

os.environ["PBR_VERSION"] = about["__version__"]

setuptools.setup(
    setup_requires=["pbr"],
    pbr=True,
    version=about["__version__"],
)

packagex/_version.py contains just

__version__ = "0.0.1"

and packagex/__init__.py

from ._version import __version__

and for .bumpversion.cfg

[bumpversion]
current_version = 0.0.1
commit = False
tag = False
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\-(?P<release>[a-z]+)(?P<build>\d+))?
serialize = 
    {major}.{minor}.{patch}-{release}{build}
    {major}.{minor}.{patch}

[bumpversion:part:release]
optional_value = prod
first_value = dev
values = 
    dev
    prod

[bumpversion:file:packagex/_version.py]

HTML Script tag: type or language (or omit both)?

HTML4/XHTML1 requires

<script type="...">...</script>

HTML5 faces the fact that there is only one scripting language on the web, and allows

<script>...</script>

The latter works in any browser that supports scripting (NN2+).

Remove Item in Dictionary based on Value

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
    {
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
        {
            src.Remove(item.Key);
        }
    }

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How can I increment a date by one day in Java?

I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.

The API says:

addDays(Date date, int amount) : Adds a number of days to a date returning a new object.

Note that it returns a new Date object and does not make changes to the previous one itself.

What should every programmer know about security?

I suggest reviewing CWE/SANS TOP 25 Most Dangerous Programming Errors. It was updated for 2010 with the promise of regular updates in the future. The 2009 revision is available as well.

From http://cwe.mitre.org/top25/index.html

The 2010 CWE/SANS Top 25 Most Dangerous Programming Errors is a list of the most widespread and critical programming errors that can lead to serious software vulnerabilities. They are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.

The Top 25 list is a tool for education and awareness to help programmers to prevent the kinds of vulnerabilities that plague the software industry, by identifying and avoiding all-too-common mistakes that occur before software is even shipped. Software customers can use the same list to help them to ask for more secure software. Researchers in software security can use the Top 25 to focus on a narrow but important subset of all known security weaknesses. Finally, software managers and CIOs can use the Top 25 list as a measuring stick of progress in their efforts to secure their software.

What is the most efficient way to create HTML elements using jQuery?

I am using jquery.min v2.0.3 . It's for me better to use following:

var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);

as following:

var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);

Processing time of first code is much lower than second code.

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

What is the correct way to do a CSS Wrapper?

a "wrapper" is just a term for some element that encapsulates all other visual elements on the page. The body tag seems to fit the bill, but you would be at the mercy of the browser to determine what displays beneath that if you adjust the max-width.

Instead, we use div because it acts as a simple container that does not break. the main, header, footer, and section tags in HTML5 are just div elements named appropriately. It seems that there could (or should) be a wrapper tag because of this trend, but you may use whichever method of wrapping you find most suitable for your situation. through classes, ids and css, you can use a span tag in a very similar way.

There are a lot of HTML element tags that we do not use often or possibly even know about. Doing some research would show you what can be done with pure HTML.

Using app.config in .Net Core

To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.

protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");

To use the EF core SqlServer provider and compile the above code install the EF SqlServer package

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After compilation before running the code do the following for the first time

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

To run the code

dotnet run

How to set HttpResponse timeout for Android in Java

If your are using Jakarta's http client library then you can do something like:

        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(5000));
        client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000));
        GetMethod method = new GetMethod("http://www.yoururl.com");
        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(5000));
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        int statuscode = client.executeMethod(method);

Why is Thread.Sleep so harmful

The problems with calling Thread.Sleep are explained quite succinctly here:

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.

The preferred solution: WaitHandles

The most-made-mistake is using Thread.Sleep with a while-construct (demo and answer, nice blog-entry)

EDIT:
I would like to enhance my answer:

We have 2 different use-cases:

  1. We are waiting because we know a specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!

My answer mainly covers use-case 2

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

How do you run a command for each line of a file?

If you want to run your command in parallel for each line you can use GNU Parallel

parallel -a <your file> <program>

Each line of your file will be passed to program as an argument. By default parallel runs as many threads as your CPUs count. But you can specify it with -j

Java: notify() vs. notifyAll() all over again

I think it depends on how resources are produced and consumed. If 5 work objects are available at once and you have 5 consumer objects, it would make sense to wake up all threads using notifyAll() so each one can process 1 work object.

If you have just one work object available, what is the point in waking up all consumer objects to race for that one object? The first one checking for available work will get it and all other threads will check and find they have nothing to do.

I found a great explanation here. In short:

The notify() method is generally used for resource pools, where there are an arbitrary number of "consumers" or "workers" that take resources, but when a resource is added to the pool, only one of the waiting consumers or workers can deal with it. The notifyAll() method is actually used in most other cases. Strictly, it is required to notify waiters of a condition that could allow multiple waiters to proceed. But this is often difficult to know. So as a general rule, if you have no particular logic for using notify(), then you should probably use notifyAll(), because it is often difficult to know exactly what threads will be waiting on a particular object and why.

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

Convert blob to base64

this worked for me:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(blob);
};

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

install apt-get on linux Red Hat server

If you insist on using yum, try yum install apt. As read on this site: Link

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You can use linear indexing to access each element.

for idx = 1:numel(array)
    element = array(idx)
    ....
end

This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()

What does '&' do in a C++ declaration?

string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:

int foo(string *param1);

You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:

int foo(string &param1);

Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.

With regards to your second question, about the method return values being a reference, consider the following three functions:

string &foo();
string *foo();
string foo();

In the first case, you would be returning a reference to the data. If your function declaration looked like this:

string &foo()
{
    string localString = "Hello!";
    return localString;
}

You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.

The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.

Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:

string foo()
{
    string localString = "Hello!";
    return localString;
}

You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.

How to find Google's IP address?

On Windows, open command prompt and type tracert google.com and press enter, or on Linux, open terminal and type nslookup google.com and press enter:

Server:     127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:

Name:   google.com
Address: 74.125.236.199
Name:   google.com
Address: 74.125.236.201
Name:   google.com
Address: 74.125.236.194
Name:   google.com
Address: 74.125.236.198
Name:   google.com
Address: 74.125.236.206
Name:   google.com
Address: 74.125.236.193
Name:   google.com
Address: 74.125.236.196
Name:   google.com
Address: 74.125.236.192
Name:   google.com
Address: 74.125.236.197
Name:   google.com
Address: 74.125.236.195
Name:   google.com
Address: 74.125.236.200

Jenkins, specifying JAVA_HOME

For those of you coming to this issue and have access to configure your Jenkins Agents, you can set the JAVA_HOME from the Jenkins > Nodes > "the agent name" > Configure page:

Setting "per agent" environment variables

What's a quick way to comment/uncomment lines in Vim?

I use comments.vim from Jasmeet Singh Anand (found on vim.org),

It works with C, C++, Java, PHP[2345], proc, CSS, HTML, htm, XML, XHTML, vim, vimrc, SQL, sh, ksh, csh, Perl, tex, fortran, ml, caml, ocaml, vhdl, haskel, and normal files

It comments and un-comments lines in different source files in both normal and visual mode

Usage:

  • CtrlC to comment a single line
  • CtrlX to un-comment a single line
  • ShiftV and select multiple lines, then CtrlC to comment the selected multiple lines
  • ShiftV and select multiple lines, then CtrlX to un-comment the selected multiple lines

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

How to compare values which may both be null in T-SQL

You create a primary key on your fields and let the engine enforce the uniqueness. Doing IF EXISTS logic is incorrect anyway as is flawed with race conditions.

C++ floating point to integer type conversions

I believe you can do this using a cast:

float f_val = 3.6f;
int i_val = (int) f_val;

How to increase font size in the Xcode editor?

I found that in the Preferences, there is no fonts and colors selection. Guess the version is different, following is the one that works for the latest version.

Method 1

enter image description here

  • Go to Xcode -> Preferences
  • Click Themes
  • Click the T symbol in the middle of the font
  • Adjust the size at the bottom right corner

Method 2

Simply adjust with cmd + or cmd -

extract column value based on another column pandas dataframe

You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'

What is a "web service" in plain English?

The best plain English explanation comes from using an analogy:

  • Web pages allow people to communicate and collaborate with each other.
  • Web services allow programs to communicate and collaborate with each other.

Your PHP example is a web service by that definition, because the output could be consumed by another program. But in reality, HTML screen-scraping is not a reliable or maintainable way of producing web services.

How to convert this var string to URL in Swift

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

How to show disable HTML select option in by default?

Electron + React Let your two first options be like this

<option hidden="true>Choose Tagging</option>
<option disabled="disabled" default="true">Choose Tagging</option>

First to display when closed Second to display first when the list opens

How to find index of STRING array in Java from a given value?

Testable mockable interafce

public interface IArrayUtility<T> {

    int find(T[] list, T item);

}

implementation

public class ArrayUtility<T> implements IArrayUtility<T> {

    @Override
    public int find(T[] array, T search) {
        if(array == null || array.length == 0 || search == null) {
            return -1;
        }

        int position = 0;

        for(T item : array) {

            if(item.equals(search)) {
                return position;
            } else {
                ++position;
            }
        }

        return -1;
    }

}

Test

@Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
    // Arrange
    String search = "bus";
    String[] array = {"car", search, "motorbike"};

    // Act
    int position = arrayUtility.find(array, search);

    // Assert
    Assert.assertEquals(position, 1);
}

Error related to only_full_group_by when executing a query in MySql

I would just add group_id to the GROUP BY.

When SELECTing a column that is not part of the GROUP BY there could be multiple values for that column within the groups, but there will only be space for a single value in the results. So, the database usually needs to be told exactly how to make those multiple values into one value. Commonly, this is done with an aggregate function like COUNT(), SUM(), MAX() etc... I say usually because most other popular database systems insist on this. However, in MySQL prior to version 5.7 the default behaviour has been more forgiving because it will not complain and then arbitrarily choose any value! It also has an ANY_VALUE() function that could be used as another solution to this question if you really needed the same behaviour as before. This flexibility comes at a cost because it is non-deterministic, so I would not recommend it unless you have a very good reason for needing it. MySQL are now turning on the only_full_group_by setting by default for good reasons, so it's best to get used to it and make your queries comply with it.

So why my simple answer above? I've made a couple of assumptions:

1) the group_id is unique. Seems reasonable, it is an 'ID' after all.

2) the group_name is also unique. This may not be such a reasonable assumption. If this is not the case and you have some duplicate group_names and you then follow my advice to add group_id to the GROUP BY, you may find that you now get more results than before because the groups with the same name will now have separate rows in the results. To me, this would be better than having these duplicate groups hidden because the database has quietly selected a value arbitrarily!

It's also good practice to qualify all the columns with their table name or alias when there's more than one table involved...

SELECT 
  g.group_id AS 'value', 
  g.group_name AS 'text' 
FROM mod_users_groups g
LEFT JOIN mod_users_data d ON g.group_id = d.group_id 
WHERE g.active = 1 
  AND g.department_id = 1 
  AND g.manage_work_orders = 1 
  AND g.group_name != 'root' 
  AND g.group_name != 'superuser' 
GROUP BY 
  g.group_name, 
  g.group_id 
HAVING COUNT(d.user_id) > 0 
ORDER BY g.group_name

How to encode a URL in Swift

Just completing Desmond Hume's answer to extend the String class for a RFC 3986 unreserved characters valid encoding function (needed if you are encoding query FORM parameters):

Swift 3

extension String {

    var RFC3986UnreservedEncoded:String {
        let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
        let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
        let encodedString: String = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
        return encodedString
    }
}

curl error 18 - transfer closed with outstanding read data remaining

I had this problem working with pycurl and I solved it using

c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0) 

like Eric Caron says.

How do you remove an array element in a foreach loop?

If you also get the key, you can delete that item like this:

foreach ($display_related_tags as $key => $tag_name) {
    if($tag_name == $found_tag['name']) {
        unset($display_related_tags[$key]);
    }
}

RESTful Authentication

That's the way to do that: Using OAuth 2.0 for Login.

You may use other authentication methods other then Google's as long as it supports OAuth.

Get user location by IP address

I have tried using http://ipinfo.io and this JSON API works perfectly. First, you need to add the below mentioned namespaces:

using System.Linq;
using System.Web; 
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;

For localhost it will give dummy data as AU. You can try hardcoding your IP and get results:

namespace WebApplication4
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
         {

          string VisitorsIPAddr = string.Empty;
          //Users IP Address.                
          if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
          {
              //To get the IP address of the machine and not the proxy
              VisitorsIPAddr =   HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
          }
          else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
          {
              VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here`
          }

          string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city";
          string ipResponse = IPRequestHelper(res);

        }

        public string IPRequestHelper(string url)
        {

            string checkURL = url;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
            string responseRead = responseStream.ReadToEnd();
            responseRead = responseRead.Replace("\n", String.Empty);
            responseStream.Close();
            responseStream.Dispose();
            return responseRead;
        }


    }
}

Passing an array of parameters to a stored procedure

What about using the XML data type instead of passing an array. I find that a better solution and works well in SQL 2005

What is the difference between HTTP and REST?

REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.

What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface

How do you round UP a number in Python?

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2

How to load a tsv file into a Pandas DataFrame?

Try this

df = pd.read_csv("rating-data.tsv",sep='\t')
df.head()

enter image description here

You actually need to fix the sep parameter.

Laravel: Auth::user()->id trying to get a property of a non-object

Your question and code sample are a little vague, and I believe the other developers are focusing on the wrong thing. I am making an application in Laravel, have used online tutorials for creating a new user and authentication, and seemed to have noticed that when you create a new user in Laravel, no Auth object is created - which you use to get the (new) logged-in user's ID in the rest of the application. This is a problem, and I believe what you may be asking. I did this kind of cludgy hack in userController::store :

$user->save();

Session::flash('message','Successfully created user!');

//KLUDGE!! rest of site depends on user id in auth object - need to force/create it here
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true);

Redirect::to('users/' . Auth::user()->id);

Shouldn't have to create and authenticate, but I didn't know what else to do.

MySQL select 10 random rows from 600K rows fast

This is super fast and is 100% random even if you have gaps.

  1. Count the number x of rows that you have available SELECT COUNT(*) as rows FROM TABLE
  2. Pick 10 distinct random numbers a_1,a_2,...,a_10 between 0 and x
  3. Query your rows like this: SELECT * FROM TABLE LIMIT 1 offset a_i for i=1,...,10

I found this hack in the book SQL Antipatterns from Bill Karwin.

How to hide the title bar for an Activity in XML with existing custom theme

I don't like the this.requestWindowFeature(Window.FEATURE_NO_TITLE); because the title bar appears briefly, then disappears.

I also don't like the android:theme="@android:style/Theme.NoTitleBar" because I lost all of the 3.0+ Holo changes that the users of the new devices have gotten used to. So I came across this solution.

In your res/values folder make a file called styles.xml (If it doesn't already exist). In that file place the following code:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="Theme.Default" parent="@android:style/Theme"></style>
    <style name="Theme.NoTitle" parent="@android:style/Theme.NoTitleBar"></style>
    <style name="Theme.FullScreen" parent="@android:style/Theme.NoTitleBar.Fullscreen"></style>
</resources>

Next create a res/values-v11 with another styles.xml file (Once again this may already exist). In that file place the following code:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="Theme.Default" parent="@android:style/Theme.Holo"></style>
    <style name="Theme.NoTitle" parent="@android:style/Theme.Holo.NoActionBar"></style>
    <style name="Theme.FullScreen" parent="@android:style/Theme.Holo.NoActionBar.Fullscreen"></style>
</resources>

And if you are targeting 4.0+, create a res/values-v14 folder with yet another styles.xml file (Yes it may already be there). In that file place the following code:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="Theme.Default" parent="@android:style/Theme.Holo.Light"></style>
    <style name="Theme.NoTitle" parent="@android:style/Theme.Holo.Light.NoActionBar"></style>
    <style name="Theme.FullScreen" parent="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen"></style>
</resources>

Finally, with all of these files created, open your AndroidManifiest.xml file you can add the code:

android:theme="@style/Theme.NoTitle"

to the activity tag of the activity you want no title for or the application tag if you want it to apply to the entire application.

Now your users will get the themes associated with their device version with the screen layout you desire.

P.S. Changing the value to android:theme="@style/Theme.FullScreen" will have the same effect, but also remove Notification bar.

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

IE8 css selector

I realize this is an old question but it was the first result on Google when I searched and I think I have found a better solution than the highest ranked suggestion and what the OP chose to do.

#nav li ul:not(.stupidIE) { color:red }

So technically this is the opposite of what the OP wanted, but that just means you have to apply the rule you want for IE8 first and then apply this for everything else. Of course you can put anything inside the () as long as it is valid css that doesn't actually select anything. IE8 chokes on this line and doesn't apply it, but previous IEs (ok I only checked IE7, I have stopped caring about IE6), just ignore the :not() and do apply the declarations. And of course every other browser (I tested Safari 5, Opera 10.5, Firefox 3.6) applies that css as you would expect.

So this solution, I guess like any other pure CSS solution would assume that if the IE developers add support for the :not selector then they will also fix what ever discrepancy was causing you to target IE8.

Link to all Visual Studio $ variables

Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE), but I wanted to err on the side of inclusiveness here.

For example, this is the first time that I see $(Language) (expanding to C++ for this project) being mentioned outside of the IDE.

$(AllowLocalNetworkLoopback)
$(ALLUSERSPROFILE)
$(AndroidTargetsPath)
$(APPDATA)
$(AppxManifestMetadataClHostArchDir)
$(AppxManifestMetadataCITargetArchDir)
$(Attach)
$(BaseIntermediateOutputPath)
$(BuildingInsideVisualStudio)
$(CharacterSet)
$(CLRSupport)
$(CommonProgramFiles)
$(CommonProgramW6432)
$(COMPUTERNAME)
$(ComSpec)
$(Configuration)
$(ConfigurationType)
$(CppWinRT_IncludePath)
$(CrtSDKReferencelnclude)
$(CrtSDKReferenceVersion)
$(CustomAfterMicrosoftCommonProps)
$(CustomBeforeMicrosoftCommonProps)
$(DebugCppRuntimeFilesPath)
$(DebuggerFlavor)
$(DebuggerLaunchApplication)
$(DebuggerRequireAuthentication)
$(DebuggerType)
$(DefaultLanguageSourceExtension)
$(DefaultPlatformToolset)
$(DefaultWindowsSDKVersion)
$(DefineExplicitDefaults)
$(DelayImplib)
$(DesignTimeBuild)
$(DevEnvDir)
$(DocumentLibraryDependencies)
$(DotNetSdk_IncludePath)
$(DotNetSdk_LibraryPath)
$(DotNetSdk_LibraryPath_arm)
$(DotNetSdk_LibraryPath_arm64)
$(DotNetSdk_LibraryPath_x64)
$(DotNetSdk_LibraryPath_x86)
$(DotNetSdkRoot)
$(DriverData)
$(EmbedManifest)
$(EnableManagedIncrementalBuild)
$(EspXtensions)
$(ExcludePath)
$(ExecutablePath)
$(ExtensionsToDeleteOnClean)
$(FPS_BROWSER_APP_PROFILE_STRING)
$(FPS_BROWSER_USER_PROFILE_STRING)
$(FrameworkDir)
$(FrameworkDir_110)
$(FrameworkSdkDir)
$(FrameworkSDKRoot)
$(FrameworkVersion)
$(GenerateManifest)
$(GPURefDebuggerBreakOnAllThreads)
$(HOMEDRIVE)
$(HOMEPATH)
$(IgnorelmportLibrary)
$(ImportByWildcardAfterMicrosoftCommonProps)
$(ImportByWildcardBeforeMicrosoftCommonProps)
$(ImportDirectoryBuildProps)
$(ImportProjectExtensionProps)
$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps)
$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps)
$(IncludePath)
$(IncludeVersionInInteropName)
$(IntDir)
$(InteropOutputPath)
$(iOSTargetsPath)
$(Keyword)
$(KIT_SHARED_IncludePath)
$(LangID)
$(LangName)
$(Language)
$(LIBJABRA_TRACE_LEVEL)
$(LibraryPath)
$(LibraryWPath)
$(LinkCompiled)
$(LinkIncremental)
$(LOCALAPPDATA)
$(LocalDebuggerAttach)
$(LocalDebuggerDebuggerlType)
$(LocalDebuggerMergeEnvironment)
$(LocalDebuggerSQLDebugging)
$(LocalDebuggerWorkingDirectory)
$(LocalGPUDebuggerTargetType)
$(LOGONSERVER)
$(MicrosoftCommonPropsHasBeenImported)
$(MpiDebuggerCleanupDeployment)
$(MpiDebuggerDebuggerType)
$(MpiDebuggerDeployCommonRuntime)
$(MpiDebuggerNetworkSecurityMode)
$(MpiDebuggerSchedulerNode)
$(MpiDebuggerSchedulerTimeout)
$(MSBuild_ExecutablePath)
$(MSBuildAllProjects)
$(MSBuildAssemblyVersion)
$(MSBuildBinPath)
$(MSBuildExtensionsPath)
$(MSBuildExtensionsPath32)
$(MSBuildExtensionsPath64)
$(MSBuildFrameworkToolsPath)
$(MSBuildFrameworkToolsPath32)
$(MSBuildFrameworkToolsPath64)
$(MSBuildFrameworkToolsRoot)
$(MSBuildLoadMicrosoftTargetsReadOnly)
$(MSBuildNodeCount)
$(MSBuildProgramFiles32)
$(MSBuildProjectDefaultTargets)
$(MSBuildProjectDirectory)
$(MSBuildProjectDirectoryNoRoot)
$(MSBuildProjectExtension)
$(MSBuildProjectExtensionsPath)
$(MSBuildProjectFile)
$(MSBuildProjectFullPath)
$(MSBuildProjectName)
$(MSBuildRuntimeType)
$(MSBuildRuntimeVersion)
$(MSBuildSDKsPath)
$(MSBuildStartupDirectory)
$(MSBuildToolsPath)
$(MSBuildToolsPath32)
$(MSBuildToolsPath64)
$(MSBuildToolsRoot)
$(MSBuildToolsVersion)
$(MSBuildUserExtensionsPath)
$(MSBuildVersion)
$(MultiToolTask)
$(NETFXKitsDir)
$(NETFXSDKDir)
$(NuGetProps)
$(NUMBER_OF_PROCESSORS)
$(OCTAVE_EXECUTABLE)
$(OneDrive)
$(OneDriveCommercial)
$(OS)
$(OutDir)
$(OutDirWasSpecified)
$(OutputType)
$(Path)
$(PATHEXT)
$(PkgDefApplicationConfigFile)
$(Platform)
$(Platform_Actual)
$(PlatformArchitecture)
$(PlatformName)
$(PlatformPropsFound)
$(PlatformShortName)
$(PlatformTarget)
$(PlatformTargetsFound)
$(PlatformToolset)
$(PlatformToolsetVersion)
$(PostBuildEventUseInBuild)
$(PreBuildEventUseInBuild)
$(PreferredToolArchitecture)
$(PreLinkEventUselnBuild)
$(PROCESSOR_ARCHITECTURE)
$(PROCESSOR_ARCHITEW6432)
$(PROCESSOR_IDENTIFIER)
$(PROCESSOR_LEVEL)
$(PROCESSOR_REVISION)
$(ProgramData)
$(ProgramFiles)
$(ProgramW6432)
$(ProjectDir)
$(ProjectExt)
$(ProjectFileName)
$(ProjectGuid)
$(ProjectName)
$(ProjectPath)
$(PSExecutionPolicyPreference)
$(PSModulePath)
$(PUBLIC)
$(ReferencePath)
$(RemoteDebuggerAttach)
$(RemoteDebuggerConnection)
$(RemoteDebuggerDebuggerlype)
$(RemoteDebuggerDeployDebugCppRuntime)
$(RemoteDebuggerServerName)
$(RemoteDebuggerSQLDebugging)
$(RemoteDebuggerWorkingDirectory)
$(RemoteGPUDebuggerTargetType)
$(RetargetAlwaysSupported)
$(RootNamespace)
$(RoslynTargetsPath)
$(SDK35ToolsPath)
$(SDK40ToolsPath)
$(SDKDisplayName)
$(SDKIdentifier)
$(SDKVersion)
$(SESSIONNAME)
$(SolutionDir)
$(SolutionExt)
$(SolutionFileName)
$(SolutionName)
$(SolutionPath)
$(SourcePath)
$(SpectreMitigation)
$(SQLDebugging)
$(SystemDrive)
$(SystemRoot)
$(TargetExt)
$(TargetFrameworkVersion)
$(TargetName)
$(TargetPlatformMinVersion)
$(TargetPlatformVersion)
$(TargetPlatformWinMDLocation)
$(TargetUniversalCRTVersion)
$(TEMP)
$(TMP)
$(ToolsetPropsFound)
$(ToolsetTargetsFound)
$(UCRTContentRoot)
$(UM_IncludePath)
$(UniversalCRT_IncludePath)
$(UniversalCRT_LibraryPath_arm)
$(UniversalCRT_LibraryPath_arm64)
$(UniversalCRT_LibraryPath_x64)
$(UniversalCRT_LibraryPath_x86)
$(UniversalCRT_PropsPath)
$(UniversalCRT_SourcePath)
$(UniversalCRTSdkDir)
$(UniversalCRTSdkDir_10)
$(UseDebugLibraries)
$(UseLegacyManagedDebugger)
$(UseOfATL)
$(UseOfMfc)
$(USERDOMAIN)
$(USERDOMAIN_ROAMINGPROFILE)
$(USERNAME)
$(USERPROFILE)
$(UserRootDir)
$(VBOX_MSI_INSTALL_PATH)
$(VC_ATLMFC_IncludePath)
$(VC_ATLMFC_SourcePath)
$(VC_CRT_SourcePath)
$(VC_ExecutablePath_ARM)
$(VC_ExecutablePath_ARM64)
$(VC_ExecutablePath_x64)
$(VC_ExecutablePath_x64_ARM)
$(VC_ExecutablePath_x64_ARM64)
$(VC_ExecutablePath_x64_x64)
$(VC_ExecutablePath_x64_x86)
$(VC_ExecutablePath_x86)
$(VC_ExecutablePath_x86_ARM)
$(VC_ExecutablePath_x86_ARM64)
$(VC_ExecutablePath_x86_x64)
$(VC_ExecutablePath_x86_x86)
$(VC_IFCPath)
$(VC_IncludePath)
$(VC_LibraryPath_ARM)
$(VC_LibraryPath_ARM64)
$(VC_LibraryPath_ATL_ARM)
$(VC_LibraryPath_ATL_ARM64)
$(VC_LibraryPath_ATL_x64)
$(VC_LibraryPath_ATL_x86)
$(VC_LibraryPath_VC_ARM)
$(VC_LibraryPath_VC_ARM_Desktop)
$(VC_LibraryPath_VC_ARM_OneCore)
$(VC_LibraryPath_VC_ARM_Store)
$(VC_LibraryPath_VC_ARM64)
$(VC_LibraryPath_VC_ARM64_Desktop)
$(VC_LibraryPath_VC_ARM64_OneCore)
$(VC_LibraryPath_VC_ARM64_Store)
$(VC_LibraryPath_VC_x64)
$(VC_LibraryPath_VC_x64_Desktop)
$(VC_LibraryPath_VC_x64_OneCore)
$(VC_LibraryPath_VC_x64_Store)
$(VC_LibraryPath_VC_x86)
$(VC_LibraryPath_VC_x86_Desktop)
$(VC_LibraryPath_VC_x86_OneCore)
$(VC_LibraryPath_VC_x86_Store)
$(VC_LibraryPath_x64)
$(VC_LibraryPath_x86)
$(VC_PGO_RunTime_Dir)
$(VC_ReferencesPath_ARM)
$(VC_ReferencesPath_ARM64)
$(VC_ReferencesPath_ATL_ARM)
$(VC_ReferencesPath_ATL_ARM64)
$(VC_ReferencesPath_ATL_x64)
$(VC_ReferencesPath_ATL_x86)
$(VC_ReferencesPath_VC_ARM)
$(VC_ReferencesPath_VC_ARM64)
$(VC_ReferencesPath_VC_x64)
$(VC_ReferencesPath_VC_x86)
$(VC_ReferencesPath_x64)
$(VC_ReferencesPath_x86)
$(VC_SourcePath)
$(VC_VC_IncludePath)
$(VC_VS_IncludePath)
$(VC_VS_LibraryPath_VC_VS_ARM)
$(VC_VS_LibraryPath_VC_VS_x64)
$(VC_VS_LibraryPath_VC_VS_x86)
$(VC_VS_SourcePath)
$(VCIDEInstallDir)
$(VCIDEInstallDir_150)
$(VCInstallDir)
$(VCInstallDir_150)
$(VCLibPackagePath)
$(VCProjectVersion)
$(VCTargetsPath)
$(VCTargetsPath10)
$(VCTargetsPath11)
$(VCTargetsPath12)
$(VCTargetsPath14)
$(VCTargetsPath15)
$(VCTargetsPathActual)
$(VCTargetsPathEffective)
$(VCToolArchitecture)
$(VCToolsInstallDir)
$(VCToolsInstallDir_150)
$(VCToolsVersion)
$(VisualStudioDir)
$(VisualStudioEdition)
$(VisualStudioVersion)
$(VS_ExecutablePath)
$(VS140COMNTOOLS)
$(VSAPPIDDIR)
$(VSAPPIDNAME)
$(VSInstallDir)
$(VSInstallDir_150)
$(VsInstallRoot)
$(VSLANG)
$(VSSKUEDITION)
$(VSVersion)
$(WDKBinRoot)
$(WebBrowserDebuggerDebuggerlype)
$(WebServiceDebuggerDebuggerlype)
$(WebServiceDebuggerSQLDebugging)
$(WholeProgramOptimization)
$(WholeProgramOptimizationAvailabilityInstrument)
$(WholeProgramOptimizationAvailabilityOptimize)
$(WholeProgramOptimizationAvailabilityTrue)
$(WholeProgramOptimizationAvailabilityUpdate)
$(windir)
$(Windows81SdkInstalled)
$(WindowsAppContainer)
$(WindowsSDK_ExecutablePath)
$(WindowsSDK_ExecutablePath_arm)
$(WindowsSDK_ExecutablePath_arm64)
$(WindowsSDK_ExecutablePath_x64)
$(WindowsSDK_LibraryPath_x86)
$(WindowsSDK_MetadataFoundationPath)
$(WindowsSDK_MetadataPath)
$(WindowsSDK_MetadataPathVersioned)
$(WindowsSDK_PlatformPath)
$(WindowsSDK_SupportedAPIs_arm)
$(WindowsSDK_SupportedAPIs_x64)
$(WindowsSDK_SupportedAPIs_x86)
$(WindowsSDK_UnionMetadataPath)
$(WindowsSDK80Path)
$(WindowsSdkDir)
$(WindowsSdkDir_10)
$(WindowsSdkDir_81)
$(WindowsSdkDir_81A)
$(WindowsSDKToolArchitecture)
$(WindowsTargetPlatformVersion)
$(WinRT_IncludePath)
$(WMSISProject)
$(WMSISProjectDirectory)

Where to find this list within Visual Studio:

  1. Open your C++ project's dialogue Property Pages
  2. Select any textual field that can use a configuration variable. (in the screenshot, I use Target Name)
  3. On the right side of the text box, click the small combobox button and select option <Edit...>.
  4. In the new window (here, title is Target Name), click on button Macros>>.
  5. Scroll through the giant list of environment/linker/macro variables.

Motivational screenshot:

Visual Studio project Property Pages with exemplary Macro variable list

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Better way to check variable for null or empty string?

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

How do I timestamp every ping result?

ping -D -n -O -i1 -W1 8.8.8.8

or maybe

while true; do \
    ping -n -w1 -W1 -c1 8.8.8.8 \
    | grep -E "rtt|100%" \
    | sed -e "s/^/`date` /g"; \
    sleep 1; \
done

use current date as default value for a column

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page in column properties set Default value or binding to : 'getdate()'

What is an opaque response, and what purpose does it serve?

There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html

JavaScript: Class.method vs. Class.prototype.method

Yes, the first one is a static method also called class method, while the second one is an instance method.

Consider the following examples, to understand it in more detail.

In ES5

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}

Person.isPerson = function(obj) {
   return obj.constructor === Person;
}

Person.prototype.sayHi = function() {
   return "Hi " + this.firstName;
}

In the above code, isPerson is a static method, while sayHi is an instance method of Person.

Below, is how to create an object from Person constructor.

var aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

In ES6

class Person {
   constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   static isPerson(obj) {
      return obj.constructor === Person;
   }

   sayHi() {
      return `Hi ${this.firstName}`;
   }
}

Look at how static keyword was used to declare the static method isPerson.

To create an object of Person class.

const aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.

How to write JUnit test with Spring Autowire?

You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

Username and password in command for git push

For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:

git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git

Programmatically close aspx page from code behind

 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Or like this :

npm install cors

cors = require("cors");
app.use(cors());

When to use 'raise NotImplementedError'?

You might want to you use the @property decorator,

>>> class Foo():
...     @property
...     def todo(self):
...             raise NotImplementedError("To be implemented")
... 
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in todo
NotImplementedError: To be implemented

Check if a Postgres JSON array contains a string

As of PostgreSQL 9.4, you can use the ? operator:

select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';

You can even index the ? query on the "food" key if you switch to the jsonb type instead:

alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';

Of course, you probably don't have time for that as a full-time rabbit keeper.

Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:

d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(#   where food::text = '"carrots"'
d(# );
 Execution time: 3084.927 ms

d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
 Execution time: 1255.501 ms

d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 465.919 ms

d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 256.478 ms

Scikit-learn train_test_split with indices

You can use pandas dataframes or series as Julien said but if you want to restrict your-self to numpy you can pass an additional array of indices:

from sklearn.model_selection import train_test_split
import numpy as np
n_samples, n_features, n_classes = 10, 2, 2
data = np.random.randn(n_samples, n_features)  # 10 training examples
labels = np.random.randint(n_classes, size=n_samples)  # 10 labels
indices = np.arange(n_samples)
x1, x2, y1, y2, idx1, idx2 = train_test_split(
    data, labels, indices, test_size=0.2)

Debugging in Maven?

I use the MAVEN_OPTS option, and find it useful to set suspend to "suspend=y" as my exec:java programs tend to be small generators which are finished before I have manage to attach a debugger.... :) With suspend on it will wait for a debugger to attach before proceding.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.

Seeing the Inner exception can help.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

How to use Java property files?

Example:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file 
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ",";                         //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);

How to implement an STL-style iterator and avoid common pitfalls?

And now a keys iterator for range-based for loop.

template<typename C>
class keys_it
{
    typename C::const_iterator it_;
public:
    using key_type        = typename C::key_type;
    using pointer         = typename C::key_type*;
    using difference_type = std::ptrdiff_t;

    keys_it(const typename C::const_iterator & it) : it_(it) {}

    keys_it         operator++(int               ) /* postfix */ { return it_++         ; }
    keys_it&        operator++(                  ) /*  prefix */ { ++it_; return *this  ; }
    const key_type& operator* (                  ) const         { return it_->first    ; }
    const key_type& operator->(                  ) const         { return it_->first    ; }
    keys_it         operator+ (difference_type v ) const         { return it_ + v       ; }
    bool            operator==(const keys_it& rhs) const         { return it_ == rhs.it_; }
    bool            operator!=(const keys_it& rhs) const         { return it_ != rhs.it_; }
};

template<typename C>
class keys_impl
{
    const C & c;
public:
    keys_impl(const C & container) : c(container) {}
    const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
    const keys_it<C> end  () const { return keys_it<C>(std::end  (c)); }
};

template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }

Usage:

std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
    // do things
}

That's what i was looking for. But nobody had it, it seems.

You get my OCD code alignment as a bonus.

As an exercise, write your own for values(my_map)

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

Fatal error: Call to undefined function socket_create()

If you are using xampp 7.3.9. socket already installed. You can check xampp\php\ext and you will get the php_socket.dll. if you get it go to your xampp control panel open php.ini file and remove (;) from extension=sockets.

How to run only one task in ansible playbook?

See my answer here: Run only one task and handler from ansible playbook

It is possible to run separate role (from roles/ dir):

ansible -i stage.yml -m include_role -a name=create-os-user localhost

and separate task file:

ansible -i stage.yml -m include_tasks -a file=tasks/create-os-user.yml localhost

If you externalize tasks from role to root tasks/ directory (reuse is achieved by import_tasks: ../../../tasks/create-os-user.yml) you can run it independently from playbook/role.