Programs & Examples On #Xop

XML-binary Optimized Packaging - convention for serialization of XML Infosets.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case : When I setup AS, my windows was configured with proxy. Later, I disconnect proxy and disable proxy in AS settings, But, in file .gradle\gradle.properties - proxy - present

Just, in text editor clear proxy settings from this file

error: resource android:attr/fontVariationSettings not found

For those that must keep compileSdkVersion 27 and are unable to upgrade to androidx yet, you must not upgrade to (or over) the versions of dependencies in the following links. These links are where the breaking change was introduced. You must find an earlier version that doesn't use androidx.

https://firebase.google.com/support/release-notes/android#update_-_june_17_2019

https://developers.google.com/android/guides/releases#june_17_2019

For instance, the following are compatible with compileSdkVersion 27:

dependencies {
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.firebase:firebase-core:16.0.9'
    implementation 'com.google.firebase:firebase-messaging:18.0.0'
}

The following will break with compileSdkVersion 27 and are only compatible with compileSdkVersion 28:

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.google.firebase:firebase-core:17.0.0'
    implementation 'com.google.firebase:firebase-messaging:19.0.0'
}

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I tried everything from unchecking offline work to matchingFallbacks. But nothing worked.

Then, in dependencies of app.gradle,

instead of

implementation project(':lib-name')

I used,

implementation project(path:':lib-name', configuration: 'default')

Eg: implementation project(path:':myService', configuration: 'default')

And it worked like a charm. :)

I was adding a dependency module with service and am not making a library as its a part of AOSP project.

Just in case, it helps someone.

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

Below changes worked for me

I change distribution URL, located in gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip

And

dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }

kotlin version 1.2.71

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Just a simple solution is here...it worked for me:

  1. Clean Project
  2. Rebuild project
  3. Sync project with gradle file

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Add multiDexEnabled true in your defaultConfig in the app level gradle.

defaultConfig {
    applicationId "your application id"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}

Forward X11 failed: Network error: Connection refused

The D-Bus error can be fixed with dbus-launch :

dbus-launch command

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

I found success using this configuration:

classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.google.gms:google-services:2.0.0-alpha3'
//or use
//classpath 'com.android.tools.build:gradle:2.0.0-alpha6'

and

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

using 8.40 Google Play services. Alpha5 & Alpha6 gave the same 2.8 error you had, regardless of the distributionUrl being 2.10

Warning: Failed propType: Invalid prop `component` supplied to `Route`

Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.

module.exports = Component should become export default Component.

CommonJS uses module.exports as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports, exoprts or exprots). There are no runtime or compile-time checks to tell you that you've messed up.

If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component then it will give you a compile error to let you know.

In your case, you can simplify the Speaker component.

import React from 'react';

export default React.createClass({
  render() {
    return (
      <h1>Speaker</h1>
    )
  }
});

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

Convert Json String to C# Object List

The variables/parameters within the class definition requires { get; set; } I was using like a variable declaration (stupid of me, because it was working for other scenarios) without

{ get; set; }

Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.

Once the {get; set;} is added, it worked like charm.

I hope it helps someone who is coming from VB6 style of programming line.

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });

SQL Error: 0, SQLState: 08S01 Communications link failure

I'm answering on specific to this error code(08s01).

usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".

1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.

2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days

3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

Unable to execute dex: method ID not in [0, 0xffff]: 65536

The perfect solution for this would be to work with Proguard. as aleb mentioned in the comment. It will decrease the size of the dex file by half.

What does .shape[] do in "for i in range(Y.shape[0])"?

shape() consists of array having two arguments rows and columns.

if you search shape[0] then it will gave you the number of rows. shape[1] will gave you number of columns.

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

Need to perform Wildcard (*,?, etc) search on a string using Regex

All upper code is not correct to the end.

This is because when searching zz*foo* or zz* you will not get correct results.

And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.

Here is the correct code.

public string WildcardToRegex(string pattern)
{             
    string result= Regex.Escape(pattern).
        Replace(@"\*", ".+?").
        Replace(@"\?", "."); 

    if (result.EndsWith(".+?"))
    {
        result = result.Remove(result.Length - 3, 3);
        result += ".*";
    }

    return result;
}

How to check for a valid Base64 encoded string

I would suggest creating a regex to do the job. You'll have to check for something like this: [a-zA-Z0-9+/=] You'll also have to check the length of the string. I'm not sure on this one, but i'm pretty sure if something gets trimmed (other than the padding "=") it would blow up.

Or better yet check out this stackoverflow question

LIKE operator in LINQ

A simple as this

string[] users = new string[] {"Paul","Steve","Annick","Yannick"};    
var result = from u in users where u.Contains("nn") select u;

Result -> Annick,Yannick

How do I solve the INSTALL_FAILED_DEXOPT error?

I am working with Android Studio and had the same error.

Deleting the build folder of the main Modul helped. After deleting everything get back to normal.

How to create a property for a List<T>

Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.

public class MyClass<T>
{
  etc

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Using JavaScript will definitely do the job.

You can also use Content if this is more your style.

Example:

MVC Controller

[HttpPost]
public ActionResult AjaxMethod()
{
    return Content(@"http://www.google.co.uk");
}

Javascript

$.ajax({
    type: 'POST',
    url: '/AjaxMethod',
    success: function (redirect) {
        window.location = redirect;
    }
});

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Simply place normal button indide Ajax.BeginForm and on click find parent form and normal submit. Ajax form in Razor:

@using (Ajax.BeginForm("AjaxPost", "Home", ajaxOptions))
    {        
        <div class="form-group">
            <div class="col-md-12">

                <button class="btn btn-primary" role="button" type="button" onclick="submitParentForm($(this))">Submit parent from Jquery</button>
            </div>
        </div>
    }

and Javascript:

function submitParentForm(sender) {
    var $formToSubmit = $(sender).closest('form');

    $formToSubmit.submit();
}

How to check if X server is running?

First you need to ensure foundational X11 packages are correctly installed on your server:

rpm -qa | grep xorg-x11-xauth

If not then, kindly install all packages :

sudo yum install xorg-x11-xauth xterm

Ensure that openssh server is configured to forward x11 connections :

edit file : vim /etc/ssh/sshd_config

X11Forwarding yes

NOTE : If that line is preceded by a comment (#) or is set to no, update the file to match the above, and restart your ssh server daemon (be careful here — if you made an error you may lock yourself out of the server)

sudo /etc/init.d/sshd restart

Now, configure SSH application to forward X11 requests :

ssh -Y your_username@your_server.your_domain.com

jQuery Ajax error handling, show custom exception messages

You need to convert the responseText to JSON. Using JQuery:

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);

Is there an alternative to string.Replace that is case-insensitive?

Here's an extension method. Not sure where I found it.

public static class StringExtensions
{
    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
    {
        int startIndex = 0;
        while (true)
        {
            startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
            if (startIndex == -1)
                break;

            originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

            startIndex += newValue.Length;
        }

        return originalString;
    }

}

Viewing full version tree in git

if you happen to not have a graphical interface available you can also print out the commit graph on the command line:

git log --oneline --graph --decorate --all

if this command complains with an invalid option --oneline, use:

git log --pretty=oneline --graph --decorate --all

Add item to array in VBScript

Based on Charles Clayton's answer, but slightly simplified...

' add item to array
Sub ArrayAdd(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
End Sub

Used like so

a = Array()
AddItem(a, 5)
AddItem(a, "foo")

How to check if a string "StartsWith" another string?

I just wanted to add my opinion about this.

I think we can just use like this:

var haystack = 'hello world';
var needle = 'he';

if (haystack.indexOf(needle) == 0) {
  // Code if string starts with this substring
}

Creating a daemon in Linux

I can stop at the first requirement "A daemon which cannot be stopped ..."

Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.

http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring

All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.

NameError: name 'self' is not defined

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

Maven dependencies are failing with a 501 error

I have the same issue, but I use GitLab instead of Jenkins. The steps I had to do to get over the issue:

  1. My project is in GitLab so it uses the .yml file which points to a Docker image I have to do continuous integration, and the image it uses has the http://maven URLs. So I changed that to https://maven.
  2. That same Dockerfile image had an older version of Maven 3.0.1 that gave me issues just overnight. I updated the Dockerfile to get the latest version 3.6.3
  3. I then deployed that image to my online repository, and updated my Maven project ymlfile to use that new image.
  4. And lastly, I updated my main projects POM file to reference https://maven... instead of http://maven

I realize that is more specific to my setup. But without doing all of the steps above I would still continue to get this error message Return code is: 501 , ReasonPhrase:HTTPS Required

Python constructors and __init__

Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.

What you typically use them for is create variables for that object like this:

>>> class testing:
...     def __init__(self, init_value):
...         self.some_value = init_value

So what you could do then is to create an object from this class like this:

>>> testobject = testing(5)

The testobject will then have an object called some_value that in this sample will be 5.

>>> testobject.some_value
5

But you don't need to set a value for each object like i did in my sample. You can also do like this:

>>> class testing:
...     def __init__(self):
...         self.some_value = 5

then the value of some_value will be 5 and you don't have to set it when you create the object.

>>> testobject = testing()
>>> testobject.some_value
5

the >>> and ... in my sample is not what you write. It's how it would look in pyshell...

How to stop an animation (cancel() does not work)

To stop animation you may set such objectAnimator that do nothing, e.g.

first when manual flipping there is animation left to right:

flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);

then when switching to auto flipping there's no animation

flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);

doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);

SQL Server : Transpose rows to columns

Based on the solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
--        table and FIeldToTranspose should be written using single quotes
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

How can you sort an array without mutating the original array?

You need to copy the array before you sort it. One way with es6:

const sorted = [...arr].sort();

the spread-syntax as array literal (copied from mdn):

var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Row Offset in SQL Server

This is one way (SQL2000)

SELECT * FROM
(
    SELECT TOP (@pageSize) * FROM
    (
        SELECT TOP (@pageNumber * @pageSize) *
        FROM tableName 
        ORDER BY columnName ASC
    ) AS t1 
    ORDER BY columnName DESC
) AS t2 
ORDER BY columnName ASC

and this is another way (SQL 2005)

;WITH results AS (
    SELECT 
        rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )
        , *
    FROM tableName 
) 
SELECT * 
FROM results
WHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize

How to extend / inherit components?

Components can be extended as same as a typescript class inheritance, just that you have to override the selector with a new name. All Input() and Output() Properties from the Parent Component works as normal

Update

@Component is a decorator,

Decorators are applied during the declaration of class not on objects.

Basically, decorators add some metadata to the class object and that cannot be accessed via inheritance.

If you want to achieve the Decorator Inheritance I would Suggest writing a custom decorator. Something like below example.

export function CustomComponent(annotation: any) {
    return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;

    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
    var parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
    var parentPropMetadata = Reflect.getMetadata('propMetadata', parentTarget);
    var parentParameters = Reflect.getMetadata('parameters', parentTarget);

    var parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
    if (isPresent(parentAnnotation[key])) {
        if (!isPresent(annotation[key])) {
        annotation[key] = parentAnnotation[key];
        }
    }
    });
    // Same for the other metadata
    var metadata = new ComponentMetadata(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
    };
};

Refer: https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7

How to catch an Exception from a thread

Use Callable instead of Thread, then you can call Future#get() which throws any exception that the Callable threw.

How to export dataGridView data Instantly to Excel on button click?

Interop is slow and has other issues, using the the clipboard seems non extensible. Here are two other ways to do this

  1. Work with Excel 2007+ files directly instead of working with Excel, it'll be much (much) faster. You can use OpenXML (http://openxmldeveloper.org/) which is Microsoft's SDK. The best way to learn OpenXML is to download the Productivity tool (http://www.microsoft.com/en-us/download/details.aspx?id=5124), ittakes an existing file and generates the code required to create it. Another, perhaps simpler, option is to use ClosedXML (http://closedxml.codeplex.com/). It seems a lot easier to use (look at the example http://closedxml.codeplex.com/wikipage?title=Showcase&referringTitle=Home), but I have no experience with it. I'm sure there are other libraries that wrap work with Excel.

  2. Work with excel via OLEDB. This allows you to work with Excel as if it's a dababase. See http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB or Performance of OLEDB to read Excel for examples and more details.

I'd start with ClosedXML.

Save modifications in place with awk

In case you want an awk-only solution without creating a temporary file and usable with version!=(gawk 4.1.0):

awk '{a[b++]=$0} END {for(c=0;c<=b;c++)print a[c]>ARGV[1]}' file

How to handle change of checkbox using jQuery?

$('#myForm').on('change', 'input[type=checkbox]', function() {
    this.checked ? this.value = 'apple' : this.value = 'pineapple';
});

Javascript: How to loop through ALL DOM elements on a page?

You can try with document.getElementsByClassName('special_class');

Is it possible to append Series to rows of DataFrame without making a list first?

DataFrame.append does not modify the DataFrame in place. You need to do df = df.append(...) if you want to reassign it back to the original variable.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

What's the difference between a word and byte?

A word is the size of the registers in the processor. This means processor instructions like, add, mul, etc are on word-sized inputs.

But most modern architectures have memory that is addressable in 8-bit chunks, so it is convenient to use the word "byte".

How do you handle a form change in jQuery?

Looking at the updated question try something like

$('input, textarea, select').each(function(){
    $(this).data("val", $(this).val());
});
$('#button').click(function() {
    $('input, textarea, select').each(function(){
        if($(this).data("val")!==$(this).val()) alert("Things Changed");
    });
});

For the original question use something like

$('input').change(function() {
    alert("Things have changed!");
});

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

How do I go about adding an image into a java project with eclipse?

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

Find non-ASCII characters in varchar columns using SQL Server

running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.

(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)

patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows

select dodgyColumn from myTable fcc
WHERE  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0

the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows

select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32 
    OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127

udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows

select dodgyColumn 
from myTable 
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

How to return the output of stored procedure into a variable in sql server

That depends on the nature of the information you want to return.

If it is a single integer value, you can use the return statement

 create proc myproc
 as 
 begin
     return 1
 end
 go
 declare @i int
 exec @i = myproc

If you have a non integer value, or a number of scalar values, you can use output parameters

create proc myproc
  @a int output,
  @b varchar(50) output
as
begin
  select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output

If you want to return a dataset, you can use insert exec

create proc myproc
as 
begin
     select name from sysobjects
end
go

declare @t table (name varchar(100))
insert @t (name)
exec myproc

You can even return a cursor but that's just horrid so I shan't give an example :)

Get generic type of java.util.List

If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a Collection and then access their generic types:

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

public class Test {

    public List<String> test() {
        return null;
    }

    public static void main(String[] args) throws Exception {

        for (Method method : Test.class.getMethods()) {
            Class returnClass = method.getReturnType();
            if (Collection.class.isAssignableFrom(returnClass)) {
                Type returnType = method.getGenericReturnType();
                if (returnType instanceof ParameterizedType) {
                    ParameterizedType paramType = (ParameterizedType) returnType;
                    Type[] argTypes = paramType.getActualTypeArguments();
                    if (argTypes.length > 0) {
                        System.out.println("Generic type is " + argTypes[0]);
                    }
                }
            }
        }

    }

}

This outputs:

Generic type is class java.lang.String

Angular 2 Checkbox Two Way Data Binding

I have done a custom component tried two way binding

Mycomponent: <input type="checkbox" [(ngModel)]="model" >

_model:  boolean;   

@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();

@Input('checked')
set model(checked: boolean) {

  this._model = checked;
  this.checked.emit(this._model);
  console.log('@Input(setmodel'+checked);
}

get model() {
  return this._model;
}

strange thing is this works

<mycheckbox  [checked]="isChecked" (checked)="isChecked = $event">

while this wont

<mycheckbox  [(checked)]="isChecked">

If a folder does not exist, create it

You can create the path if it doesn't exist yet with a method like the following:

using System.IO;

private void CreateIfMissing(string path)
{
  bool folderExists = Directory.Exists(Server.MapPath(path));
  if (!folderExists)
    Directory.CreateDirectory(Server.MapPath(path));
}

Restarting cron after changing crontab file?

Depending on distribution, using "cron reload" might do nothing. To paste a snippet out of init.d/cron (debian squeeze):

reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "cron"
    # cron reloads automatically
    log_end_msg 0
    ;;

Some developer/maintainer relied on it reloading, but doesn't, and in this case there's not a way to force reload. I'm generating my crontab files as part of a deploy, and unless somehow the length of the file changes, the changes are not reloaded.

Get the string representation of a DOM node

You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.

How to determine total number of open/active connections in ms sql server 2005

see sp_who it gives you more details than just seeing the number of connections

in your case i would do something like this

 DECLARE @temp TABLE(spid int , ecid int, status varchar(50),
                     loginname varchar(50),   
                     hostname varchar(50),
blk varchar(50), dbname varchar(50), cmd varchar(50), request_id int) 
INSERT INTO @temp  

EXEC sp_who

SELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'

What is a monad?

I'm trying to understand monads as well. It's my version:

Monads are about making abstractions about repetitive things. Firstly, monad itself is a typed interface (like an abstract generic class), that has two functions: bind and return that have defined signatures. And then, we can create concrete monads based on that abstract monad, of course with specific implementations of bind and return. Additionally, bind and return must fulfill a few invariants in order to make it possible to compose/chain concrete monads.

Why create the monad concept while we have interfaces, types, classes and other tools to create abstractions? Because monads give more: they enforce rethinking problems in a way that enables to compose data without any boilerplate.

serialize/deserialize java 8 java.time with Jackson JSON mapper

For those who use Spring Boot 2.x

There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.

See this reference too JSON Java 8 LocalDateTime format in Spring Boot

Retrieving Property name from lambda expression

I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
    var expression = (MemberExpression)action.Body;
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

And then call it like so.

GetInfo((User u) => u.UserId);

and voila it works.

org.hibernate.PersistentObjectException: detached entity passed to persist

Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.

The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:

  • Obtain the session
  • Fetch the objects you need to update or add associations to. Preferabley by their primary key
  • Alter what is needed
  • Save/update/evict/delete what you want
  • Close/commit your session/transaction

If you keep having issues post some of the code that is calling your service.

How do I obtain a list of all schemas in a Sql Server database

You can also use the following query to get Schemas for a specific Database user:

select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

What are the lengths of Location Coordinates, latitude and longitude?

Valid longitudes are from -180 to 180 degrees.

Latitudes are supposed to be from -90 degrees to 90 degrees, but areas very near to the poles are not indexable.

So exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

  • Valid longitudes are from -180 to 180 degrees.
  • Valid latitudes are from -85.05112878 to 85.05112878 degrees.

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

HTML Submit-button: Different value / button-text?

If you handle "adding tag" via JScript:

<form ...>
<button onclick="...">any text you want</button>
</form>

Or above if handle via page reload

How to get the HTML for a DOM element in javascript

If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-

function getHTML(who,lines){
    if(!who || !who.tagName) return '';

    var txt, ax, str, el= document.createElement('div');
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;
    ax= txt.indexOf('>')+1;
    str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);

    el= null;
    return lines? str.replace(/> *</g,'>\n<'): str;
    //easier to read if elements are separated
}

Change selected value of kendo ui dropdownlist

You have to use Kendo UI DropDownList select method (documentation in here).

Basically you should:

// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");

If you know the index you can use:

// selects by index
dropdownlist.select(1);

If not, use:

// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
    return dataItem.symbol === "test";
});

JSFiddle example here

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

MySQL select with CONCAT condition

There is an alternative to repeating the CONCAT expression or using subqueries. You can make use of the HAVING clause, which recognizes column aliases.

SELECT 
  neededfield, CONCAT(firstname, ' ', lastname) AS firstlast 
FROM
  users 
HAVING firstlast = "Bob Michael Jones"

Here is a working SQL Fiddle.

Best way to restrict a text field to numbers only?

This is my plugin for that case:

 (function( $ ) {
    $.fn.numbers = function(options) {
      $(this).keypress(function(evt){
          var setting = $.extend( {
                'digits' : 8
              }, options);
          if($(this).val().length > (setting.digits - 1) && evt.which != 8){
              evt.preventDefault(); 
          }
          else{
              if(evt.which < 48 || evt.which > 57){
                if(evt.keyCode != 8){
                    evt.preventDefault();  
                }
              }
          }
      });
    };
  })( jQuery );

Use:

 $('#limin').numbers({digits:3});
 $('#limax').numbers();

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

How to convert hex to ASCII characters in the Linux shell?

You can make it through echo only and without the other stuff. Don't forget to add "-n" or you will get a linebreak automatically:

echo -n -e "\x5a"

Script not served by static file handler on IIS7.5

Navigate to your flavor of .Net and CPU architecture directory using CMD or powershell

Enter this command: aspnet_regiis –r

Detect home button press in android

It is impossible to detect and/or intercept the HOME button from within an Android app. This is built into the system to prevent malicious apps that cannot be exited.

Passing in class names to react components

In React, when you want to pass an interpreted expression, you have to open a pair of curly braces. Try:

render () {
  return (
    <button className={`pill ${ this.props.styleName }`}>
      {this.props.children}
    </button>
  );
}

Using the classnames npm package

import classnames from 'classnames';

render() {
  return (
    <button className={classnames('pill', this.props.styleName)}>
      {this.props.children}
    </button>
  );
}

Difference between declaring variables before or in loop?

It is language dependent - IIRC C# optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation shebang each time.

'dict' object has no attribute 'has_key'

I think it is considered "more pythonic" to just use in when determining if a key already exists, as in

if start not in graph:
    return None

git add, commit and push commands in one?

This Result - Try this: Simple script one command for git add, git commit and git push

Open your CMD on Windows and paste this answer

git commit -m "your message" . && git push origin master

This example my picture screenshot : https://i.stack.imgur.com/2IZDe.jpg

JavaScript before leaving the page

This code when you also detect form state changed or not.

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

What's wrong with using == to compare floats in Java?

One way to reduce rounding error is to use double rather than float. This won't make the problem go away, but it does reduce the amount of error in your program and float is almost never the best choice. IMHO.

How do I convert from BLOB to TEXT in MySQL?

Or you can use this function:

DELIMITER $$

CREATE FUNCTION BLOB2TXT (blobfield VARCHAR(255)) RETURNS longtext
DETERMINISTIC
NO SQL
BEGIN
       RETURN CAST(blobfield AS CHAR(10000) CHARACTER SET utf8);
END
$$


DELIMITER ;

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

Calculate number of hours between 2 dates in PHP

First, you should create an interval object from a range of dates. By the wording used in this sentence alone, one can easily identify basic abstractions needed. There is an interval as a concept, and a couple of more ways to implement it, include the one already mentioned -- from a range of dates. Thus, an interval looks like that:

$interval =
    new FromRange(
        new FromISO8601('2017-02-14T14:27:39+00:00'),
        new FromISO8601('2017-03-14T14:27:39+00:00')
    );

FromISO8601 has the same semantics: it's a datetime object created from iso8601-formatted string, hence the name.

When you have an interval, you can format it however you like. If you need a number of full hours, you can have

(new TotalFullHours($interval))->value();

If you want a ceiled total hours, here you go:

(new TotalCeiledHours($interval))->value();

For more about this approach and some examples, check out this entry.

Ignoring SSL certificate in Apache HttpClient 4.3

class ApacheHttpClient {

    /***
     * This is a https get request that bypasses certificate checking and hostname verifier.
     * It uses basis authentication method.
     * It is tested with Apache httpclient-4.4.
     * It dumps the contents of a https page on the console output.
     * It is very similar to http get request, but with the additional customization of
     *   - credential provider, and
     *   - SSLConnectionSocketFactory to bypass certification checking and hostname verifier.
     * @param path String
     * @param username String
     * @param password String
     * @throws IOException
     */
    public void get(String path, String username, String password) throws IOException {
        final CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(createCredsProvider(username, password))
                .setSSLSocketFactory(createGenerousSSLSocketFactory())
                .build();

        final CloseableHttpResponse response = httpClient.execute(new HttpGet(path));
        try {
            HttpEntity entity = response.getEntity();
            if (entity == null)
                return;
            System.out.println(EntityUtils.toString(entity));
        } finally {
            response.close();
            httpClient.close();
        }
    }

    private CredentialsProvider createCredsProvider(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        return credsProvider;
    }

    /***
     * 
     * @return SSLConnectionSocketFactory that bypass certificate check and bypass HostnameVerifier
     */
    private SSLConnectionSocketFactory createGenerousSSLSocketFactory() {
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{createGenerousTrustManager()}, new SecureRandom());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    }

    private X509TrustManager createGenerousTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
    }
}

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Adding :default => true to boolean in existing Rails column

As a variation on the accepted answer you could also use the change_column_default method in your migrations:

def up
  change_column_default :profiles, :show_attribute, true
end

def down
  change_column_default :profiles, :show_attribute, nil
end

Rails API-docs

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

On the CREATE TABLE,

The AUTO_INCREMENT of abuse_id is set to 2. MySQL now thinks 1 already exists.

With the INSERT statement you are trying to insert abuse_id with record 1. Please set AUTO_INCREMENT on CREATE_TABLE to 1 and try again.

Otherwise set the abuse_id in the INSERT statement to 'NULL'.

How can i resolve this?

How can I check if a jQuery plugin is loaded?

To detect jQuery plugins I found more accurate to use the brackets:

if(jQuery().pluginName) {
    //run plugin dependent code
}

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

Create a .csv file with values from a Python list

Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.

For example, here is the worked example for you:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"

How do I create an Android Spinner as a popup?

You can create your own custom Dialog. It's fairly easy. If you want to dismiss it with a selection in the spinner, then add an OnItemClickListener and add

int n = mSpinner.getSelectedItemPosition();
mReadyListener.ready(n);
SpinnerDialog.this.dismiss();

as in the OnClickListener for the OK button. There's one caveat, though, and it's that the onclick listener does not fire if you reselect the default option. You need the OK button also.

Start with the layout:

res/layout/spinner_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content">
<TextView 
    android:id="@+id/dialog_label" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    android:hint="Please select an option" 
    />
<Spinner
    android:id="@+id/dialog_spinner" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    />
<Button
    android:id="@+id/dialogOK" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="OK"
    android:layout_below="@id/dialog_spinner"
    />
<Button
    android:id="@+id/dialogCancel" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="Cancel"
    android:layout_below="@id/dialog_spinner"
    android:layout_toRightOf="@id/dialogOK"
    />
</RelativeLayout>

Then, create the class:

src/your/package/SpinnerDialog.java:

public class SpinnerDialog extends Dialog {
    private ArrayList<String> mList;
    private Context mContext;
    private Spinner mSpinner;

   public interface DialogListener {
        public void ready(int n);
        public void cancelled();
    }

    private DialogListener mReadyListener;

    public SpinnerDialog(Context context, ArrayList<String> list, DialogListener readyListener) {
        super(context);
        mReadyListener = readyListener;
        mContext = context;
        mList = new ArrayList<String>();
        mList = list;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner_dialog);
        mSpinner = (Spinner) findViewById (R.id.dialog_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (mContext, android.R.layout.simple_spinner_dropdown_item, mList);
        mSpinner.setAdapter(adapter);

        Button buttonOK = (Button) findViewById(R.id.dialogOK);
        Button buttonCancel = (Button) findViewById(R.id.dialogCancel);
        buttonOK.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                int n = mSpinner.getSelectedItemPosition();
                mReadyListener.ready(n);
                SpinnerDialog.this.dismiss();
            }
        });
        buttonCancel.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                mReadyListener.cancelled();
                SpinnerDialog.this.dismiss();
            }
        });
    }
}

Finally, use it as:

