Programs & Examples On #Java service wrapper

The Java Service Wrapper enables a Java Application to be run as a Windows Service or Unix Daemon.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Uploading/Displaying Images in MVC 4

Have a look at the following

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

your controller should have action method which would accept HttpPostedFileBase;

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

Update 1

In case you want to upload files using jQuery with asynchornously, then try this article.

the code to handle the server side (for multiple upload) is;

 try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

Switching to landscape mode in Android Emulator

Just a little bug (Bug for me) I found on mac emulator.

On changing the orientation to landscape (CtrlCmdF11) it changes to landscape but content shows in portrait format.for that:

Go to emulator: Settings-> Display->When device is rotated->Rotate the contents of the screen

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

How to generate xsd from wsdl

Follow these steps :

  1. Create a project using the WSDL.
  2. Choose your interface and open in interface viewer.
  3. Navigate to the tab 'WSDL Content'.
  4. Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
  5. select the folder where you want the XSDs to be exported to.

Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot : enter image description here

How to run Nginx within a Docker container without halting?

It is also good idea to use supervisord or runit[1] for service management.

[1] https://github.com/phusion/baseimage-docker

How to include static library in makefile

Make sure that the -L option appears ahead of the -l option; the order of options in linker command lines does matter, especially with static libraries. The -L option specifies a directory to be searched for libraries (static or shared). The -lname option specifies a library which is with libmine.a (static) or libmine.so (shared on most variants of Unix, but Mac OS X uses .dylib and HP-UX used to use .sl). Conventionally, a static library will be in a file libmine.a. This is convention, not mandatory, but if the name is not in the libmine.a format, you cannot use the -lmine notation to find it; you must list it explicitly on the compiler (linker) command line.

The -L./libmine option says "there is a sub-directory called libmine which can be searched to find libraries". I can see three possibilities:

  1. You have such a sub-directory containing libmine.a, in which case you also need to add -lmine to the linker line (after the object files that reference the library).
  2. You have a file libmine that is a static archive, in which case you simply list it as a file ./libmine with no -L in front.
  3. You have a file libmine.a in the current directory that you want to pick up. You can either write ./libmine.a or -L . -lmine and both should find the library.

JUnit 5: How to assert an exception is thrown?

They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:

@Test
public void wrongInput() {
    Throwable exception = assertThrows(InvalidArgumentException.class,
            ()->{objectName.yourMethod("WRONG");} );
}

How do I get elapsed time in milliseconds in Ruby?

%L gives milliseconds in ruby

require 'time'
puts Time.now.strftime("%Y-%m-%dT%H:%M:%S.%L")

or

puts Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")

will give you current timestamp in milliseconds.

jQuery Scroll to bottom of page/iframe

This one worked for me:

var elem = $('#box');
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
  // We're at the bottom.
}

Does MySQL ignore null values on unique constraints?

Yes, MySQL allows multiple NULLs in a column with a unique constraint.

CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;

Result:

x
NULL
NULL
1

This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

Javascript switch vs. if...else if...else

  1. If there is a difference, it'll never be large enough to be noticed.
  2. N/A
  3. No, they all function identically.

Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.

Illegal mix of collations error in MySql

You need to set 'utf8' for all parameters in each Function. It's my case:

enter image description here

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

Field 'browser' doesn't contain a valid alias configuration

In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.

const path = require('path');

const config = {
    mode: 'development',
    entry: "./lib/components/Index.js",
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: path.resolve(__dirname, "node_modules")
            }
        ]
    }
}

// pay attention to "export!s!" here
module.exports = config;

Uncaught SyntaxError: Unexpected token with JSON.parse

Check this code. It gives you the clear solution of JSON parse error. It commonly happen by the newlines and the space between json key start and json key end

data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")  
               .replace(/\"[\n\s]{1,}/g, "\"")  
               .replace(/[\n]/g, "\\n") 

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

Using <style> tags in the <body> with other HTML

BREAKING BAD NEWS for "style in body" lovers: W3C has recently lost the HTML war against WHATWG, whose versionless HTML "Living Standard" has now become the official one, which, alas, does not allow STYLE in the BODY. The short-lived happy days are over. ;) The W3C validator also works by the WHATWG specs now. (Thanks @FrankConijn for the heads-up!)

(Note: this is the case "as of today", but since there's no versioning, links can become invalid at any moment without notice or control. Unless you're willing to link to its individual source commits at GitHub, you basically can no longer make stable references to the new official HTML standard, AFAIK. Please correct me if there's a canonical way of doing this properly.)

OBSOLETED GOOD NEWS:

Yay, STYLE is finally valid in BODY, as of HTML5.2! (And scoped is gone, too.)

From the W3C specs (relish the last line!):

4.2.6. The style element

...

Contexts in which this element can be used:

Where metadata content is expected.

In a noscript element that is a child of a head element.

In the body, where flow content is expected.


META SIDE-NOTE:

The mere fact that despite the damages of the "browser war" we still had to keep developing against two ridiculously competing "official" HTML "standards" (quotes for 1 standard + 1 standard < 1 standard) means that the "fallback to in-the-trenches common sense" approach to web development has never really ceased to apply.

This may finally change now, but citing the conventional wisdom: web authors/developers and thus, in turn, browsers should ultimately decide what should (and shouldn't) be in the specifications, when there's no good reason against what's already been done in reality. And most browsers have long supported STYLE in BODY (in one way or another; see e.g. the scoped attr.), despite its inherent performance (and possibly other) penalties (which we should decide to pay or not, not the specs.). So, for one, I'll keep betting on them, and not going to give up hope. ;) If WHATWG has the same respect for reality/authors as they claim, they may just end up doing here what the W3C did.

Create Map in Java

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

FromBody string parameter is giving null

Referencing Parameter Binding in ASP.NET Web API

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

[Route("Edit/Test")]
[HttpPost]
public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }

In this example, Web API will use a media-type formatter to read the value of jsonString from the request body. Here is an example client request.

POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/json
Content-Length: 6

"test"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

In the above example no model is needed if the data is provided in the correct format in the body.

For URL encoded a request would look like this

POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/x-www-form-urlencoded
Content-Length: 5

=test

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

How can I validate a string to only allow alphanumeric characters in it?

You could do it easily with an extension function rather than a regex ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

Per comment :) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}

Is it possible to have a default parameter for a mysql stored procedure?

If you look into CREATE PROCEDURE Syntax for latest MySQL version you'll see that procedure parameter can only contain IN/OUT/INOUT specifier, parameter name and type.

So, default values are still unavailable in latest MySQL version.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

How to disable and then enable onclick event on <div> with javascript

First of all this is JavaScript and not C#

Then you cannot disable a div because it normally has no functionality. To disable a click event, you simply have to remove the event from the dom object. (bind and unbind)...

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How to add an item to an ArrayList in Kotlin?

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

How to get value from form field in django framework?

It is easy if you are using django version 3.1 and above

def login_view(request):
    if(request.POST):
        yourForm= YourForm(request.POST)
        itemValue = yourForm['your_filed_name'].value()
        # Check if you get the value
        return HttpResponse(itemValue )
    else:
        return render(request, "base.html")

Hiding user input on terminal in Linux script

A bit different from (but mostly like) @lesmana's answer

stty -echo
read password
stty echo

simply: hide echo do your stuff show echo

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

How do I specify local .gem files in my Gemfile?

Seems bundler can't use .gem files out of the box. Pointing the :path to a directory containing .gem files doesn't work. Some people suggested to setup a local gem server (geminabox, stickler) for that purpose.

However, what I found to be much simpler is to use a local gem "server" from file system: Just put your .gem files in a local directory, then use "gem generate_index" to make it a Gem repository

mkdir repo
mkdir repo/gems
cp *.gem repo/gems
cd repo
gem generate_index

Finally point bundler to this location by adding the following line to your Gemfile

source "file://path/to/repo"

If you update the gems in the repository, make sure to regenerate the index.

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

How can I put a database under git (version control)?

I've released a tool for sqlite that does what you're asking for. It uses a custom diff driver leveraging the sqlite projects tool 'sqldiff', UUIDs as primary keys, and leaves off the sqlite rowid. It is still in alpha so feedback is appreciated.

Postgres and mysql are trickier, as the binary data is kept in multiple files and may not even be valid if you were able to snapshot it.

https://github.com/cannadayr/git-sqlite

How to error handle 1004 Error with WorksheetFunction.VLookup?

There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:

Sub new1()

Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")

currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)

If Err.Number <> 0 Then
''error appeared
    MsgBox "currName not found" ''optional, no need to do anything
End If

On Error GoTo 0 ''no error, coming back to default conditions

End Sub

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

jQuery UI Dialog with ASP.NET button postback

With ASP.NET just use UseSubmitBehavior="false" in your ASP.NET button:

<asp:Button ID="btnButton" runat="server"  Text="Button" onclick="btnButton_Click" UseSubmitBehavior="false" />       

Reference: Button.UseSubmitBehavior Property