mSpinnerDialog = new SpinnerDialog(this, mTimers, new SpinnerDialog.DialogListener() {
  public void cancelled() {
    // do your code here
  }
  public void ready(int n) {
    // do your code here
  }
});

Figure out size of UILabel based on String in Swift

For multiline text this answer is not working correctly. You can build a different String extension by using UILabel

extension String {
func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let label =  UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.text = self
    label.font = font
    label.sizeToFit()

    return label.frame.height
 }
}

The UILabel gets a fixed width and the .numberOfLines is set to 0. By adding the text and calling .sizeToFit() it automatically adjusts to the correct height.

Code is written in Swift 3

How to get the separate digits of an int number?

I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:

int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();

To be clear: You use String.valueOf(number) to convert int to String, then chars() method to get an IntStream (each char from your string is now an Ascii number), then you need to run map() method to get a numeric values of the Ascii number. At the end you use toArray() method to change your stream into an int[] array.

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

You might have pressed 0 (also used for insert, shortcut INS) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.

Intellij idea cannot resolve anything in maven

In my case,i expanded the maven projects panel on the right side, clicked + and added the project. Then it worked.

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

What's the main difference between int.Parse() and Convert.ToInt32

for clarification open console application, just copy below code and paste it in static void Main(string[] args) method, I hope you can understand

public  class Program
    {
        static void Main(string[] args)
        { 
            int result;
            bool status;
            string s1 = "12345";
            Console.WriteLine("input1:12345");
            string s2 = "1234.45";
            Console.WriteLine("input2:1234.45");
            string s3 = null;
            Console.WriteLine("input3:null");
            string s4 = "1234567899012345677890123456789012345667890";
            Console.WriteLine("input4:1234567899012345677890123456789012345667890");
            string s5 = string.Empty;
            Console.WriteLine("input5:String.Empty");
            Console.WriteLine();
            Console.WriteLine("--------Int.Parse Methods Outputs-------------");
            try
            {
               result = int.Parse(s1);

               Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:"+ee.Message);
            }
            try
            {
              result = int.Parse(s2);

              Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {
               result = int.Parse(s3);

               Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {
                result = int.Parse(s4);

                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {
                 result = int.Parse(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }
            Console.WriteLine();
            Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
            try
            {

                result=  Convert.ToInt32(s1);

                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                result = Convert.ToInt32(s2);

                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

         result = Convert.ToInt32(s3);

         Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                  result = Convert.ToInt32(s4);

                  Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                 result = Convert.ToInt32(s5);

                 Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }

            Console.WriteLine();
            Console.WriteLine("--------TryParse Methods Outputs-------------");
            try
            {

                status = int.TryParse(s1, out result);
                Console.WriteLine("OutPut1:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut1:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s2, out result);
                Console.WriteLine("OutPut2:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut2:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s3, out result);
                Console.WriteLine("OutPut3:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut3:" + ee.Message);
            }
            try
            {

                status = int.TryParse(s4, out result);
                Console.WriteLine("OutPut4:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut4:" + ee.Message);
            }

            try
            {

                status = int.TryParse(s5, out result);
                Console.WriteLine("OutPut5:" + result);
            }
            catch (Exception ee)
            {
                Console.WriteLine("OutPut5:" + ee.Message);
            }


            Console.Read();
        }
    }

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

Get checkbox list values with jQuery

Not tested but should work:

$("#MyDiv td input:checked").each(function()
{
    alert($(this).attr("id"));
});

Converting Symbols, Accent Letters to English Alphabet

String tested : ÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝß

Tested :

  • Output from Apache Commons Lang3 : AAAAAÆCEEEEIIIIÐNOOOOOØUUUUYß
  • Output from ICU4j : AAAAAÆCEEEEIIIIÐNOOOOOØUUUUYß
  • Output from JUnidecode : AAAAAAECEEEEIIIIDNOOOOOOUUUUUss (problem with Ý and another issue)
  • Output from Unidecode : AAAAAAECEEEEIIIIDNOOOOOOUUUUYss

The last choice is the best.

How to redirect 404 errors to a page in ExpressJS?

What I do after defining all routes is to catch potential 404 and forward to error handler, like this:

    const httpError = require('http-errors');

    ...

    // API router
    app.use('/api/', routes);
    
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
      const err = new httpError(404)
      return next(err);
    });

    module.exports = app;

How to get all Errors from ASP.Net MVC modelState?

Useful for passing array of error messages to View, perhaps via Json:

messageArray = this.ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors, (modelState, error) => error.ErrorMessage).ToArray();

int value under 10 convert to string two digit number

You can also do it this way

private static string GetPaddingSequence(int padding)
{
      StringBuilder SB = new StringBuilder();
      for (int i = 0; i < padding; i++)
      {
           SB.Append("0");
      }

      return SB.ToString();
  }

public static string FormatNumber(int number, int padding)
{
    return number.ToString(GetPaddingSequence(padding));
}

Finally call the function FormatNumber

string x = FormatNumber(1,2);

Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

htaccess "order" Deny, Allow, Deny

As Gerben suggested, just change:

order deny,allow
deny from all

to

order allow,deny

And the restrictions will work as you want them to.

Details can be found in Apache's docs.

How can I use jQuery in Greasemonkey?

You might get Component unavailable if you import the jQuery script directly.

Maybe it's what @Conley was talking about...

You can use

@require        http://userscripts.org/scripts/source/85365.user.js

which is an modified version to work on Greasemonkey, and then get the jQuery object

var $ = unsafeWindow.jQuery;
$("div").css("display", "none");

How do you uninstall MySQL from Mac OS X?

For me, I had installed MariaDB years ago using homebrew. Correct uninstall procedure was: brew uninstall mariadb.

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

How to add footnotes to GitHub-flavoured Markdown?

For short notes, providing an anchor element with a title attribute creates a "tooltip".

<a title="Note text goes here."><sup>n</sup></a>

Otherwise, for more involved notes, it looks like your best bet is maintaining named links manually.

How to use a variable for a key in a JavaScript object literal?

If you want object key to be same as variable name, there's a short hand in ES 2015. New notations in ECMAScript 2015

var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

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

If you want to use [System.IO.File]::WriteAllLines(), you should cast second parameter to String[] (if the type of $MyFile is Object[]), and also specify absolute path with $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MyPath), like:

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
Get-ChildItem | ConvertTo-Csv | Set-Variable MyFile
[System.IO.File]::WriteAllLines($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MyPath), [String[]]$MyFile, $Utf8NoBomEncoding)

If you want to use [System.IO.File]::WriteAllText(), sometimes you should pipe the second parameter into | Out-String | to add CRLFs to the end of each line explictly (Especially when you use them with ConvertTo-Csv):

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
Get-ChildItem | ConvertTo-Csv | Out-String | Set-Variable tmp
[System.IO.File]::WriteAllText("/absolute/path/to/foobar.csv", $tmp, $Utf8NoBomEncoding)

Or you can use [Text.Encoding]::UTF8.GetBytes() with Set-Content -Encoding Byte:

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
Get-ChildItem | ConvertTo-Csv | Out-String | % { [Text.Encoding]::UTF8.GetBytes($_) } | Set-Content -Encoding Byte -Path "/absolute/path/to/foobar.csv"

see: How to write result of ConvertTo-Csv to a file in UTF-8 without BOM

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

MySQL and GROUP_CONCAT() maximum length

The correct syntax is mysql> SET @@global.group_concat_max_len = integer;
If you do not have the privileges to do this on the server where your database resides then use a query like:
mySQL="SET @@session.group_concat_max_len = 10000;"or a different value.
Next line:
SET objRS = objConn.Execute(mySQL)  your variables may be different.
then
mySQL="SELECT GROUP_CONCAT(......);" etc
I use the last version since I do not have the privileges to change the default value of 1024 globally (using cPanel).
Hope this helps.

extra qualification error in C++

This means a class is redundantly mentioned with a class function. Try removing JSONDeserializer::

Lost connection to MySQL server during query?

I encountered similar problems too. In my case it was solved by getting the cursor in this way:

cursor = self.conn.cursor(buffered=True)

Difference between float and decimal data type

If you are after performance and not precision, you should note that calculations with floats are much faster than decimals

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

Prefer composition over inheritance?

Even though Composition is preferred, I would like to highlight pros of Inheritance and cons of Composition.

Pros of Inheritance:

  1. It establishes a logical "IS A" relation. If Car and Truck are two types of Vehicle ( base class), child class IS A base class.

    i.e.

    Car is a Vehicle

    Truck is a Vehicle

  2. With inheritance, you can define/modify/extend a capability

    1. Base class provides no implementation and sub-class has to override complete method (abstract) => You can implement a contract
    2. Base class provides default implementation and sub-class can change the behaviour => You can re-define contract
    3. Sub-class adds extension to base class implementation by calling super.methodName() as first statement => You can extend a contract
    4. Base class defines structure of the algorithm and sub-class will override a part of algorithm => You can implement Template_method without change in base class skeleton

Cons of Composition:

  1. In inheritance, subclass can directly invoke base class method even though it's not implementing base class method because of IS A relation. If you use composition, you have to add methods in container class to expose contained class API

e.g. If Car contains Vehicle and if you have to get price of the Car, which has been defined in Vehicle, your code will be like this

class Vehicle{
     protected double getPrice(){
          // return price
     }
} 

class Car{
     Vehicle vehicle;
     protected double getPrice(){
          return vehicle.getPrice();
     }
} 

How should I copy Strings in Java?

Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

How to update/refresh specific item in RecyclerView

Below solution worked for me:

On a RecyclerView item, user will click a button but another view like TextView will update without directly notifying adapter:

I found a good solution for this without using notifyDataSetChanged() method, this method reloads all data of recyclerView so if you have image or video inside item then they will reload and user experience will not good:

Here is an example of click on a ImageView like icon and only update a single TextView (Possible to update more view in same way of same item) to show like count update after adding +1:

// View holder class inside adapter class
public class MyViewHolder extends RecyclerView.ViewHolder{

    ImageView imageViewLike;

    public MyViewHolder(View itemView) {
         super(itemView);

        imageViewLike = itemView.findViewById(R.id.imageViewLike);
        imageViewLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = getAdapterPosition(); // Get clicked item position
                TextView tv = v.getRootView().findViewById(R.id.textViewLikeCount); // Find textView of recyclerView item
                resultList.get(pos).setLike(resultList.get(pos).getLike() + 1); // Need to change data list to show updated data again after scrolling
                tv.setText(String.valueOf(resultList.get(pos).getLike())); // Set data to TextView from updated list
            }
        });
    }

Eclipse internal error while initializing Java tooling

check the Eclipse log (the intelligently named ".log" file in your workspace .metadata folder) and check for the complete stacktrace. In my case it was caused at method "org.eclipse.m2e.jdt.internal.MavenClasspathVariableInitializer.initialize(MavenClasspathVariableInitializer.java:30)" which lead to a never fixed "race condition during startup" bug. I would really recommend dumping Eclipse in favor of a more serious IDE; like IntelliJ or Netbeans. Using Eclipse means that you will invest 40-50% of your time trying to work around this kind of bugs, instead of being productive.

What is the LDF file in SQL Server?

The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.

You do not want to delete, but you can shrink it with the dbcc shrinkfile command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.

Why does CSS not support negative padding?

Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)

Negative margins would be an easy solution.

Alternative to deprecated getCellType

It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated. A lot of disturbances for little add value...

How do I get a human-readable file size in bytes abbreviation using .NET?

Mixture of all solutions :-)

    /// <summary>
    /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,
    /// kilobytes, megabytes, or gigabytes, depending on the size.
    /// </summary>
    /// <param name="fileSize">The numeric value to be converted.</param>
    /// <returns>The converted string.</returns>
    public static string FormatByteSize(double fileSize)
    {
        FileSizeUnit unit = FileSizeUnit.B;
        while (fileSize >= 1024 && unit < FileSizeUnit.YB)
        {
            fileSize = fileSize / 1024;
            unit++;
        }
        return string.Format("{0:0.##} {1}", fileSize, unit);
    }

    /// <summary>
    /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,
    /// kilobytes, megabytes, or gigabytes, depending on the size.
    /// </summary>
    /// <param name="fileInfo"></param>
    /// <returns>The converted string.</returns>
    public static string FormatByteSize(FileInfo fileInfo)
    {
        return FormatByteSize(fileInfo.Length);
    }
}

public enum FileSizeUnit : byte
{
    B,
    KB,
    MB,
    GB,
    TB,
    PB,
    EB,
    ZB,
    YB
}

How do I display local image in markdown?

I got a solution:

a) Example Internet:

![image info e.g. Alt](URL Internet to Images.jpg "Image Description")

b) Example local Image:

![image Info](file:///<Path to your File><image>.jpg "Image Description")
![image Info](file:///C:/Users/<name>/Pictures/<image>.jpg "Image Description")

TurboByte

Check if a number is int or float

You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

. "$PSScriptRoot\MyFunctions.ps1" MyA1Func

Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.

P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).

How can I measure the similarity between two images?

Well, not to answer your question directly, but I have seen this happen. Microsoft recently launched a tool called PhotoSynth which does something very similar to determine overlapping areas in a large number of pictures (which could be of different aspect ratios).

I wonder if they have any available libraries or code snippets on their blog.

Calculate days between two Dates in Java 8

Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).

The docs for both actually mention both approaches and say to use whichever one is more readable.

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

What is the difference between an interface and abstract class?

I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here.

tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.

Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.

ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?

Answer 2: Abstract classes can have a function body as partial/default implementation.

ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?

Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.

ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.

Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.

Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.

Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.

Coming to the UML Part. You should be familiar with below relationships:

  • Is A
  • Has A
  • Uses

Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?

Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.

When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:

abstract class Car
{
   string color;
   int speed;
}
class HondaAccord : Car
{
   MusicPlayer musicPlayer;
}

Now Honda doesn't manufacture music players. Or at least it’s not their main business.

So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.

This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.

You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.

Why can’t you create an object of abstract classes?

Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.

Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.

Why do interfaces allow multiple inheritance?

Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:

abstract class Car
{
    string color;
    int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
    MusicPlayer musicPlayer;
}

And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

Scripting Language vs Programming Language

Programming Language : Is compiled to machine code and run on the hardware of the underlying Operating System.

Scripting Language : Is unstructure subset of programming language. It is generally interpreted. it basically "scripts" other things to do stuff. The primary focus isn't primarily building your own apps but getting an existing app to act the way you want, e.g. JavaScript for browsers, TCL etc.,

*** But there are situation where a programming language is converted to interpreter and vice-verse like use have a C interpreter where you can 'C' Script. Scripts are generally written to control an application behaviour where as Programming Language is use to build applications. But beware that the demarcation is blurring day - by - day as an example of Python it depends on how one uses the language.

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

JComboBox Selection Change Listener?

I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.

How do I get the previous or last item?

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

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

How can I calculate the time between 2 Dates in typescript

Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:

var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();

Force youtube embed to start in 720p

I've managed to get this working by the following fix:

//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720

You video should have the hd720 resolution to do so.

I was using the embedding via iframe, BTW. Hope someone will find this helpful.

Declaring a boolean in JavaScript using just var

No it is not safe. You could later do var IsLoggedIn = "Foo"; and JavaScript will not throw an error.

It is possible to do

var IsLoggedIn = new Boolean(false);
var IsLoggedIn = new Boolean(true);

You can also pass the non boolean variable into the new Boolean() and it will make IsLoggedIn boolean.

var IsLoggedIn = new Boolean(0); // false
var IsLoggedIn = new Boolean(NaN); // false
var IsLoggedIn = new Boolean("Foo"); // true
var IsLoggedIn = new Boolean(1); // true

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

All sprints are iterations but not all iterations are sprints. Iteration is a common term in iterative and incremental development (IID). Scrum is one specialized flavor of IID so it makes sense to specialize the terminology as well. It also helps brand the methodology different from other IID methodologies :)

As to the sprint length: anything goes as long as the sprint is timeboxed i.e. it is finished on the planned date and not "when it's ready". (Or alternatively, in rare occasions, the sprint is terminated prematurely to start a new sprint in case some essential boundary conditions are changed.)

It does help to have the sprints of similar durations. There's less to remember about the sprint schedule and your planning gets more accurate. I like to keep mine at 2 calendar weeks, which will resolve into 8..10 business days outside holiday seasons.

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

How to enable assembly bind failure logging (Fusion) in .NET

If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:

  1. Create a new application pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new pool

Use find command but exclude files in two directories

Here is one way you could do it...

find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"

OkHttp Post Body as JSON

You can create your own JSONObject then toString().

Remember run it in the background thread like doInBackground in AsyncTask.

OkHttp version > 4:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
            .url("https://YOUR_URL/")
            .post(body)
            .build()

var response: Response? = null
try {
    response = client.newCall(request).execute()
    val resStr = response.body!!.string()
} catch (e: IOException) {
    e.printStackTrace()
}
   

OkHttp version 3:

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

How to get the integer value of day of week

Try this. It will work just fine:

int week = Convert.ToInt32(currentDateTime.DayOfWeek);

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

react-native: command not found

According to official documentation, the following command worked for me.

  • npx react-native run-android

Link is here

I was trying to run by "react-native run-android" command. make sure to have react-native cli installed globally!

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Repeat String - Javascript

Good news! String.prototype.repeat is now a part of JavaScript.

"yo".repeat(2);
// returns: "yoyo"

The method is supported by all major browsers, except Internet Explorer. For an up to date list, see MDN: String.prototype.repeat > Browser compatibility.

MDN has a polyfill for browsers without support.

How to get ID of the last updated row in MySQL?

Hm, I am surprised that among the answers I do not see the easiest solution.

Suppose, item_id is an integer identity column in items table and you update rows with the following statement:

UPDATE items
SET qwe = 'qwe'
WHERE asd = 'asd';

Then, to know the latest affected row right after the statement, you should slightly update the statement into the following:

UPDATE items
SET qwe = 'qwe',
    item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();

If you need to update only really changed row, you would need to add a conditional update of the item_id through the LAST_INSERT_ID checking if the data is going to change in the row.

Checking for Undefined In React

In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
    //
}

And, when an undefined , empty or null value is not expected; you can make it more concise:

if (nextProps.blog && nextProps.blog.content) {
    //
}

How to change or add theme to Android Studio?

File - Settings - Appearance & Behavior - Appearance - CHOOSE Darcula in "Theme" - Press Apply.

or

Choose File - Settings - Editor - Colors & Fonts - Then SELECT Darcula in scheme name - Press Apply - restart Studio (sometimes not all elements implement theme)

How to write new line character to a file in Java

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();

Bootstrap Carousel : Remove auto slide