How to trigger button click in MVC 4

as per @anaximander s answer but your signup action should look more like

    [HttpPost]
    public ActionResult SignUp(Account account)
    {
        if(ModelState.IsValid){
            //do something with account
            return RedirectToAction("Index"); 
        }
        return View("SignUp");
    }

Angular 2: How to write a for loop, not a foreach loop

You could dynamically generate an array of however time you wanted to render <li>Something</li>, and then do ngFor over that collection. Also you could take use of index of current element too.

Markup

<ul>
   <li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
      {{currentElementIndex}} Something
   </li>
</ul>

Code

createRange(number){
  var items: number[] = [];
  for(var i = 1; i <= number; i++){
     items.push(i);
  }
  return items;
}

Demo Here

Under the hood angular de-sugared this *ngFor syntax to ng-template version.

<ul>
    <ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
      {{currentElementIndex}} Something
    </ng-template>
</ul>

Initialize a byte array to a certain value, other than the default null?

Use this to create the array in the first place:

byte[] array = Enumerable.Repeat((byte)0x20, <number of elements>).ToArray();

Replace <number of elements> with the desired array size.

Get Application Directory

There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):

getApplicationInfo().dataDir

http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()

How to access random item in list?

I have been using this ExtensionMethod for a while:

public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
    if (count <= 0)
      yield break;
    var r = new Random();
    int limit = (count * 10);
    foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
      yield return item;
}

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

how to print json data in console.log

Object

input_data: Object price-row_122: " 35.1 " quantity-row_122: "1" success: true

How can I define an array of objects?

What you have above is an object, not an array.

To make an array use [ & ] to surround your objects.

userTestStatus = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" }
];

Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.

Feedback clarification from OP... in need of a definition for the model posted

You can use the types defined here to represent your object model:

type MyType = {
    id: number;
    name: string;
}

type MyGroupType = {
    [key:string]: MyType;
}

var obj: MyGroupType = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

Handling ExecuteScalar() when no results are returned

In your case either the record doesn't exist with the userid=2 or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar() returns null.

How to generate a git patch for a specific commit?

This command (as suggested already by @Naftuli Tzvi Kay):

git format-patch -1 HEAD

Replace HEAD with specific hash or range.

will generate the patch file for the latest commit formatted to resemble UNIX mailbox format.

-<n> - Prepare patches from the topmost commits.

Then you can re-apply the patch file in a mailbox format by:

git am -3k 001*.patch

See: man git-format-patch.

How to get the hostname of the docker host from inside a docker container on that host without env vars

You can pass in the hostname as an environment variable. You could also mount /etc so you can cat /etc/hostname. But I agree with Vitaly, this isn't the intended use case for containers IMO.

ReactJs: What should the PropTypes be for this.props.children?

For me it depends on the component. If you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:

PropTypes.oneOfType 

If you want to refer to a React component then you will be looking for

PropTypes.element

Although,

PropTypes.node

describes anything that can be rendered - strings, numbers, elements or an array of these things. If this suits you then this is the way.

With very generic components, who can have many types of children, you can also use the below - though bare in mind that eslint and ts may not be happy with this lack of specificity:

PropTypes.any

How do I set the default Java installation/runtime (Windows)?

I have several JDK (1.4, 1.5, 1.6) installed in C:\Java with their JREs. Then I let Sun update the public JRE in C:\Program Files\Java.
Lately there is an improvement, installing in jre6. Previously, there was a different folder per new version (1.5.0_4, 1.5.0_5, etc.), which was taking lot of space

Rounding SQL DateTime to midnight

You could round down the time.

Using ROUND below will round it down to midnight.

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >  CONVERT(datetime, (ROUND(convert(float, getdate()-6.5),0)))

Inserting HTML elements with JavaScript

As others said the convenient jQuery prepend functionality can be emulated:

var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;

While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:

If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Or:

var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)