You can do this 2 ways, via js or html (easist)

  1. Via js
$('.carousel').carousel({
  interval: false,
});

That will make the auto sliding stop because there no Milliseconds added and will never slider next.

  1. Via Html By adding data-interval="false" and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">

becomes:

<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">

updated based on @webMan's comment

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Is there a JavaScript strcmp()?

var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;

Usage: strcmp(string1, string2)

Result: 1 means string1 is bigger, 0 means equal, -1 means string2 is bigger.

This has higher performance than String.prototype.localeCompare

Also, numeric:true makes it do logical number comparison

Scale an equation to fit exact page width

I just had the situation that I wanted this only for lines exceeding \linewidth, that is: Squeezing long lines slightly. Since it took me hours to figure this out, I would like to add it here.

I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g. multline of the mathtools package). So use it conscious.

In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.

\usepackage{environ}         % provides \BODY
\usepackage{etoolbox}        % provides \ifdimcomp
\usepackage{graphicx}        % provides \resizebox

\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation

\RenewEnviron{equation}{
  \settowidth{\myl}{$\BODY$}                       % calculate width and save as \myl
  \origequation
  \ifdimcomp{\the\linewidth}{>}{\the\myl}
  {\ensuremath{\BODY}}                             % True
  {\resizebox{\linewidth}{!}{\ensuremath{\BODY}}}  % False
  \origendequation
}

Before before After after

Is there a Google Voice API?

I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:

http://github.com/mastermind202/GoogleVoice

I hope others find it useful. Feedback and suggestions welcome.

Difference between size and length methods?

  • .length is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.

  • length() is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.

  • size() is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.

MySQL error: key specification without a key length

Also, if you want to use index in this field, you should use the MyISAM storage engine and the FULLTEXT index type.

Converting year and month ("yyyy-mm" format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

How to limit text width

use css property word-wrap: break-word;

see example here: http://jsfiddle.net/emgRF/

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

You need to enable SQL Server Authentication:

  1. In the Object Explorer, right click on the server and click on "Properties"

DBMS Properties dialog

  1. In the "Server Properties" window click on "Security" in the list of pages on the left. Under "Server Authentication" choose the "SQL Server and Windows Authentication mode" radio option.

SQL Server Authentication dialog

  1. Restart the SQLEXPRESS service.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

I had the same issue when I was using the main storyboard as the launch screen file. I guess if you are using a storyboard as the launch screen file, it shouldn't be connected to the view controller as it won't have been loaded yet.

HTML forms - input type submit problem with action=URL when URL contains index.aspx

This appears to be my "preferred" solution:

<form action="www.spufalcons.com/index.aspx?tab=gymnastics&path=gym" method="post">  <div>
<input type="submit" value="Gymnastics"></div>

Sorry for the presentation format - I'm still trying to learn how to use this forum....

I do have a follow-up question. In looking at my MySQL database of URL's it appears that ~30% of the URL's will need to use this post/div wrapper approach. This leaves ~70% that cannot accept the "post" attribute. For example:

<form action="http://www.google.com" method="post">
  <div>
    <input type="submit" value="Google"/>
  </div></form>

does not work. Do you have a recommendation for how to best handle this get/post condition test. Off the top of my head I'm guessing that using PHP to evaluate the existence of the "?" character in the URL may be my best approach, although I'm not sure how to structure the HTML form to accomplish this.

Thank YOU!

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had this problem. The solution was to allow node.js through the server's firewall.

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
    title: locations[i].title,
    icon: icon,
    map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
    for(i=0; i<gmarkers.length; i++){
        gmarkers[i].setMap(null);
    }
}

working example (toggles the markers)

code snippet:

_x000D_
_x000D_
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
  stylers: [{_x000D_
    hue: "black"_x000D_
  }, {_x000D_
    saturation: -90_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "geometry",_x000D_
  stylers: [{_x000D_
    lightness: 100_x000D_
  }, {_x000D_
    visibility: "simplified"_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "labels",_x000D_
  stylers: [{_x000D_
    visibility: "on"_x000D_
  }]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
  name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
  center: RoseHulman,_x000D_
  zoom: 15,_x000D_
  mapTypeControl: true,_x000D_
  zoomControl: true,_x000D_
  zoomControlOptions: {_x000D_
    style: google.maps.ZoomControlStyle.SMALL_x000D_
  },_x000D_
  mapTypeControlOptions: {_x000D_
    mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
  },_x000D_
  scrollwheel: false,_x000D_
  streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
  maxWidth: 300,_x000D_
  infoBoxClearance: new google.maps.Size(1, 1),_x000D_
  disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
  "id": "1",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Alpha Tau Omega Fraternity",_x000D_
  "description": "<p>Alpha Tau Omega house</p>",_x000D_
  "longitude": "-87.321133",_x000D_
  "latitude": "39.484092"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment Commons",_x000D_
  "description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
  "longitude": "-87.329282",_x000D_
  "latitude": "39.483599"_x000D_
}, {_x000D_
  "id": "3",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment East",_x000D_
  "description": "<p>Apartment East</p>",_x000D_
  "longitude": "-87.328809",_x000D_
  "latitude": "39.483748"_x000D_
}, {_x000D_
  "id": "4",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment West",_x000D_
  "description": "<p>Apartment West</p>",_x000D_
  "longitude": "-87.329732",_x000D_
  "latitude": "39.483429"_x000D_
}, {_x000D_
  "id": "5",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
  "description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.482382"_x000D_
}, {_x000D_
  "id": "6",_x000D_
  "category": "6",_x000D_
  "campus_location": "D3",_x000D_
  "title": "Blumberg Hall",_x000D_
  "description": "<p>Blumberg Hall</p>",_x000D_
  "longitude": "-87.328321",_x000D_
  "latitude": "39.483388"_x000D_
}, {_x000D_
  "id": "7",_x000D_
  "category": "1",_x000D_
  "campus_location": "E1",_x000D_
  "title": "The Branam Innovation Center",_x000D_
  "description": "<p>The Branam Innovation Center</p>",_x000D_
  "longitude": "-87.322614",_x000D_
  "latitude": "39.48494"_x000D_
}, {_x000D_
  "id": "8",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Chi Omega Sorority",_x000D_
  "description": "<p>Chi Omega house</p>",_x000D_
  "longitude": "-87.319905",_x000D_
  "latitude": "39.482071"_x000D_
}, {_x000D_
  "id": "9",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Cook Stadium/Phil Brown Field",_x000D_
  "description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
  "longitude": "-87.325258",_x000D_
  "latitude": "39.485007"_x000D_
}, {_x000D_
  "id": "10",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Crapo Hall",_x000D_
  "description": "<p>Crapo Hall</p>",_x000D_
  "longitude": "-87.324368",_x000D_
  "latitude": "39.483709"_x000D_
}, {_x000D_
  "id": "11",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Delta Delta Delta Sorority",_x000D_
  "description": "<p>Delta Delta Delta</p>",_x000D_
  "longitude": "-87.317477",_x000D_
  "latitude": "39.482951"_x000D_
}, {_x000D_
  "id": "12",_x000D_
  "category": "6",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Deming Hall",_x000D_
  "description": "<p>Deming Hall</p>",_x000D_
  "longitude": "-87.325822",_x000D_
  "latitude": "39.483421"_x000D_
}, {_x000D_
  "id": "13",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Facilities Operations",_x000D_
  "description": "<p>Facilities Operations</p>",_x000D_
  "longitude": "-87.321782",_x000D_
  "latitude": "39.484916"_x000D_
}, {_x000D_
  "id": "14",_x000D_
  "category": "2",_x000D_
  "campus_location": "E3",_x000D_
  "title": "Flame of the Millennium",_x000D_
  "description": "<p>Flame of Millennium sculpture</p>",_x000D_
  "longitude": "-87.323306",_x000D_
  "latitude": "39.481978"_x000D_
}, {_x000D_
  "id": "15",_x000D_
  "category": "5",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Hadley Hall",_x000D_
  "description": "<p>Hadley Hall</p>",_x000D_
  "longitude": "-87.324046",_x000D_
  "latitude": "39.482887"_x000D_
}, {_x000D_
  "id": "16",_x000D_
  "category": "2",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Hatfield Hall",_x000D_
  "description": "<p>Hatfield Hall</p>",_x000D_
  "longitude": "-87.322340",_x000D_
  "latitude": "39.482146"_x000D_
}, {_x000D_
  "id": "17",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Hulman Memorial Union",_x000D_
  "description": "<p>Hulman Memorial Union</p>",_x000D_
  "longitude": "-87.32698",_x000D_
  "latitude": "39.483574"_x000D_
}, {_x000D_
  "id": "18",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "John T. Myers Center for Technological Research with Industry",_x000D_
  "description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
  "longitude": "-87.322984",_x000D_
  "latitude": "39.484063"_x000D_
}, {_x000D_
  "id": "19",_x000D_
  "category": "6",_x000D_
  "campus_location": "A2",_x000D_
  "title": "Lakeside Hall",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330612",_x000D_
  "latitude": "39.482804"_x000D_
}, {_x000D_
  "id": "20",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Lambda Chi Alpha Fraternity",_x000D_
  "description": "<p>Lambda Chi Alpha</p>",_x000D_
  "longitude": "-87.320999",_x000D_
  "latitude": "39.48305"_x000D_
}, {_x000D_
  "id": "21",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Logan Library",_x000D_
  "description": "<p>Logan Library</p>",_x000D_
  "longitude": "-87.324851",_x000D_
  "latitude": "39.483408"_x000D_
}, {_x000D_
  "id": "22",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Mees Hall",_x000D_
  "description": "<p>Mees Hall</p>",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.483533"_x000D_
}, {_x000D_
  "id": "23",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Moench Hall",_x000D_
  "description": "<p>Moench Hall</p>",_x000D_
  "longitude": "-87.323695",_x000D_
  "latitude": "39.483471"_x000D_
}, {_x000D_
  "id": "24",_x000D_
  "category": "1",_x000D_
  "campus_location": "G4",_x000D_
  "title": "Oakley Observatory",_x000D_
  "description": "<p>Oakley Observatory</p>",_x000D_
  "longitude": "-87.31616",_x000D_
  "latitude": "39.483789"_x000D_
}, {_x000D_
  "id": "25",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Olin Hall and Olin Advanced Learning Center",_x000D_
  "description": "<p>Olin Hall</p>",_x000D_
  "longitude": "-87.324550",_x000D_
  "latitude": "39.482796"_x000D_
}, {_x000D_
  "id": "26",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Percopo Hall",_x000D_
  "description": "<p>Percopo Hall</p>",_x000D_
  "longitude": "-87.328182",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "27",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Public Safety Office",_x000D_
  "description": "<p>The Office of Public Safety</p>",_x000D_
  "longitude": "-87.320377",_x000D_
  "latitude": "39.48191"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Rotz Mechanical Engineering Lab",_x000D_
  "description": "<p>Rotz Lab</p>",_x000D_
  "longitude": "-87.323247",_x000D_
  "latitude": "39.483711"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Scharpenberg Hall",_x000D_
  "description": "<p>Scharpenberg Hall</p>",_x000D_
  "longitude": "-87.328139",_x000D_
  "latitude": "39.483582"_x000D_
}, {_x000D_
  "id": "29",_x000D_
  "category": "6",_x000D_
  "campus_location": "G2",_x000D_
  "title": "Sigma Nu Fraternity",_x000D_
  "description": "<p>The Sigma Nu house</p>",_x000D_
  "longitude": "-87.31999",_x000D_
  "latitude": "39.48374"_x000D_
}, {_x000D_
  "id": "30",_x000D_
  "category": "6",_x000D_
  "campus_location": "E4",_x000D_
  "title": "South Campus / Rose-Hulman Ventures",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330623",_x000D_
  "latitude": "39.417646"_x000D_
}, {_x000D_
  "id": "31",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Speed Hall",_x000D_
  "description": "<p>Speed Hall</p>",_x000D_
  "longitude": "-87.326632",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "32",_x000D_
  "category": "3",_x000D_
  "campus_location": "C1",_x000D_
  "title": "Sports and Recreation Center",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.3272",_x000D_
  "latitude": "39.484874"_x000D_
}, {_x000D_
  "id": "33",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Triangle Fraternity",_x000D_
  "description": "<p>Triangle fraternity</p>",_x000D_
  "longitude": "-87.32113",_x000D_
  "latitude": "39.483659"_x000D_
}, {_x000D_
  "id": "34",_x000D_
  "category": "6",_x000D_
  "campus_location": "B3",_x000D_
  "title": "White Chapel",_x000D_
  "description": "<p>The White Chapel</p>",_x000D_
  "longitude": "-87.329367",_x000D_
  "latitude": "39.482481"_x000D_
}, {_x000D_
  "id": "35",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Women's Fraternity Housing",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320753",_x000D_
  "latitude": "39.482401"_x000D_
}, {_x000D_
  "id": "36",_x000D_
  "category": "3",_x000D_
  "campus_location": "E1",_x000D_
  "title": "Intramural Fields",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.321267",_x000D_
  "latitude": "39.485934"_x000D_
}, {_x000D_
  "id": "37",_x000D_
  "category": "3",_x000D_
  "campus_location": "A3",_x000D_
  "title": "James Rendel Soccer Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.332135",_x000D_
  "latitude": "39.480933"_x000D_
}, {_x000D_
  "id": "38",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Art Nehf Field",_x000D_
  "description": "<p>Art Nehf Field</p>",_x000D_
  "longitude": "-87.330923",_x000D_
  "latitude": "39.48022"_x000D_
}, {_x000D_
  "id": "39",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Women's Softball Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.329904",_x000D_
  "latitude": "39.480278"_x000D_
}, {_x000D_
  "id": "40",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Joy Hulbert Tennis Courts",_x000D_
  "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
  "longitude": "-87.323767",_x000D_
  "latitude": "39.485595"_x000D_
}, {_x000D_
  "id": "41",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Speed Lake",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328134",_x000D_
  "latitude": "39.482779"_x000D_
}, {_x000D_
  "id": "42",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Recycling Center",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320098",_x000D_
  "latitude": "39.484593"_x000D_
}, {_x000D_
  "id": "43",_x000D_
  "category": "1",_x000D_
  "campus_location": "F3",_x000D_
  "title": "Army ROTC",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321342",_x000D_
  "latitude": "39.481992"_x000D_
}, {_x000D_
  "id": "44",_x000D_
  "category": "2",_x000D_
  "campus_location": "  ",_x000D_
  "title": "Self Made Man",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326272",_x000D_
  "latitude": "39.484481"_x000D_
}, {_x000D_
  "id": "P1",_x000D_
  "category": "4",_x000D_
  "title": "Percopo Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328756",_x000D_
  "latitude": "39.481587"_x000D_
}, {_x000D_
  "id": "P2",_x000D_
  "category": "4",_x000D_
  "title": "Speed Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.327361",_x000D_
  "latitude": "39.481694"_x000D_
}, {_x000D_
  "id": "P3",_x000D_
  "category": "4",_x000D_
  "title": "Main Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326245",_x000D_
  "latitude": "39.481446"_x000D_
}, {_x000D_
  "id": "P4",_x000D_
  "category": "4",_x000D_
  "title": "Lakeside Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.330848",_x000D_
  "latitude": "39.483284"_x000D_
}, {_x000D_
  "id": "P5",_x000D_
  "category": "4",_x000D_
  "title": "Hatfield Hall Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321417",_x000D_
  "latitude": "39.482398"_x000D_
}, {_x000D_
  "id": "P6",_x000D_
  "category": "4",_x000D_
  "title": "Women's Fraternity Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320977",_x000D_
  "latitude": "39.482315"_x000D_
}, {_x000D_
  "id": "P7",_x000D_
  "category": "4",_x000D_
  "title": "Myers and Facilities Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.322243",_x000D_
  "latitude": "39.48417"_x000D_
}, {_x000D_
  "id": "P8",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323241",_x000D_
  "latitude": "39.484758"_x000D_
}, {_x000D_
  "id": "P9",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323617",_x000D_
  "latitude": "39.484311"_x000D_
}, {_x000D_
  "id": "P10",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.484584"_x000D_
}, {_x000D_
  "id": "P11",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.484145"_x000D_
}, {_x000D_
  "id": "P12",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.329035",_x000D_
  "latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
  var marker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
    title: locations[i].title,_x000D_
    map: map_x000D_
  });_x000D_
  gmarkers.push(marker);_x000D_
  google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
    return function() {_x000D_
      if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
        infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
          '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
          '<hr class="grey" />' +_x000D_
          hasImage(locations[i]) +_x000D_
          locations[i].description) + '</div>';_x000D_
        infowindow.open(map, marker);_x000D_
      }_x000D_
    }_x000D_
  })(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
  for (i = 0; i < gmarkers.length; i++) {_x000D_
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
    else gmarkers[i].setMap(map);_x000D_
  }_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
  return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
_x000D_
_x000D_

Visual Studio Code pylint: Unable to import 'protorpc'

I got the same error on my vscode where I had a library installed and the code working when running from the terminal, but for some reason, the vscode pylint was not able to pick the installed package returning the infamous error:

Unable to import 'someLibrary.someModule' pylint(import-error)

The problem might arise due to the multiple Python installations. Basically you have installed a library/package on one, and vscode pylint is installed and running from another installation. For example, on macOS and many Linux distros, there are by default Python2 installed and when you install Python3 this might cause confusion. Also on windows the Chocolatey package manager might cause some mess and you end up with multiple Python installations. To figure it out if you are on a *nix machine (i.e., macOS, GNU/Linux, BSD...), use the which command, and if you are on Windows, use the where command to find the installed Python interpreters. For example, on *nix machines:

which python3

and on Windows

where python

then you may want to uninstall the ones you don't want. and the one you want to use check if the package causing above issue is installed by

python -c "import someLibrary"

if you get an error then you should install it by for example pip:

pip install someLibrary

then on vscode press ??P if you are on a mac and CtrlShiftP on other operating systems. Then type-select the >python: Select Interpreter option and select the one you know have the library installed. At this moment vscode might asks you to install pyling again, which you just go on with.

Keep background image fixed during scroll using css

background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}

How to request Location Permission at runtime

After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: https://github.com/LikeTheSalad/aaper like so:

@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
    // Your code that needs the location permission granted.
}

Disclaimer, I'm the creator of Aaper.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

How to get the full path of running process?

 using System.Diagnostics;
 var process = Process.GetCurrentProcess(); // Or whatever method you are using
 string fullPath = process.MainModule.FileName;
 //fullPath has the path to exe.