insertAdjacentHTML is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • Image re-size to 50% of original size in HTML

    We can do this by css3 too. Try this:

    .halfsize {
        -moz-transform:scale(0.5);
        -webkit-transform:scale(0.5);
        transform:scale(0.5);
    }
    
    <img class="halfsize" src="image4.jpg">
    
    • subjected to browser compatibility

    NUnit Unit tests not showing in Test Explorer with Test Adapter installed

    I had this problem too but the cause was different. I'm using VS2017 with F# 4.0.

    Firstly, the console in Visual Studio does not give you enough details why the tests could not be found; it will just fail to the load the DLL with the tests. So use NUnit3console.exe on the command line as this gives you more details.

    In my case, it was because the test adapter was looking for a newer version of the F# Core DLL (4.4.1.0) (F# 4.1) whereas I'm still using 4.4.0.0 (F# 4.0). So I just added this to the app.config of the test project:-

      <dependentAssembly>
        <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="4.4.0.0" />
      </dependentAssembly>
    

    i.e. redirect to the earlier F# core.

    How do I login and authenticate to Postgresql after a fresh install?

    If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".

    Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.

    MySQL: Invalid use of group function

    First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

    Second, instead of using a subquery, simply join the table to itself:

    SELECT a.pid 
    FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
    WHERE a.sid != b.sid
    GROUP BY a.pid
    

    Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

    Using external images for CSS custom cursors

    It wasn't working because your image was too big - there are restrictions on the image dimensions. In Firefox, for example, the size limit is 128x128px. See this page for more details.

    Additionally, you also have to add in auto.

    jsFiddle demo here - note that's an actual image, and not a default cursor.

    _x000D_
    _x000D_
    .test {_x000D_
      background:gray;_x000D_
      width:200px;_x000D_
      height:200px;_x000D_
      cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;_x000D_
    }
    _x000D_
    <div class="test">TEST</div>
    _x000D_
    _x000D_
    _x000D_

    $watch an object

    Little performance tip if somebody has a datastore kind of service with key -> value pairs:

    If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.

    app.factory('dataStore', function () {
    
        var store = { data: [], change: [] };
    
        // when storing the data, updating the timestamp
        store.setData = function(key, data){
            store.data[key] = data;
            store.setChange(key);
        }
    
        // get the change to watch
        store.getChange = function(key){
            return store.change[key];
        }
    
        // set the change
        store.setChange = function(key){
            store.change[key] = new Date().getTime();
        }
    
    });
    

    And in a directive you are only watching the timestamp to change

    app.directive("myDir", function ($scope, dataStore) {
        $scope.dataStore = dataStore;
        $scope.$watch('dataStore.getChange("myKey")', function(newVal, oldVal){
            if(newVal !== oldVal && newVal){
                // Data changed
            }
        });
    });
    

    System.Drawing.Image to stream C#

    Use a memory stream

    using(MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, ...);
        return ms.ToArray();
    }
    

    Error 0x80005000 and DirectoryServices

    I had the same error - in my case it was extra slash in path argument that made the difference.

    BAD:

    DirectoryEntry directoryEntry = 
        new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com/", 
                           userName, password);
    

    GOOD:

    DirectoryEntry directoryEntry = 
        new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com", 
                           userName, password);
    

    C# Passing Function as Argument

    There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

    For functions with return types, there is Func<> and for functions without return types there is Action<>.

    Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

    So you can declare your Diff function to take a Func:

    public double Diff(double x, Func<double, double> f) {
        double h = 0.0000001;
    
        return (f(x + h) - f(x)) / h;
    }
    

    And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

    double result = Diff(myValue, Function);
    

    You can even write the function in-line with lambda syntax:

    double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
    

    Using a batch to copy from network drive to C: or D: drive

    Just do the following change

    echo off
    cls
    
    echo Would you like to do a backup?
    
    pause
    
    copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
    
    pause
    

    How to write JUnit test with Spring Autowire?

    Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

    Also this looks wierd to me :

    @ContextConfiguration("classpath*:conf/components.xml")
    

    Here is an example that works fine for me :

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/applicationContext_mock.xml" })
    public class OwnerIntegrationTest {
    
        @Autowired
        OwnerService ownerService;
    
        @Before
        public void setup() {
    
            ownerService.cleanList();
    
        }
    
        @Test
        public void testOwners() {
    
            Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
            owner = ownerService.createOwner(owner);
            assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
            assertTrue("Check that Id exist: ", owner.getId() > 0);
    
            owner.setLastName("Larsson");
            ownerService.updateOwner(owner);
            owner = ownerService.getOwner(owner.getId());
            assertEquals("Name is changed", "Larsson", owner.getLastName());
    
        }
    

    Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

    This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.

    Here is my code in the view

    @Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
    

    Now you can use this in the JavaScript file as:

     var url = $("#RedirectTo").val();
     location.href = url;
    

    It worked like a charm fro me. I hope it helps you too.

    How to delete all files older than 3 days when "Argument list too long"?

    Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

    find . -name "*.sess" -mtime +100 
    

    and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

    What are the differences between JSON and JSONP?

    “JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?

    Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.

    How to convert Milliseconds to "X mins, x seconds" in Java?

    Use the java.util.concurrent.TimeUnit class:

    String.format("%d min, %d sec", 
        TimeUnit.MILLISECONDS.toMinutes(millis),
        TimeUnit.MILLISECONDS.toSeconds(millis) - 
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
    );
    

    Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.

    To add a leading zero for values 0-9, just do:

    String.format("%02d min, %02d sec", 
        TimeUnit.MILLISECONDS.toMinutes(millis),
        TimeUnit.MILLISECONDS.toSeconds(millis) - 
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
    );
    

    If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:

    int seconds = (int) (milliseconds / 1000) % 60 ;
    int minutes = (int) ((milliseconds / (1000*60)) % 60);
    int hours   = (int) ((milliseconds / (1000*60*60)) % 24);
    //etc...
    

    SaveFileDialog setting default path and file type?

    The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

    1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

    2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

    Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

    SaveFileDialog savefile = new SaveFileDialog(); 
    // set a default file name
    savefile.FileName = "unknown.txt";
    // set filters - this can be done in properties as well
    savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    
    if (savefile.ShowDialog() == DialogResult.OK)
    {
        using (StreamWriter sw = new StreamWriter(savefile.FileName))
            sw.WriteLine ("Hello World!");
    }
    

    PHP read and write JSON from file

    When you want to create json format it had to be in this format for it to read:

    [ 
      {
        "":"",
        "":[
         {
           "":"",
           "":""
         }
        ]
      }
    ]
    

    MYSQL order by both Ascending and Descending sorting

    You can do that in this way:

    ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
    

    Have a look at ORDER BY Optimization

    [ :Unexpected operator in shell programming

    To execute it with Bash, use #!/bin/bash and chmod it to be executable, then use

    ./choose.sh
    

    Linux command line howto accept pairing for bluetooth device without pin

    This worked like a charm for me, of-course it requires super-user privileges :-)

    # hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>

    To get <target-bdaddr> you may issue below command:
    $ hcitool scan

    Note: Exclude # & $ as they are command line prompts.

    Courtesy

    Benefits of inline functions in C++?

    I'd like to add that inline functions are crucial when you are building shared library. Without marking function inline, it will be exported into the library in the binary form. It will be also present in the symbols table, if exported. On the other side, inlined functions are not exported, neither to the library binaries nor to the symbols table.

    It may be critical when library is intended to be loaded at runtime. It may also hit binary-compatible-aware libraries. In such cases don't use inline.

    How to prevent Browser cache for php site

    Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:

    <link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">
    

    the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.

    I use this solution to force browser to download assets only if its content is modified:

    <link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">
    

    How do I check that a Java String is not all whitespaces?

    This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is null.

    We want false if (1) s is null or (2) s is empty or (3) s only contains whitechars.

    public static boolean containsNonWhitespaceChar(String s) {
      return !((s == null) || "".equals(s.trim()));
    }
    

    Reading a resource file from within jar

    I had this problem before and I made fallback way for loading. Basically first way work within .jar file and second way works within eclipse or other IDE.

    public class MyClass {
    
        public static InputStream accessFile() {
            String resource = "my-file-located-in-resources.txt";
    
            // this is the path within the jar file
            InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource);
            if (input == null) {
                // this is how we load file within editor (eg eclipse)
                input = MyClass.class.getClassLoader().getResourceAsStream(resource);
            }
    
            return input;
        }
    }
    

    MySQL - Using COUNT(*) in the WHERE clause

    try

    SELECT DISTINCT gid
    FROM `gd`
    group by gid
    having count(*) > 10
    ORDER BY max(lastupdated) DESC
    

    How to check Oracle database for long running queries

    You can use the v$sql_monitor view to find queries that are running longer than 5 seconds. This may only be available in Enterprise versions of Oracle. For example this query will identify slow running queries from my TEST_APP service:

    select to_char(sql_exec_start, 'dd-Mon hh24:mi'), (elapsed_time / 1000000) run_time,
           cpu_time, sql_id, sql_text 
    from   v$sql_monitor
    where  service_name = 'TEST_APP'
    order  by 1 desc;
    

    Note elapsed_time is in microseconds so / 1000000 to get something more readable

    How can I see the raw SQL queries Django is running?

    Just to add, in django, if you have a query like:

    MyModel.objects.all()
    

    do:

    MyModel.objects.all().query.sql_with_params()
    

    or:

    str(MyModel.objects.all().query)
    

    to get the sql string

    Setting the focus to a text field

    I did it by setting an AncesterAdded event on the textField and the requesting focus in the window.

    Git Bash doesn't see my PATH

    I've run into a stupid mistake on my part. I had a systems wide and a user variable path set for my golang workspace on my windows 10 machine. When I removed the redundant systems variable pathway and logged off and back on, I was able to call .exe files in bash and call go env with success.

    Although OP has been answered this is another problem that could keep bash from seeing your pathways. I just tested bash again with this problem and it does seem to give a conflict of some sort that blocks bash from following either of the paths.

    Is there a method that tells my program to quit?

    Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.

    Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)

    This answer from Alex Martelli for more details.

    A tool to convert MATLAB code to Python

    There are several tools for converting Matlab to Python code.

    The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

    Other options include:

    • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
    • OMPC: Matlab to Python (a bit outdated).

    Also, for those interested in an interface between the two languages and not conversion:

    • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
    • Python-Matlab wormholes: both directions of interaction supported.
    • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
    • PyMat: Control Matlab session from Python.
    • pymat2: continuation of the seemingly abandoned PyMat.
    • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
    • oct2py: run GNU Octave commands from within Python.
    • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
    • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
    • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

    Btw might be helpful to look here for other migration tips:

    On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

    How do I remove a comma off the end of a string?

    A simple regular expression would work

    $string = preg_replace("/,$/", "", $string)
    

    How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

    Another yet simple solution is to paste these line into the build.gradle file

    dependencies {
    
        //import of gridlayout
        compile 'com.android.support:gridlayout-v7:19.0.0'
        compile 'com.android.support:appcompat-v7:+'
    }
    

    C# difference between == and Equals()

    == Operator

    1. If operands are Value Types and their values are equal, it returns true else false.
    2. If operands are Reference Types with exception of string and both refer to the same instance (same object), it returns true else false.
    3. If operands are string type and their values are equal, it returns true else false.

    .Equals

    1. If operands are Reference Types, it performs Reference Equality that is if both refer to the same instance (same object), it returns true else false.
    2. If Operands are Value Types then unlike == operator it checks for their type first and if their types are same it performs == operator else it returns false.

    Using FFmpeg in .net?

    You can use this nuget package:

    Install-Package Xabe.FFmpeg
    

    I'm trying to make easy to use, cross-platform FFmpeg wrapper.

    You can find more information about this at Xabe.FFmpeg

    More info in documentation

    Conversion is simple:

    IConversionResult result = await Conversion.ToMp4(Resources.MkvWithAudio, output).Start();
    

    How To Upload Files on GitHub

    You need to create a git repo locally, add your project files to that repo, commit them to the local repo, and then sync that repo to your repo on github. You can find good instructions on how to do the latter bit on github, and the former should be easy to do with the software you've downloaded.

    `IF` statement with 3 possible answers each based on 3 different ranges

    Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

    logout and redirecting session in php

    Use this instead:

    <?
    session_start();
    session_unset();
    session_destroy();
    
    header("location:home.php");
    exit();
    ?>
    

    grid controls for ASP.NET MVC?

    If it's just for viewing data, I use simple foreach or even aspRepeater. For editing I build specialized views and actions. Didn't like webforms GridView inline edit capabilities anyway, this is kinda much clearer and better - one view for viewing and another for edit/new.

    What does "#include <iostream>" do?

    That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.

    Getting list of lists into pandas DataFrame

    Call the pd.DataFrame constructor directly:

    df = pd.DataFrame(table, columns=headers)
    df
    
       Heading1  Heading2
    0         1         2
    1         3         4
    

    Eclipse add Tomcat 7 blank server name

    I also had this problem today, and deleting files org.eclipse.jst.server.tomcat.core.prefs and org.eclipse.wst.server.core.prefs didn't work.

    Finally I found it's permission issue:

    By default <apache-tomcat-version>/conf/* can be read only by owner, after I made it readable for all, it works! So run this command:

    chmod a+r <apache-tomcat-version>/conf/*
    

    Here is the link where I found the root cause:

    http://www.thecodingforums.com/threads/eclipse-cannot-create-tomcat-server.953960/#post-5058434

    Convert string to BigDecimal in java

    Hi Guys you cant convert directly string to bigdecimal

    you need to first convert it into long after that u will convert big decimal

    String currency = "135.69"; 
    Long rate1=Long.valueOf((currency ));            
    System.out.println(BigDecimal.valueOf(rate1));
    

    @import vs #import - iOS 7

    History:

    #include => #import => .pch => @import
    

    [#include vs #import]
    [.pch - Precompiled header]

    Module - @import

    Product Name == Product Module Name 
    

    @import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

    If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

    enter image description here

    PHP sessions that have already been started

    <?php
    if ( session_id() != "" ) {
        session_start();
    }
    

    Basically, you need to check if a session was started before creating another one; ... more reading.

    On the other hand, you chose to destroy an existing session before creating another one using session_destroy().

    ZIP file content type for HTTP request

    [request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
    

    Where is the visual studio HTML Designer?

    Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.

    How to create Python egg file

    For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.

    python myapp.zip
    

    Where myapp.zip is a zip containing a __main__.py file which is executed as the script file to be executed. Your package dependencies can also be included in the file:

    __main__.py
    mypackage/__init__.py
    mypackage/someliblibfile.py
    

    You can also execute an egg, but the incantation is not as nice:

    # Bourn Shell and derivatives (Linux/OSX/Unix)
    PYTHONPATH=myapp.egg python -m myapp
    
    rem Windows 
    set PYTHONPATH=myapp.egg
    python -m myapp
    

    This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:

    myapp/__init__.py
    myapp/somelibfile.py
    

    And python will run __init__.py (you should check that __file__=='__main__' in your app for command line use).

    Egg files are just zip files so you might be able to add __main__.py to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg instead of the above incantation where the PYTHONPATH environment variable is set.

    More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.

    How to rename array keys in PHP?

    Talking about functional PHP, I have this more generic answer:

        array_map(function($arr){
            $ret = $arr;
            $ret['value'] = $ret['url'];
            unset($ret['url']);
            return $ret;
        }, $tag);
    }
    

    How to make an Android device vibrate? with different frequency?

    Vibrating in Patterns/Waves:

    import android.os.Vibrator;
    ...
    // Vibrate for 500ms, pause for 500ms, then start again
    private static final long[] VIBRATE_PATTERN = { 500, 500 };
    
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // API 26 and above
        mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
    } else {
        // Below API 26
        mVibrator.vibrate(VIBRATE_PATTERN, 0);
    }
    

    Plus

    The necessary permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.VIBRATE"/>
    

    Install numpy on python3.3 - Install pip for python3

    My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:

    python3 -m pip install numpy
    

    How do I find the location of my Python site-packages directory?

    There are two types of site-packages directories, global and per user.

    1. Global site-packages ("dist-packages") directories are listed in sys.path when you run:

      python -m site
      

      For a more concise list run getsitepackages from the site module in Python code:

      python -c 'import site; print(site.getsitepackages())'
      

      Note: With virtualenvs getsitepackages is not available, sys.path from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead:

      python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
      
    2. The per user site-packages directory (PEP 370) is where Python installs your local packages:

      python -m site --user-site
      

      If this points to a non-existing directory check the exit status of Python and see python -m site --help for explanations.

      Hint: Running pip list --user or pip freeze --user gives you a list of all installed per user site-packages.


    Practical Tips

    • <package>.__path__ lets you identify the location(s) of a specific package: (details)

      $ python -c "import setuptools as _; print(_.__path__)"
      ['/usr/lib/python2.7/dist-packages/setuptools']
      
    • <module>.__file__ lets you identify the location of a specific module: (difference)

      $ python3 -c "import os as _; print(_.__file__)"
      /usr/lib/python3.6/os.py
      
    • Run pip show <package> to show Debian-style package information:

      $ pip show pytest
      Name: pytest
      Version: 3.8.2
      Summary: pytest: simple powerful testing with Python
      Home-page: https://docs.pytest.org/en/latest/
      Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
      Author-email: None
      License: MIT license
      Location: /home/peter/.local/lib/python3.4/site-packages
      Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
      

    How to get the filename without the extension in Java?

    You can use java split function to split the filename from the extension, if you are sure there is only one dot in the filename which for extension.

    File filename = new File('test.txt'); File.getName().split("[.]");

    so the split[0] will return "test" and split[1] will return "txt"

    Passing parameters to a Bash function

    A simple example that will clear both during executing script or inside script while calling a function.

    #!/bin/bash
    echo "parameterized function example"
    function print_param_value(){
        value1="${1}" # $1 represent first argument
        value2="${2}" # $2 represent second argument
        echo "param 1 is  ${value1}" # As string
        echo "param 2 is ${value2}"
        sum=$(($value1+$value2)) # Process them as number
        echo "The sum of two value is ${sum}"
    }
    print_param_value "6" "4" # Space-separated value
    # You can also pass parameters during executing the script
    print_param_value "$1" "$2" # Parameter $1 and $2 during execution
    
    # Suppose our script name is "param_example".
    # Call it like this:
    #
    # ./param_example 5 5
    #
    # Now the parameters will be $1=5 and $2=5
    

    Render partial from different folder (not shared)

    The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.

    I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried

    <%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

    or is that just a typo in your question?

    How do I get the current username in Windows PowerShell?

    Just building on the work of others here:

    [String] ${stUserDomain},[String]  ${stUserAccount} = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")
    

    Why doesn't height: 100% work to expand divs to the screen height?

    This may not be ideal but you can allways do it with javascript. Or in my case jQuery

    <script>
    var newheight = $('.innerdiv').css('height');
    $('.mainwrapper').css('height', newheight);
    </script>
    

    I can't delete a remote master branch on git

    As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.

    You need to go to the GitHub page for your forked repository, and click on the “Settings” button.

    Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.

    From there, select placeholder (where placeholder is the dummy name for your new default branch).

    Confirm that you want to change your default branch.

    Now you can do (from the command line):

    git push origin :master
    

    Or, since 2012, you can delete that same branch directly on GitHub:

    GitHub deletion

    That was announced in Sept. 2013, a year after I initially wrote that answer.

    For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.


    Note: for BitBucket, Tum reports in the comments:

    About the same for Bitbucket

    Repo -> Settings -> Repository details -> Main branch
    

    "make clean" results in "No rule to make target `clean'"

    You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

    However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

    Lost connection to MySQL server during query?

    This happend to me when my CONSTRAINT name have the same name with other CONSTRAINT name.

    Changing my CONSTRAINT name solved this.

    How to read a text file from server using JavaScript?

    I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.

    Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

    How to get the indexpath.row when an element is activated?

    // CustomCell.swift
    
    protocol CustomCellDelegate {
        func tapDeleteButton(at cell: CustomCell)
    }
    
    class CustomCell: UICollectionViewCell {
        
        var delegate: CustomCellDelegate?
        
        fileprivate let deleteButton: UIButton = {
            let button = UIButton(frame: .zero)
            button.setImage(UIImage(named: "delete"), for: .normal)
            button.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
            button.translatesAutoresizingMaskIntoConstraints = false
            return button
        }()
        
        @objc fileprivate func deleteButtonTapped(_sender: UIButton) {
            delegate?.tapDeleteButton(at: self)
        }
        
    }
    
    //  ViewController.swift
    
    extension ViewController: UICollectionViewDataSource {
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as? CustomCell else {
                fatalError("Unexpected cell instead of CustomCell")
            }
            cell.delegate = self
            return cell
        }
    
    }
    
    extension ViewController: CustomCellDelegate {
    
        func tapDeleteButton(at cell: CustomCell) {
            // Here we get the indexPath of the cell what we tapped on.
            let indexPath = collectionView.indexPath(for: cell)
        }
    
    }
    

    PostgreSQL Error: Relation already exists

    There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
    Either use double quotes to preserve the upper case spelling of "A":

    CREATE TABLE "A" ...
    

    Or don't use quotes at all:

    CREATE TABLE A ...
    

    which is identical to

    CREATE TABLE a ...
    

    because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


    You could avoid problems with the index name completely by using simpler syntax:

    CREATE TABLE csd_relationship (
        csd_relationship_id serial PRIMARY KEY,
        type_id integer NOT NULL,
        object_id integer NOT NULL
    );
    

    Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

    How to upgrade rubygems

    To update just one gem (and it's dependencies), do:

        bundle update gem-name
    

    But to update just the gem alone (without updating it's dependencies), do

        bundle update --source gem-name
    

    Typescript interface default values

    You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with & and Required:

    interface DefaultedFuncConfig {
      b?: boolean;
    }
    
    interface MandatoryFuncConfig {
      a: boolean;
    }
    
    export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
     
    export const func = (config: FuncConfig): Required<FuncConfig> => ({
      b: true,
      ...config
    });
    
    // will compile
    func({ a: true });
    func({ a: true, b: true });
    
    // will error
    func({ b: true });
    func({});
    

    How to alias a table in Laravel Eloquent queries (or using Query Builder)?

    Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

    How do you get an iPhone's device name

    In Unity, using C#:

    SystemInfo.deviceName;
    

    SSRS expression to format two decimal places does not show zeros

    Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

    Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

    Create directory if it does not exist

    There are three ways I know to create a directory using PowerShell:

    Method 1: PS C:\> New-Item -ItemType Directory -path "C:\livingston"
    

    Enter image description here

    Method 2: PS C:\> [system.io.directory]::CreateDirectory("C:\livingston")
    

    Enter image description here

    Method 3: PS C:\> md "C:\livingston"
    

    Enter image description here

    Create dynamic variable name

    This is not possible, it will give you a compile time error,

    You can use array for this type of requirement .

    For your Reference :

    http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

    Export MySQL data to Excel in PHP

    Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)

    The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:

    $filename = "webreport.csv";
    header("Content-Type: application/xls");    
    header("Content-Disposition: attachment; filename=$filename");  
    header("Pragma: no-cache"); 
    header("Expires: 0");
    foreach($results as $x => $x_value){
        echo '"'.$x.'",' . '"'.$x_value.'"' . "\r\n";
    }
    
    1. Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
    2. Use the comma as delimiter.
    3. Double quote the Key and Value to escape any commas in the data.
    4. I also prepended column headers to $results so the spreadsheet looked even nicer.

    Submitting a form on 'Enter' with jQuery?

    I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.

    My test script:

            $('.module input').keydown(function (e) {
                var keyCode = e.which;
                console.log("keydown ("+keyCode+")")
                if (keyCode == 13) {
                    console.log("enter");
                    return false;
                }
            });
            $('.module input').keyup(function (e) {
                var keyCode = e.which;
                console.log("keyup ("+keyCode+")")
                if (keyCode == 13) {
                    console.log("enter");
                    return false;
                }
            });
            $('.module input').keypress(function (e) {
                var keyCode = e.which;
                console.log("keypress ("+keyCode+")");
                if (keyCode == 13) {
                    console.log("Enter");
                    return false;
                }
            });
    

    The output in the console when typing "A Enter B" on the keyboard:

    keydown (65)
    keypress (97)
    keyup (65)
    
    keydown (13)
    enter
    keyup (13)
    enter
    
    keydown (66)
    keypress (98)
    keyup (66)
    

    You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released. As per jQuery documentation on the function keypress():

    Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
    

    Tested on IE11 and FF61 on Server 2012 R2

    When do I need a fb:app_id or fb:admins?

    Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

    The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

    You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

    fb:admins is specified like this:
    <meta property="fb:admins" content="USER_ID"/>
    OR
    <meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

    and fb:app_id like this:
    <meta property="fb:app_id" content="APPID"/>

    Delete last commit in bitbucket

    In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

    Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

    On git:

    git revert <commit>
    

    On mercurial:

    hg backout <REV>
    

    EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.

    Android: How can I validate EditText input?

    I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:

        compile 'com.github.TeleClinic:SmartEditText:0.1.0'
    

    then you can use it like this:

    <com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
        android:id="@+id/passwordSmartEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:setLabel="Password"
        app:setMandatoryErrorMsg="Mandatory field"
        app:setPasswordField="true"
        app:setRegexErrorMsg="Weak password"
        app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />
    
    <com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
        android:id="@+id/ageSmartEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:setLabel="Age"
        app:setMandatoryErrorMsg="Mandatory field"
        app:setRegexErrorMsg="Is that really your age :D?"
        app:setRegexString=".*\\d.*" />
    

    Then you can check if it is valid like this:

        ageSmartEditText.check()
    

    For more examples and customization check the repository https://github.com/TeleClinic/SmartEditText

    How to hash a string into 8 digits?

    I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.

    var crypto = require('crypto');
    var s = 'she sells sea shells by the sea shore';
    console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));
    

    jQuery counting elements by class - what is the best way to implement this?

    try

    document.getElementsByClassName('myclass').length
    

    _x000D_
    _x000D_
    let num = document.getElementsByClassName('myclass').length;_x000D_
    console.log('Total "myclass" elements: '+num);
    _x000D_
    .myclass { color: red }
    _x000D_
    <span class="myclass" >1</span>_x000D_
    <span>2</span>_x000D_
    <span class="myclass">3</span>_x000D_
    <span class="myclass">4</span>
    _x000D_
    _x000D_
    _x000D_

    Compare objects in Angular

    Assuming that the order is the same in both objects, just stringify them both and compare!

    JSON.stringify(obj1) == JSON.stringify(obj2);
    

    Change background of LinearLayout in Android

     android:background="@drawable/ic_launcher"
    

    should be included inside Layout tab. where ic_launcher is image name that u can put inside project folder/res/drawable . you can copy any number of images and make it as background

    What does auto do in margin:0 auto?

    auto: The browser sets the margin. The result of this is dependant of the browser

    margin:0 auto specifies

    * top and bottom margins are 0
    * right and left margins are auto
    

    Why is quicksort better than mergesort?

    Quick sort is worst case O(n^2), however, the average case consistently out performs merge sort. Each algorithm is O(nlogn), but you need to remember that when talking about Big O we leave off the lower complexity factors. Quick sort has significant improvements over merge sort when it comes to constant factors.

    Merge sort also requires O(2n) memory, while quick sort can be done in place (requiring only O(n)). This is another reason that quick sort is generally preferred over merge sort.

    Extra info:

    The worst case of quick sort occurs when the pivot is poorly chosen. Consider the following example:

    [5, 4, 3, 2, 1]

    If the pivot is chosen as the smallest or largest number in the group then quick sort will run in O(n^2). The probability of choosing the element that is in the largest or smallest 25% of the list is 0.5. That gives the algorithm a 0.5 chance of being a good pivot. If we employ a typical pivot choosing algorithm (say choosing a random element), we have 0.5 chance of choosing a good pivot for every choice of a pivot. For collections of a large size the probability of always choosing a poor pivot is 0.5 * n. Based on this probability quick sort is efficient for the average (and typical) case.

    How to find Current open Cursors in Oracle

    Oracle has a page for this issue with SQL and trouble shooting suggestions.

    "Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352

    Using Mockito, how do I verify a method was a called with a certain argument?

    Building off of Mamboking's answer:

    ContractsDao mock_contractsDao = mock(ContractsDao.class);
    when(mock_contractsDao.save(anyString())).thenReturn("Some result");
    
    m_orderSvc.m_contractsDao = mock_contractsDao;
    m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
    m_prog.work(); 
    

    Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

    ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
    verify(mock_contractsDao).save(savedCaptor.capture());
    assertTrue(savedCaptor.getValue().contains("substring I want to find");
    

    If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

    ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
    verify(mock_contractsDao).save(savedCaptor.capture());
    assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);
    

    You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

    Dynamically set value of a file input

    I ended up doing something like this for AngularJS in case someone stumbles across this question:

    const imageElem = angular.element('#awardImg');
    
    if (imageElem[0].files[0])
        vm.award.imageElem = imageElem;
        vm.award.image = imageElem[0].files[0];
    

    And then:

    if (vm.award.imageElem)
        $('#awardImg').replaceWith(vm.award.imageElem);
        delete vm.award.imageElem;
    

    What is this: [Ljava.lang.Object;?

    [Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

    The naming scheme is documented in Class.getName():

    If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

    If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

    If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

    Element Type        Encoding
    boolean             Z
    byte                B
    char                C
    double              D
    float               F
    int                 I
    long                J
    short               S 
    class or interface  Lclassname;
    

    Yours is the last on that list. Here are some examples:

    // xxxxx varies
    System.out.println(new int[0][0][7]); // [[[I@xxxxx
    System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
    System.out.println(new boolean[256]); // [Z@xxxxx
    

    The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

    getClass().getName() + '@' + Integer.toHexString(hashCode())
    

    Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


    On a more "useful" toString for arrays

    java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

    Here are some examples:

    int[] nums = { 1, 2, 3 };
    
    System.out.println(nums);
    // [I@xxxxx
    
    System.out.println(Arrays.toString(nums));
    // [1, 2, 3]
    
    int[][] table = {
            { 1, },
            { 2, 3, },
            { 4, 5, 6, },
    };
    
    System.out.println(Arrays.toString(table));
    // [[I@xxxxx, [I@yyyyy, [I@zzzzz]
    
    System.out.println(Arrays.deepToString(table));
    // [[1], [2, 3], [4, 5, 6]]
    

    There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

    Related questions

    How to get evaluated attributes inside a custom directive

    For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

    <input my-directive value="{{1+1}}">
    

    use Attributes' method $observe:

    myApp.directive('myDirective', function () {
      return function (scope, element, attr) {
        attr.$observe('value', function(actual_value) {
          element.val("value = "+ actual_value);
        })
     }
    });
    

    From the directive page,

    observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

    If the attribute value is just a constant, e.g.,

    <input my-directive value="123">
    

    you can use $eval if the value is a number or boolean, and you want the correct type:

    return function (scope, element, attr) {
       var number = scope.$eval(attr.value);
       console.log(number, number + 1);
    });
    

    If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

    return function (scope, element, attr) {
       var str = attr.value;
       console.log(str, str + " more");
    });
    

    In your case, however, since you want to support interpolated values and constants, use $observe.

    "ImportError: no module named 'requests'" after installing with pip

    One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.

    Type python in the prompt, and press the tab key to see what versions of Python in your environment.

    JQuery: if div is visible

    You can use .is(':visible')

    Selects all elements that are visible.

    For example:

    if($('#selectDiv').is(':visible')){
    

    Also, you can get the div which is visible by:

    $('div:visible').callYourFunction();
    

    Live example:

    _x000D_
    _x000D_
    console.log($('#selectDiv').is(':visible'));_x000D_
    console.log($('#visibleDiv').is(':visible'));
    _x000D_
    #selectDiv {_x000D_
      display: none;  _x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <div id="selectDiv"></div>_x000D_
    <div id="visibleDiv"></div>
    _x000D_
    _x000D_
    _x000D_

    Execute a SQL Stored Procedure and process the results

    At the top of your .vb file:

    Imports System.data.sqlclient
    

    Within your code:

    'Setup SQL Command
    Dim CMD as new sqlCommand("StoredProcedureName")
    CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value
    
    Dim connection As New SqlConnection(connectionString)
    CMD.Connection = connection
    CMD.CommandType = CommandType.StoredProcedure
    
    Dim adapter As New SqlDataAdapter(CMD)
    adapter.SelectCommand.CommandTimeout = 300
    
    'Fill the dataset
    Dim DS as DataSet    
    adapter.Fill(ds)
    connection.Close()   
    
    'Now, read through your data:
    For Each DR as DataRow in DS.Tables(0).rows
        Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
    next
    

    Now that the basics are out of the way,

    I highly recommend abstracting the actual SqlCommand Execution out into a function.

    Here is a generic function that I use, in some form, on various projects:

    ''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
    ''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),''' 
    ''' otherwise if there is just one token, it's a stored procedure command</param>''''
    Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
        Dim ds As New DataSet()
    
        Try
            Dim connection As New SqlConnection(connectionString)
            CMD.Connection = connection
    
            'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
            If CMD.CommandText.Contains(" ") Then
                CMD.CommandType = CommandType.Text
            Else
                CMD.CommandType = CommandType.StoredProcedure
            End If
    
            Dim adapter As New SqlDataAdapter(CMD)
            adapter.SelectCommand.CommandTimeout = 300
    
            'fill the dataset
            adapter.Fill(ds)
            connection.Close()
    
        Catch ex As Exception
            ' The connection failed. Display an error message.
            Throw New Exception("Database Error: " & ex.Message)
        End Try
    
        Return ds
    End Function
    

    Once you have that, your SQL Execution + reading code is very simple:

    '----------------------------------------------------------------------'
    Dim CMD As New SqlCommand("GetProductName")
    CMD.Parameters.Add("@productID", SqlDbType.Int).Value = ProductID
    Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
    MsgBox("Product Name: " & cstr(DR(0)))
    '----------------------------------------------------------------------'
    

    Show current assembly instruction in GDB

    From within gdb press Ctrl x 2 and the screen will split into 3 parts.

    First part will show you the normal code in high level language.

    Second will show you the assembly equivalent and corresponding instruction Pointer.

    Third will present you the normal gdb prompt to enter commands.

    See the screen shot

    Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

    If you added (or have) a CSS class or id to the parent element, then you can do something like this:

    <div id="parent">
      <div>
      </div>
    </div>
    
    JavaScript:
    document.getElementById("parent").onmouseout = function(e) {
      e = e ? e : window.event //For IE
      if(e.target.id == "parent") {
        //Do your stuff
      }
    }
    

    So stuff only gets executed when the event is on the parent div.

    How do I get the current username in .NET using C#?

    For a Windows Forms app that was to be distributed to several users, many of which log in over vpn, I had tried several ways which all worked for my local machine testing but not for others. I came across a Microsoft article that I adapted and works.

    using System;
    using System.Security.Principal;
    
    namespace ManageExclusion
    {
        public static class UserIdentity
    
        {
            // concept borrowed from 
            // https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx
    
            public static string GetUser()
            {
                IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
                WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
                return windowsIdentity.Name;
            }
        }
    }
    

    When does a process get SIGABRT (signal 6)?

    abort() sends the calling process the SIGABRT signal, this is how abort() basically works.

    abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.

    Python: Differentiating between row and column vectors

    Here's another intuitive way. Suppose we have:

    >>> a = np.array([1, 3, 4])
    >>> a
    array([1, 3, 4])
    

    First we make a 2D array with that as the only row:

    >>> a = np.array([a])
    >>> a
    array([[1, 3, 4]])
    

    Then we can transpose it:

    >>> a.T
    array([[1],
           [3],
           [4]])
    

    Replace text in HTML page with jQuery

    Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.

    In this sample usage, I replace all text inside a <div id="content"> that looks like a US telephone number with a tel: scheme link:

    findAndReplaceDOMText(document.getElementById('content'), {
        find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
        replace:function (portion) {
            var a = document.createElement('a');
            a.className = 'telephone';
            a.href = 'tel:' + portion.text.replace(/\D/g, '');
            a.textContent = portion.text;
            return a;
        }
    });
    

    How to break out of jQuery each Loop

    To break a $.each or $(selector).each loop, you have to return false in the loop callback.

    Returning true skips to the next iteration, equivalent to a continue in a normal loop.

    $.each(array, function(key, value) { 
        if(value === "foo") {
            return false; // breaks
        }
    });
    
    // or
    
    $(selector).each(function() {
      if (condition) {
        return false;
      }
    });
    

    Parsing query strings on Android

    On Android its simple as the code below:

    UrlQuerySanitizer sanitzer = new UrlQuerySanitizer(url);
    String value = sanitzer.getValue("your_get_parameter");
    

    Also if you don't want to register each expected query key use:

    sanitzer.setAllowUnregisteredParamaters(true)
    

    Before calling:

    sanitzer.parseUrl(yourUrl)
    

    Java 8 Lambda Stream forEach with multiple statements

    In the first case alternatively to multiline forEach you can use the peek stream operation:

    entryList.stream()
             .peek(entry -> entry.setTempId(tempId))
             .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));
    

    In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

    Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

    Polygon Drawing and Getting Coordinates with Google Map API v3

    try this

    In your controller use

    > $scope.onMapOverlayCompleted = onMapOverlayCompleted;
    > 
    >  function onMapOverlayCompleted(e) {
    > 
    >                 e.overlay.getPath().getArray().forEach(function (position) {
    >                     console.log('lat', position.lat());
    >                     console.log('lng', position.lng());
    >                 });
    > 
    >  }
    
    **In Your html page , include drawning manaer** 
    
    
        <ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
                            tilt="45"
                            heading="90">
    
                        <drawing-manager
                                on-overlaycomplete="onMapOverlayCompleted()"
                                drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
                                drawingControl="true"
                                drawingMode="null"
                                markerOptions="{icon:'www.example.com/icon'}"
                                rectangleOptions="{fillColor:'#B43115'}"
                                circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
                        </drawing-manager>
        </ng-map>
    

    What is the meaning of # in URL and how can I use that?

    Originally it was used as an anchor to jump to an element with the same name/id.

    However, nowadays it's usually used with AJAX-based pages since changing the hash can be detected using JavaScript and allows you to use the back/forward button without actually triggering a full page reload.

    Iterating Over Dictionary Key Values Corresponding to List in Python

    You can very easily iterate over dictionaries, too:

    for team, scores in NL_East.iteritems():
        runs_scored = float(scores[0])
        runs_allowed = float(scores[1])
        win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
        print '%s: %.1f%%' % (team, win_percentage)
    

    Creating a PDF from a RDLC Report in the Background

    This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.

    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string filenameExtension;
    
    byte[] bytes = reportViewer.LocalReport.Render(
        "PDF", null, out mimeType, out encoding, out filenameExtension,
        out streamids, out warnings);
    
    using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
    {
        fs.Write(bytes, 0, bytes.Length);
    }
    

    How to read large text file on windows?

    if you can code, write a console app. here is the c# equivalent of what you're after. you can do what you want with the results (split, execute etc):

    SqlCommand command = null;
    try
    {
        using (var connection = new SqlConnection("XXXX"))
        {
            command = new SqlCommand();
            command.Connection = connection;
            if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("C:\\test.txt"))
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                    command.CommandText = line;
                    command.ExecuteNonQuery();
                    Console.Write(" - DONE");
                }
            }
        }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
    finally
    {
        if (command.Connection.State == ConnectionState.Open) command.Connection.Close();
    }
    

    SQL Server Output Clause into a scalar variable

    Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

    DECLARE @val1 int;
    DECLARE @val2 int;
    UPDATE [dbo].[PortalCounters_TEST]
    SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
    WHERE [Condition] = 'unique value'
    SELECT @val1, @val2
    

    In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

    One place this is very helpful is if you want to turn a column into a comma-separated list;

    DECLARE @list varchar(max) = '';
    DECLARE @comma varchar(2) = '';
    SELECT @list = @list + @comma + County, @comma = ', ' FROM County
    print @list
    

    Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

    I got this error when I used ViewTreeObserver inside onDraw() function.

    @Override
    protected void onDraw(Canvas canvas) {
        // super.onDraw(canvas);
        ViewTreeObserver vto = mTextView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // some animation        
            }
        });
     }
    

    Writing Unicode text to a text file?

    In Python 2.6+, you could use io.open() that is default (builtin open()) on Python 3:

    import io
    
    with io.open(filename, 'w', encoding=character_encoding) as file:
        file.write(unicode_text)
    

    It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding) multiple times). Unlike codecs module, io module has a proper universal newlines support.

    Selecting multiple columns in a Pandas dataframe

    The different approaches discussed in the previous answers are based on the assumption that either the user knows column indices to drop or subset on, or the user wishes to subset a dataframe using a range of columns (for instance between 'C' : 'E').

    pandas.DataFrame.drop() is certainly an option to subset data based on a list of columns defined by user (though you have to be cautious that you always use copy of dataframe and inplace parameters should not be set to True!!)

    Another option is to use pandas.columns.difference(), which does a set difference on column names, and returns an index type of array containing desired columns. Following is the solution:

    df = pd.DataFrame([[2,3,4], [3,4,5]], columns=['a','b','c'], index=[1,2])
    columns_for_differencing = ['a']
    df1 = df.copy()[df.columns.difference(columns_for_differencing)]
    print(df1)
    

    The output would be:

        b   c
    1   3   4
    2   4   5
    

    Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

    If you look at the chain of exceptions, the problem is

    Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account

    The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.

    To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).

    Get current index from foreach loop

    You can't, because IEnumerable doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue elements (or long.MaxValue if you use a long index), you can:

    1. Don't use foreach, and use a for loop, converting your IEnumerable to a generic enumerable first:

      var genericList = list.Cast<object>();
      for(int i = 0; i < genericList.Count(); ++i)
      {
         var row = genericList.ElementAt(i);
         /* .... */
      }
      
    2. Have an external index:

      int i = 0;
      foreach(var row in list)
      {
         /* .... */
         ++i;
      }
      
    3. Get the index via Linq:

      foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
      {
        var row = rowObject.Row;
        var i = rowObject.Index;
        /* .... */    
      }
      

    In your case, since your IEnumerable is not a generic one, I'd rather use the foreach with external index (second method)... otherwise, you may want to make the Cast<object> outside your loop to convert it to an IEnumerable<object>.

    Your datatype is not clear from the question, but I'm assuming object since it's an items source (it could be DataGridRow)... you may want to check if it's directly convertible to a generic IEnumerable<object> without having to call Cast<object>(), but I'll make no such assumptions.


    All this said:

    The concept of an "index" is foreign to an IEnumerable. An IEnumerable can be potentially infinite. In your example, you are using the ItemsSource of a DataGrid, so more likely your IEnumerable is just a list of objects (or DataRows), with a finite (and hopefully less than int.MaxValue) number of members, but IEnumerable can represent anything that can be enumerated (and an enumeration can potentially never end).

    Take this example:

    public static IEnumerable InfiniteEnumerable()
    {
      var rnd = new Random();
      while(true)
      {
        yield return rnd.Next();
      }
    }
    

    So if you do:

    foreach(var row in InfiniteEnumerable())
    {
      /* ... */
    }
    

    Your foreach will be infinite: if you used an int (or long) index, you'll eventually overflow it (and unless you use an unchecked context, it'll throw an exception if you keep adding to it: even if you used unchecked, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).

    So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.

    Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

    Try:

    SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
           convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
    FROM
    (......)SA
    WHERE......
    

    Or:

    SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
           format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
    FROM
    (......)SA
    WHERE......
    

    Java: Detect duplicates in ArrayList?

    If you want the set of duplicate values:

    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    public class FindDuplicateInArrayList {
    
        public static void main(String[] args) {
    
            Set<String> uniqueSet = new HashSet<String>();
            List<String> dupesList = new ArrayList<String>();
            for (String a : args) {
                if (uniqueSet.contains(a))
                    dupesList.add(a);
                else
                    uniqueSet.add(a);
            }
            System.out.println(uniqueSet.size() + " distinct words: " + uniqueSet);
            System.out.println(dupesList.size() + " dupesList words: " + dupesList);
        }
    }
    

    And probably also think about trimming values or using lowercase ... depending on your case.

    jQuery: select all elements of a given class, except for a particular Id

    I'll just throw in a JS (ES6) answer, in case someone is looking for it:

    Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
        doSomething(el);
    }
    

    Update (this may have been possible when I posted the original answer, but adding this now anyway):

    document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
        doSomething(el);
    });
    

    This gets rid of the Array.from usage.

    document.querySelectorAll returns a NodeList.
    Read here to know more about how to iterate on it (and other things): https://developer.mozilla.org/en-US/docs/Web/API/NodeList

    Converting an int to a binary string representation in Java?

    public class BinaryConverter {
    
        public static String binaryConverter(int number) {
            String binary = "";
            if (number == 1){
                binary = "1";
                System.out.print(binary);
                return binary;
            }
            if (number == 0){
                binary = "0";
                System.out.print(binary);
                return binary;
            }
            if (number > 1) {
                String i = Integer.toString(number % 2);
    
                binary = binary + i;
                binaryConverter(number/2);
            }
            System.out.print(binary);
            return binary;
        }
    }
    

    MVC 5 Access Claims Identity User Data

    This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.

    public class AppUser : ClaimsPrincipal
    {
        public AppUser(ClaimsPrincipal principal)
            : base(principal)
        {
        }
    
        public string Name
        {
            get
            {
                return this.FindFirst(ClaimTypes.Name).Value;
            } 
        }
    
    }
    

    Then you can add a base controller.

    public abstract class AppController : Controller
    {       
        public AppUser CurrentUser
        {
            get
            {
                return new AppUser(this.User as ClaimsPrincipal);
            }
        }
    }
    

    In you controller, you would do:

    public class HomeController : AppController
    {
        public ActionResult Index()
        {
            ViewBag.Name = CurrentUser.Name;
            return View();
        }
    }
    

    What is the "right" JSON date format?

    Just for reference I've seen this format used:

    Date.UTC(2017,2,22)
    

    It works with JSONP which is supported by the $.getJSON() function. Not sure I would go so far as to recommend this approach... just throwing it out there as a possibility because people are doing it this way.

    FWIW: Never use seconds since epoch in a communication protocol, nor milliseconds since epoch, because these are fraught with danger thanks to the randomized implementation of leap seconds (you have no idea whether sender and receiver both properly implement UTC leap seconds).

    Kind of a pet hate, but many people believe that UTC is just the new name for GMT -- wrong! If your system does not implement leap seconds then you are using GMT (often called UTC despite being incorrect). If you do fully implement leap seconds you really are using UTC. Future leap seconds cannot be known; they get published by the IERS as necessary and require constant updates. If you are running a system that attempts to implement leap seconds but contains and out-of-date reference table (more common than you might think) then you have neither GMT, nor UTC, you have a wonky system pretending to be UTC.

    These date counters are only compatible when expressed in a broken down format (y, m, d, etc). They are NEVER compatible in an epoch format. Keep that in mind.

    Spring Boot Multiple Datasource

    I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem

    http://www.baeldung.com/spring-data-jpa-multiple-databases

    Arguments to main in C

    The signature of main is:

    int main(int argc, char **argv);
    

    argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

    So, if you ran your program like this:

    ./program hello world
    

    Then:

    • argc would be 3.
    • argv[0] would be "./program".
    • argv[1] would be "hello".
    • argv[2] would be "world".

    How do I output an ISO 8601 formatted string in JavaScript?

    See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:

    /* Use a function for the exact format desired... */
    function ISODateString(d) {
        function pad(n) {return n<10 ? '0'+n : n}
        return d.getUTCFullYear()+'-'
             + pad(d.getUTCMonth()+1)+'-'
             + pad(d.getUTCDate())+'T'
             + pad(d.getUTCHours())+':'
             + pad(d.getUTCMinutes())+':'
             + pad(d.getUTCSeconds())+'Z'
    }
    
    var d = new Date();
    console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
    

    Create parameterized VIEW in SQL Server 2008

    in fact there exists one trick:

    create view view_test as
    
    select
      * 
    from 
      table 
    where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
    where
    spid = @@spid)
    

    ... in sql-query:

    set context_info 2
    select * from view_test
    

    will be the same with

    select * from table where id = 2
    

    but using udf is more acceptable

    Request format is unrecognized for URL unexpectedly ending in

    Superb.

    Case 2 - where the same issue can arrise) in my case the problem was due to the following line:

    <webServices>
      <protocols>
        <remove name="Documentation"/>
      </protocols>
    </webServices>
    

    It works well in server as calls are made directly to the webservice function - however will fail if you run the service directly from .Net in the debug environment and want to test running the function manually.

    calling java methods in javascript code

    Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

    How to expand a list to function arguments in Python

    You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

    Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

    def foo(x,y,z):
       return "%d, %d, %d" % (x,y,z)
    
    values = [1,2,3]
    
    # the solution.
    foo(*values)
    

    How to return data from PHP to a jQuery ajax call

    based on accepted answer

    $output = some_function();
      echo $output;
    

    if it results array then use json_encode it will result json array which is supportable by javascript

    $output = some_function();
      echo json_encode($output);
    

    If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword

    $output = some_function();
      echo $output;
    exit;
    

    Binding an enum to a WinForms combo box, and then setting it

    Convert the enum to a list of string and add this to the comboBox

    comboBox1.DataSource = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
    

    Set the displayed value using selectedItem

    comboBox1.SelectedItem = SomeEnum.SomeValue;
    

    How do I rotate the Android emulator display?

    On Mac OS X, you can use Ctrl + Fn + F12 to rotate the Android emulator if you have have not configured your keyboard to "Use all F1, F2, etc. keys as standard function keys" (Check it on System Preferences - Keyboard).

    If you have checked the option mentioned above, you will not need the Fn key and you should be able to rotate the emulator only with Ctrl + F12.

    VB.NET Connection string (Web.Config, App.Config)

    I don't know if this still is an issue, but i prefere just to use the My.Settings in my code.

    Visual Studio generates a simple class with functions for reading settings from the app.config file.

    You can simply access it using My.Settings.ConnectionString.

        Using Context As New Data.Context.DataClasses()
            Context.Connection.ConnectionString = My.Settings.ConnectionString
        End Using
    

    Difference between [routerLink] and routerLink

    ROUTER LINK DIRECTIVE:

    [routerLink]="link"                  //when u pass URL value from COMPONENT file
    [routerLink]="['link','parameter']" //when you want to pass some parameters along with route
    
     routerLink="link"                  //when you directly pass some URL 
    [routerLink]="['link']"              //when you directly pass some URL
    

    How to change max_allowed_packet size

    in MYSQL 5.7, max_allowed_packet is at most 1G. if you want to set it to 4G, it would failed without error and warning.

    Android Studio-No Module

    I had a similar issue of my app module disappearing, this was after a large merge (from hell). I found app.iml was missing <component name="FacetManager"> when compared with other projects and before the merge. So I copy and pasted the below under the root <module > element.

    Manually editing the .iml files maybe ill advised so proceed at your own risk.

    File: project root folder > app > app.iml

    Add the following...

      <component name="FacetManager">
        <facet type="android-gradle" name="Android-Gradle">
          <configuration>
            <option name="GRADLE_PROJECT_PATH" value=":app" />
          </configuration>
        </facet>
        <facet type="android" name="Android">
          <configuration>
            <option name="SELECTED_BUILD_VARIANT" value="debug" />
            <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
            <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
            <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
            <afterSyncTasks>
              <task>generateDebugSources</task>
            </afterSyncTasks>
            <option name="ALLOW_USER_CONFIGURATION" value="false" />
            <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
            <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
            <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res;file://$MODULE_DIR$/src/debug/res" />
            <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
          </configuration>
        </facet>
      </component>
    

    Is it necessary to assign a string to a variable before comparing it to another?

    Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

    NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];
    

    Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

    Next time you want a string variable you can use the "@" symbol in a much more convenient way:

    NSString *myString = @"SomeText";
    

    This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

    Hope that helps!

    Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

    What i did was i commented out the

    props.put("mail.smtp.starttls.enable","true"); 
    

    Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.

    HTML.HiddenFor value set

    You shouldn't need to set the value in the attributes parameter. MVC should automatically bind it for you.

    @Html.HiddenFor(model => model.title, new { id= "natureOfVisitField" })
    

    How to step through Python code to help debug issues?

    By using Python Interactive Debugger 'pdb'

    First step is to make the Python interpreter to enter into the debugging mode.

    A. From the Command Line

    Most straight forward way, running from command line, of python interpreter

    $ python -m pdb scriptName.py
    > .../pdb_script.py(7)<module>()
    -> """
    (Pdb)
    

    B. Within the Interpreter

    While developing early versions of modules and to experiment it more iteratively.

    $ python
    Python 2.7 (r27:82508, Jul  3 2010, 21:12:11)
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import pdb_script
    >>> import pdb
    >>> pdb.run('pdb_script.MyObj(5).go()')
    > <string>(1)<module>()
    (Pdb)
    

    C. From Within Your Program

    For a big project and long-running module, can start the debugging from inside the program using import pdb and set_trace() like this :

    #!/usr/bin/env python
    # encoding: utf-8
    #
    
    import pdb
    
    class MyObj(object):
        count = 5
        def __init__(self):
            self.count= 9
    
        def go(self):
            for i in range(self.count):
                pdb.set_trace()
                print i
            return
    
    if __name__ == '__main__':
        MyObj(5).go()
    

    Step-by-Step debugging to go into more internal

    1. Execute the next statement… with “n” (next)

    2. Repeating the last debugging command… with ENTER

    3. Quitting it all… with “q” (quit)

    4. Printing the value of variables… with “p” (print)

      a) p a

    5. Turning off the (Pdb) prompt… with “c” (continue)

    6. Seeing where you are… with “l” (list)

    7. Stepping into subroutines… with “s” (step into)

    8. Continuing… but just to the end of the current subroutine… with “r” (return)

    9. Assign a new value

      a) !b = "B"

    10. Set a breakpoint

      a) break linenumber

      b) break functionname

      c) break filename:linenumber

    11. Temporary breakpoint

      a) tbreak linenumber

    12. Conditional breakpoint

      a) break linenumber, condition

    Note:**All these commands should be execute from **pdb

    For in-depth knowledge, refer:-

    https://pymotw.com/2/pdb/

    https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

    Java/ JUnit - AssertTrue vs AssertFalse

    I think it's just for your convenience (and the readers of your code)

    Your code, and your unit tests should be ideally self documenting which this API helps with,

    Think abt what is more clear to read:

    AssertTrue(!(a > 3));
    

    or

    AssertFalse(a > 3);
    

    When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

    CSS Selector "(A or B) and C"?

    Not yet, but there is the experimental :matches() pseudo-class function that does just that:

    :matches(.a .b) .c {
      /* stuff goes here */
    }
    

    You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :matches(). We just have to wait a little more before using this everywhere (I surely will).

    BATCH file asks for file or folder

    The virtual parent trick

    Assuming you have your source and destination file in

    %SRC_FILENAME% and %DST_FILENAME%
    

    you could use a 2 step method:

    @REM on my win 7 system mkdir creates all parent directories also
    mkdir "%DST_FILENAME%\.."
    xcopy "%SRC_FILENAME% "%DST_FILENAME%\.."
    

    this would be resolved to e.g

    mkdir "c:\destination\b\c\file.txt\.."
    @REM The special trick here is that mkdir can create the parent
    @REM directory of a "virtual" directory (c:\destination\b\c\file.txt\) that 
    @REM doesn't even need to exist.
    @REM So the directory "c:\destination\b\c" is created here.
    @REM mkdir "c:\destination\b\c\dummystring\.." would have the same effect
    
    xcopy "c:\source\b\c\file.txt" "c:\destination\b\c\file.txt\.."
    @REM xcopy computes the real location of  "c:\destination\b\c\file.txt\.."
    @REM which is the now existing directory "c:\destination\b\c"
    @REM (the parent directory of the "virtual" directory c:\destination\b\c\file.txt\).
    

    I came to the idea when I stumbled over some really wild ../..-constructs in the command lines generated from a build process.

    How do I put my website's logo to be the icon image in browser tabs?

    Add a icon file named "favicon.ico" to the root of your website.

    How do I return to an older version of our code in Subversion?

    The standard way of using merge to undo the entire check-in works great, if that's what you want to do. Sometimes, though, all you want to do is revert a single file. There's no legitimate way to do that, but there is a hack:

    1. Find the version that you want using svn log.
    2. Use svn's export subcommand:

      svn export http://url-to-your-file@123 /tmp/filename

    (Where 123 is the revision number for a good version of the file.) Then either move or copy that single file to overwrite the old one. Check in the modified file and you are done.

    window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

    I got the solution for onunload in all browsers except Opera by changing the Ajax asynchronous request into synchronous request.

    xmlhttp.open("POST","LogoutAction",false);
    

    It works well for all browsers except Opera.

    Rounding a double value to x number of decimal places in swift

    In Swift 5.3 and Xcode 12:

    let pi: Double = 3.14159265358979
    String(format:"%.2f", pi)
    

    Example:

    enter image description here

    PS.: It still the same since Swift 2.0 and Xcode 7.2

    MongoError: connect ECONNREFUSED 127.0.0.1:27017

    If you are a windows user, right click on Start and open Windows Powershell(Run as administartor). Then type

    mongod
    

    That's it. Your database will surely get connected!

    How to restore PostgreSQL dump file into Postgres databases?

    By using pg_restore command you can restore postgres database

    First open terminal type

    sudo su postgres
    

    Create new database

    createdb [database name] -O [owner]

    createdb test_db [-O openerp]
    

    pg_restore -d [Database Name] [path of dump file]

    pg_restore -d test_db /home/sagar/Download/sample_dbump
    

    Wait for completion of database restoring.

    Remember that dump file should have read, write, execute access, so for that you can apply chmod command