There is one catch with this API, if you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties ? Build ? Platform Target ? x64).

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

How can I get the ID of an element using jQuery?

Since the id is an attribute, you can get it by using the attr method.

How would I find the second largest salary from the employee table?

Try something like:

SELECT TOP 1 compensation FROM (
  SELECT TOP 2 compensation FROM employees
  ORDER BY compensation DESC
) AS em ORDER BY compensation ASC

Essentially:

  • Find the top 2 salaries in descending order.
  • Of those 2, find the top salary in ascending order.
  • The selected value is the second-highest salary.

If the salaries aren't distinct, you can use SELECT DISTINCT TOP ... instead.

Unable to add window -- token null is not valid; is your activity running?

This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout and use below code

Java:

 findViewById(R.id.main_layout).post(new Runnable() {
   public void run() {
       popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
   }
});

Kotlin:

 main_layout.post {
      popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)
    }

Credit to @kordzik

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

How to get today's Date?

Date today = new Date();
today.setHours(0); //same for minutes and seconds

Since the methods are deprecated, you can do this with Calendar:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds

And if you need a Date object in the end, simply call today.getTime()

How to get and set the current web page scroll position?

The currently accepted answer is incorrect - document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

To get the current position, you want:

document.documentElement.scrollTop || document.body.scrollTop

You can set the current position to 1000px down the page like so:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

Or, using jQuery (animate it while you're at it!):

$("html, body").animate({ scrollTop: "1000px" });

A JOIN With Additional Conditions Using Query Builder or Eloquent

I am using laravel5.2 and we can add joins with different options, you can modify as per your requirement.

Option 1:    
    DB::table('users')
            ->join('contacts', function ($join) {
                $join->on('users.id', '=', 'contacts.user_id')->orOn(...);//you add more joins here
            })// and you add more joins here
        ->get();

Option 2:
    $users = DB::table('users')
        ->join('contacts', 'users.id', '=', 'contacts.user_id')
        ->join('orders', 'users.id', '=', 'orders.user_id')// you may add more joins
        ->select('users.*', 'contacts.phone', 'orders.price')
        ->get();

option 3:
    $users = DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->leftJoin('...', '...', '...', '...')// you may add more joins
        ->get();

How to get a complete list of ticker symbols from Yahoo Finance?

There is a nice C# wrapper for the Yahoo.Finance API at http://code.google.com/p/yahoo-finance-managed/ that will get you there. Unfortunately there is no direct way to download the ticker list but the following creates the list by iterating through the alphabetical groups:

        AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
        dl1.Settings.TopIndex = null;
        Response<AlphabeticIDIndexResult> resp1 = dl1.Download();

        writeStream.WriteLine("Id|Isin|Name|Exchange|Type|Industry");

        foreach (var alphabeticalIndex in resp1.Result.Items)
        {
            AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex) alphabeticalIndex;
            dl1.Settings.TopIndex = topIndex;
            Response<AlphabeticIDIndexResult> resp2 = dl1.Download();

            foreach (var index in resp2.Result.Items)
            {
                IDSearchDownload dl2 = new IDSearchDownload();
                Response<IDSearchResult> resp3 = dl2.Download(index);


                int i = 0;
                foreach (var item in resp3.Result.Items)
                {
                    writeStream.WriteLine(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
                }

            }
        }

It gave me a list of about 75,000 securities in about 4 mins.

How do I change the android actionbar title and icon

You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this

getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Counter in foreach loop in C#

Use for instead of foreach. foreach doesn't expose its inner workings, it enumerates anything that is IEnumerable (which doesn't have to have an index at all).

for (int i=0; i<arr.Length; i++)
{
    ...
}

Besides, if what you're trying to do is find the index of a particular item in the list, you don't have to iterate it at all by yourself. Use Array.IndexOf(item) instead.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

If you're OK with using a library that writes the SQL for you, then you can use Upsert (currently Ruby and Python only):

Pet.upsert({:name => 'Jerry'}, :breed => 'beagle')
Pet.upsert({:name => 'Jerry'}, :color => 'brown')

That works across MySQL, Postgres, and SQLite3.

It writes a stored procedure or user-defined function (UDF) in MySQL and Postgres. It uses INSERT OR REPLACE in SQLite3.

What is the SQL command to return the field names of a table?

You can use the provided system views to do this:

eg

select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'

alternatively, you can use the system proc sp_help

eg

sp_help '[table name]'

Is it possible to disable the network in iOS Simulator?

You can use Little Snitch to cut off network traffic to any individual process, including ones that run on the iOS simulator. That way you can keep your internet connection and disconnect your running app.

Disable submit button on form submit

The following worked for me:

var form_enabled = true;
$().ready(function(){
       // allow the user to submit the form only once each time the page loads
       $('#form_id').on('submit', function(){
               if (form_enabled) {
                       form_enabled = false;
                       return true;
               }

               return false;
        });
});

This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)

Can I use git diff on untracked files?

For my interactive day-to-day gitting (where I diff the working tree against the HEAD all the time, and would like to have untracked files included in the diff), add -N/--intent-to-add is unusable, because it breaks git stash.

So here's my git diff replacement. It's not a particularly clean solution, but since I really only use it interactively, I'm OK with a hack:

d() {
    if test "$#" = 0; then
        (
            git diff --color
            git ls-files --others --exclude-standard |
                while read -r i; do git diff --color -- /dev/null "$i"; done
        ) | `git config --get core.pager`
    else
        git diff "$@"
    fi
}

Typing just d will include untracked files in the diff (which is what I care about in my workflow), and d args... will behave like regular git diff.

Notes:

  • We're using the fact here that git diff is really just individual diffs concatenated, so it's not possible to tell the d output from a "real diff" -- except for the fact that all untracked files get sorted last.
  • The only problem with this function is that the output is colorized even when redirected; but I can't be bothered to add logic for that.
  • I couldn't find any way to get untracked files included by just assembling a slick argument list for git diff. If someone figures out how to do this, or if maybe a feature gets added to git at some point in the future, please leave a note here!

How do I set a program to launch at startup

I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:

IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();

IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + @"MyIconName.ico";
shortcut.Save();

How do you delete all text above a certain line

d1G = delete to top including current line (vi)

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also

// 24 = 192 bits
    private const int SaltByteSize = 24;
    private const int HashByteSize = 24;
    private const int HasingIterationsCount = 10101;


    public static string HashPassword(string password)
    {
        // http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing

        byte[] salt;
        byte[] buffer2;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
        {
            salt = bytes.Salt;
            buffer2 = bytes.GetBytes(HashByteSize);
        }
        byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
        Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
        Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
        return Convert.ToBase64String(dst);
    }

    public static bool VerifyHashedPassword(string hashedPassword, string password)
    {
        byte[] _passwordHashBytes;

        int _arrayLen = (SaltByteSize + HashByteSize) + 1;

        if (hashedPassword == null)
        {
            return false;
        }

        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] src = Convert.FromBase64String(hashedPassword);

        if ((src.Length != _arrayLen) || (src[0] != 0))
        {
            return false;
        }

        byte[] _currentSaltBytes = new byte[SaltByteSize];
        Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

        byte[] _currentHashBytes = new byte[HashByteSize];
        Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

        using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
        {
            _passwordHashBytes = bytes.GetBytes(SaltByteSize);
        }

        return AreHashesEqual(_currentHashBytes, _passwordHashBytes);

    }

    private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
    {
        int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
        var xor = firstHash.Length ^ secondHash.Length;
        for (int i = 0; i < _minHashLength; i++)
            xor |= firstHash[i] ^ secondHash[i];
        return 0 == xor;
    }

In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.

Convert array of indices to 1-hot encoded numpy array

Your array a defines the columns of the nonzero elements in the output array. You need to also define the rows and then use fancy indexing:

>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max()+1))
>>> b[np.arange(a.size),a] = 1
>>> b
array([[ 0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.]])

Trim last character from a string

Very easy and simple:

str = str.Remove( str.Length - 1 );

iOS download and save image inside app

As other people said, there are many cases in which you should download a picture in the background thread without blocking the user interface

In this cases my favorite solution is to use a convenient method with blocks, like this one: (credit -> iOS: How To Download Images Asynchronously (And Make Your UITableView Scroll Fast))

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

And call it like

NSURL *imageUrl = //...

[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
    //Here you can save the image permanently, update UI and do what you want...
}];

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

Custom pagination view in Laravel 5

A quick JS fix for Bootstrap 4 pagination in Laravel 5+

Simply place the below script within your page:

    <script>
            $('.pagination li').addClass('page-item');
            $('.pagination li a').addClass('page-link');
            $('.pagination span').addClass('page-link');

    </script>

Advantages: saves server CPU, needs no adjustments in your app.

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

Can't connect to docker from docker-compose

I solved the issue in Ubuntu 20.0.4 by

sudo chmod 666 /var/run/docker.sock

and then

sudo service docker start && docker-compose up -d

Ref.

How can I do string interpolation in JavaScript?

While templates are probably best for the case you describe, if you have or want your data and/or arguments in iterable/array form, you can use String.raw.

String.raw({
  raw: ["I'm ", " years old!"]
}, 3);

With the data as an array, one can use the spread operator:

const args = [3, 'yesterday'];
String.raw({
  raw: ["I'm ", " years old as of ", ""]
}, ...args);

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.