Programs & Examples On #Aubio

A tool designed for the extraction of annotations from audio signals. Its features include segmenting a sound file before each of its attacks, performing pitch detection, tapping the beat and producing midi streams from live audio.

How to delete specific characters from a string in Ruby?

Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"

Edit line thickness of CSS 'underline' attribute

Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.

_x000D_
_x000D_
<span style="font-size:1em;text-decoration:underline;">_x000D_
 <span style="font-size:1.5em;">_x000D_
   Text with big font size and thin underline_x000D_
 </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to read a line from the console in C?

This function should do what you want:

char* readLine( FILE* file )
 {
 char buffer[1024];
 char* result = 0;
 int length = 0;

 while( !feof(file) )
  {
  fgets( buffer, sizeof(buffer), file );
  int len = strlen(buffer);
  buffer[len] = 0;

  length += len;
  char* tmp = (char*)malloc(length+1);
  tmp[0] = 0;

  if( result )
   {
   strcpy( tmp, result );
   free( result );
   result = tmp;
   }

  strcat( result, buffer );

  if( strstr( buffer, "\n" ) break;
  }

 return result;
 }

char* line = readLine( stdin );
/* Use it */
free( line );

I hope this helps.

Entity Framework Core: A second operation started on this context before a previous operation completed

I got the same message. But it's not making any sense in my case. My issue is I used a "NotMapped" property by mistake. It probably only means an error of Linq syntax or model class in some cases. The error message seems misleading. The original meaning of this message is you can't call async on same dbcontext more than once in the same request.

[NotMapped]
public int PostId { get; set; }
public virtual Post Post { get; set; }

You can check this link for detail, https://www.softwareblogs.com/Posts/Details/5/error-a-second-operation-started-on-this-context-before-a-previous-operation-completed

Postgresql: password authentication failed for user "postgres"

Time flies!

On version 12, I have to use "password" instead of "ident" here:

local   all             postgres                                password

Connect without using the -h option.

How to set up tmux so that it starts up with specified windows opened?

Use tmuxinator - it allows you to have multiple sessions configured, and you can choose which one to launch at any given time. You can launch commands in particular windows or panes and give titles to windows. Here is an example use with developing Django applications.

Sample config file:

# ~/.tmuxinator/project_name.yml
# you can make as many tabs as you wish...

project_name: Tmuxinator
project_root: ~/code/rails_project
socket_name: foo # Not needed. Remove to use default socket
rvm: 1.9.2@rails_project
pre: sudo /etc/rc.d/mysqld start
tabs:
  - editor:
      layout: main-vertical
      panes:
        - vim
        - #empty, will just run plain bash
        - top
  - shell: git pull
  - database: rails db
  - server: rails s
  - logs: tail -f logs/development.log
  - console: rails c
  - capistrano:
  - server: ssh me@myhost

See the README at the above link for a full explanation.

Javascript array sort and unique

The fastest and simpleness way to do this task.

const N = Math.pow(8, 8)
let data = Array.from({length:  N}, () => Math.floor(Math.random() * N))
let newData = {}
let len = data.length

// the magic
while (len--) {
    newData[data[len]] = true
}

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

How do I tell if an object is a Promise?

If you are in an async method you can do this and avoid any ambiguity.

async myMethod(promiseOrNot){
  const theValue = await promiseOrNot()
}

If the function returns promise, it will await and return with the resolved value. If the function returns a value, it will be treated as resolved.

If the function does not return a promise today, but tomorrow returns one or is declared async, you will be future-proof.

What is the --save option for npm install?

You can also use -S, -D or -P which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:

-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long

This list of shortcuts can be obtained by running the following command:

$ npm help 7 config

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Had been over looking the issue having surfaced it. Believe this will be a good read for others who come down here with the same issue:

https://bugs.eclipse.org/bugs/show_bug.cgi?id=387064

Detecting superfluous #includes in C/C++?

This article explains a technique of #include removing by using the parsing of Doxygen. That's just a perl script, so it's quite easy to use.

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

What is the purpose of the "role" attribute in HTML?

Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How can I restart a Java application?

Windows

public void restartApp(){

    // This launches a new instance of application dirctly, 
    // remember to add some sleep to the start of the cmd file to make sure current instance is
    // completely terminated, otherwise 2 instances of the application can overlap causing strange
    // things:)

    new ProcessBuilder("cmd","/c start /min c:/path/to/script/that/launches/my/application.cmd ^& exit").start();
    System.exit(0);
}

/min to start script in minimized window

^& exit to close cmd window after finish

a sample cmd script could be

@echo off
rem add some sleep (e.g. 10 seconds) to allow the preceding application instance to release any open resources (like ports) and exit gracefully, otherwise the new instance could fail to start
sleep 10   
set path=C:\someFolder\application_lib\libs;%path%
java -jar application.jar

sleep 10 sleep for 10 seconds

Cannot use a leading ../ to exit above the top directory

I had such a problem and the answer, although frustrating to find, was solved by doing a search on the offending page for the ".." in the error message. I am using Visual Studio Express and the solution was changing "../../Images/" to "~/Images/" . Hopefully this will help someone.

"NOT IN" clause in LINQ to Entities

If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).

   var exceptionList = new List<string> { "exception1", "exception2" };

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Where(e => !exceptionList.Contains(e.Name));

If you're excluding based on another database query using Except might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)

   var exceptionList = myEntities.MyOtherEntity
                                 .Select(e => e.Name);

   var query = myEntities.MyEntity
                         .Select(e => e.Name)
                         .Except(exceptionList);

This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"

Javascript parse float is ignoring the decimals after my comma

As @JaredPar pointed out in his answer use parseFloat with replace

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

Just replacing the comma with a dot will fix, Unless it's a number over the thousands like 1.000.000,00 this way will give you the wrong digit. So you need to replace the comma remove the dots.

// Remove all dot's. Replace the comma.
var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.'));

By using two replaces you'll be able to deal with the data without receiving wrong digits in the output.

How to do a JUnit assert on a message in a logger

Using Jmockit (1.21) I was able to write this simple test. The test makes sure a specific ERROR message is called just once.

@Test
public void testErrorMessage() {
    final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( MyConfig.class );

    new Expectations(logger) {{
        //make sure this error is happens just once.
        logger.error( "Something went wrong..." );
        times = 1;
    }};

    new MyTestObject().runSomethingWrong( "aaa" ); //SUT that eventually cause the error in the log.    
}

Java ArrayList copy

Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:

ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);

This is actual copying of values and not just copying of reference.

Can I access a form in the controller?

This answer is a little late, but I stumbled upon a solution that makes everything a LOT easier.

You can actually assign the form name directly to your controller if you're using the controllerAs syntax and then reference it from your "this" variable. Here's how I did it in my code:

I configured the controller via ui-router (but you can do it however you want, even in the HTML directly with something like <div ng-controller="someController as myCtrl">) This is what it might look like in a ui-router configuration:

views: {
            "": {
                templateUrl: "someTemplate.html",
                controller: "someController",
                controllerAs: "myCtrl"
            }
       }

and then in the HTML, you just set the form name as the "controllerAs"."name" like so:

<ng-form name="myCtrl.someForm">
    <!-- example form code here -->
    <input name="firstName" ng-model="myCtrl.user.firstName" required>
</ng-form>

now inside your controller you can very simply do this:

angular
.module("something")
.controller("someController",
    [
       "$scope",
        function ($scope) {
            var vm = this;
            if(vm.someForm.$valid){
              // do something
            }
    }]);

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

get list of pandas dataframe columns based on data type

If after 6 years you still have the issue, this should solve it :)

cols = [c for c in df.columns if df[c].dtype in ['object', 'datetime64[ns]']]

How to provide shadow to Button

you can use this great library https://github.com/BluRe-CN/ComplexView and it is really easy to use

C# Return Different Types?

Let the method return a object from a common baseclass or interface.

public class TV:IMediaPlayer
{
   void Play(){};
}

public class Radio:IMediaPlayer
{
   void Play(){};
}

public interface IMediaPlayer
{
   void Play():
}

public class Test
{
  public void Main()
  {
     IMediaPlayer player = GetMediaPlayer();
     player.Play();
  }


  private IMediaPlayer GetMediaPlayer()
  {
     if(...)
        return new TV();
     else
        return new Radio();
  }
}

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

I couldn't get the "Attach source..." method to work either, and I tried many different ways. The Javadocs for JavaFX are installed in Program Files\Oracle\JavaFX 2.x SDK\docs. Another way to install the Javadocs is:

  1. Right click on the project, select Properties
  2. Select Libraries on the right side of the tab
  3. At the right top side of the tab, you may see "Default JavaFX Platform" or something similar. Click on the Manage Platforms button. (You can also install this default platform from here if you haven't got this already).
  4. In the Java Platform Manager tab which appears, select "Default JavaFX Platform" on the left side, and then click on the JavaFX tab on the right side of the window.
  5. One of the entry fields is labeled "JavaFX Javadoc". Click the "Browse" button next to this field and browse to the installed docs file mentioned above.

Hope this helps some people who were as puzzled as I was.

Python dictionary : TypeError: unhashable type: 'list'

It works fine : http://codepad.org/5KgO0b1G, your aSourceDictionary variable may have other datatype than dict

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
        aTargetDictionary[aKey] = []
        aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary

How to debug when Kubernetes nodes are in 'Not Ready' state

First, describe nodes and see if it reports anything:

$ kubectl describe nodes

Look for conditions, capacity and allocatable:

Conditions:
  Type              Status
  ----              ------
  OutOfDisk         False
  MemoryPressure    False
  DiskPressure      False
  Ready             True
Capacity:
 cpu:       2
 memory:    2052588Ki
 pods:      110
Allocatable:
 cpu:       2
 memory:    1950188Ki
 pods:      110

If everything is alright here, SSH into the node and observe kubelet logs to see if it reports anything. Like certificate erros, authentication errors etc.

If kubelet is running as a systemd service, you can use

$ journalctl -u kubelet

Python Sets vs Lists

Lists are slightly faster than sets when you just want to iterate over the values.

Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.

It turns out tuples perform in almost exactly the same way as lists, except for their immutability.

Iterating

>>> def iter_test(iterable):
...     for i in iterable:
...         pass
...
>>> from timeit import timeit
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = set(range(10000))",
...     number=100000)
12.666952133178711
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = list(range(10000))",
...     number=100000)
9.917098999023438
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = tuple(range(10000))",
...     number=100000)
9.865639209747314

Determine if an object is present

>>> def in_test(iterable):
...     for i in range(1000):
...         if i in iterable:
...             pass
...
>>> from timeit import timeit
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = set(range(1000))",
...     number=10000)
0.5591847896575928
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = list(range(1000))",
...     number=10000)
50.18339991569519
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = tuple(range(1000))",
...     number=10000)
51.597304821014404

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

How to make a <svg> element expand or contract to its parent container?

Suppose I have an SVG which looks like this: pic1

And I want to put it in a div and make it fill the div responsively. My way of doing it is as follows:

First I open the SVG file in an application like inkscape. In File->Document Properties I set the width of the document to 800px and and the height to 600px (you can choose other sizes). Then I fit the SVG into this document.

pic2

Then I save this file as a new SVG file and get the path data from this file. Now in HTML the code that does the magic is as follows:

<div id="containerId">    
    <svg
    id="svgId" 
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    x="0"
    y="0"
    width="100%"
    height="100%"
    viewBox="0 0 800 600"
    preserveAspectRatio="none">
       <path d="m0 0v600h800v-600h-75.07031l-431 597.9707-292.445315-223.99609 269.548825-373.97461h-271.0332z" fill="#f00"/>
    </svg>
</div>

Note that width and height of SVG are both set to 100%, since we want it to fill the container vertically and horizontally ,but width and height of the viewBox are the same as the width and height of the document in inkscape which is 800px X 600px. The next thing you need to do is set the preserveAspectRatio to "none". If you need to have more information on this attribute here's a good link. And that's all there is to it.

One more thing is that this code works on almost all the major browsers even the old ones but on some versions of android and ios you need to use some javascrip/jQuery code to keep it consistent. I use the following in document ready and resize functions:

$('#svgId').css({
    'width': $('#containerId').width() + 'px',
    'height': $('#containerId').height() + 'px'
});

Hope it helps!

Encoding an image file with base64

The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.

encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))

Error during installing HAXM, VT-X not working

I ran into same issue, and problem was that virtualization was not enabled by default on my machine, you need to enter BIOS setting and enable it incase its disabled. Detailed Instructions available here on how to resolve this and enable virtualization on your machine.

https://maksbay.blogspot.in/2017/12/trying-to-set-up-android-emulators-you.html

Breaking to a new line with inline-block?

If you're OK with not using <p>s (only <div>s and <span>s), this solution might even allow you to align your inline-blocks center or right, if you want to (or just keep them left, the way you originally asked for). While the solution might still work with <p>s, I don't think the resulting HTML code would be quite correct, but it's up to you anyways.

The trick is to wrap each one of your <span>s with a corresponding <div>. This way we're taking advantage of the line break caused by the <div>'s display: block (default), while still keeping the visual green box tight to the limits of the text (with your display: inline-block declaration).

_x000D_
_x000D_
.text span {_x000D_
   background:rgba(165, 220, 79, 0.8);_x000D_
   display:inline-block;_x000D_
   padding:7px 10px;_x000D_
   color:white;_x000D_
}_x000D_
.large {  font-size:80px }
_x000D_
<div class="text">_x000D_
  <div><span class="medium">We</span></div>_x000D_
  <div><span class="large">build</span></div>_x000D_
  <div><span class="medium">the</span></div>_x000D_
  <div><span class="large">Internet</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

Dynamically creating keys in a JavaScript associative array

I think it is better if you just created it like this:

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

For more info, take a look at this:

JavaScript Data Structures - Associative Array

MatPlotLib: Multiple datasets on the same scatter plot

You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:

http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

How do I deal with certificates using cURL while trying to access an HTTPS url?

If anyone is still having trouble, try this, it worked for me. Delete the files in your /etc/ssl/certs/ directory then reinstall ca-certificates:

sudo apt install ca-certificates --reinstall

Did this when I tried installing Linuxbrew.

How do you create a toggle button?

The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('a#button').click(function() {_x000D_
    $(this).toggleClass("down");_x000D_
  });_x000D_
});
_x000D_
a {_x000D_
  background: #ccc;_x000D_
  cursor: pointer;_x000D_
  border-top: solid 2px #eaeaea;_x000D_
  border-left: solid 2px #eaeaea;_x000D_
  border-bottom: solid 2px #777;_x000D_
  border-right: solid 2px #777;_x000D_
  padding: 5px 5px;_x000D_
}_x000D_
_x000D_
a.down {_x000D_
  background: #bbb;_x000D_
  border-top: solid 2px #777;_x000D_
  border-left: solid 2px #777;_x000D_
  border-bottom: solid 2px #eaeaea;_x000D_
  border-right: solid 2px #eaeaea;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a id="button" title="button">Press Me</a>
_x000D_
_x000D_
_x000D_

Obviously, you can add background images that represent button up and button down, and make the background color transparent.

AngularJS For Loop with Numbers & Ranges

This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors). The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:

$scope.rangeCreator = function (minVal, maxVal) {
    var arr = [];
   for (var i = minVal; i <= maxVal; i++) {
      arr.push(i);
   }
   return arr;
};


<div class="col-sm-1">
    <select ng-model="monthDays">
        <option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
    </select>
</div>

git: Switch branch and ignore any changes without committing

If you want to discard the changes,

git checkout -- <file>
git checkout branch

If you want to keep the changes,

git stash save
git checkout branch
git stash pop

Working with INTERVAL and CURDATE in MySQL

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

Java Error opening registry key

I would have tagged this as a comment but cant (dont have the rep) just wanted to thank Tilman. I was trying to get PDFsam (PDF Split and Merge) to work to no avail.

At launch it would produce an error stating that it could not find JRE 1.6.0. I Have both 32 and 64 bit versions and they check out fine at the java website in their respective browsers.

Tried uninstalling/reinstalling and rebooting repeatedly as well as using JavaRa. No such luck, still no go.

I looked in the registry after reading this post and there was no ...\SOFTWARE\JavaSoft\ key so I added each with their respective string values pointing to my x86 version (PDFsam is a 32bit program). This got past the first problem but an error popped up about amd64 libraries suggesting the machine wanted to run the 64bit version. So I changed the paths to the 64bit JRE and PDFsam now works.

FYI - I got here by searching for Java registry keys after I was unable to launch javaw.exe from command prompt (even after adding the requisite paths to system path), making the aforementioned changes solved this as well.

jQuery returning "parsererror" for ajax request

You have specified the ajax call response dataType as:

'json'

where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.

The best approach that I would recommend is to change the dataType to:

'text'

and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:

$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    dataType: 'text',
    data: {viewID: $("#view").val()},
    success: function (data) {
        try {
            var output = JSON.parse(data);
            alert(output);
        } catch (e) {
            alert("Output is not valid JSON: " + data);
        }
    }, error: function (request, error) {
        alert("AJAX Call Error: " + error);
    }
});

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Find if a textbox is disabled or not using jquery

You can check if a element is disabled or not with this:

if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice 
}

Are arrays passed by value or passed by reference in Java?

Everything in Java is passed by value .

In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .

Take a look at this interesting article for further information ...

Redirect Windows cmd stdout and stderr to a single file

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

  • public : it is a access specifier that means it will be accessed by publically.
  • static : it is access modifier that means when the java program is load then it will create the space in memory automatically.
  • void : it is a return type i.e it does not return any value.
  • main() : it is a method or a function name.
  • string args[] : its a command line argument it is a collection of variables in the string format.

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

JCheckbox - ActionListener and ItemListener?

I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.

The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.

The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.

Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;

    public RadioButtonsAndCheckBoxesTest(){
        funny = "You are not ugly, you were just born... different";
        serious = "Recommend powdered soap in prison!";
        political = "Trump can eat a little Bernie, but will choke on his     Birdie";

        display = new JLabel(funny);
        Font defaultFont = new Font("Ariel",Font.PLAIN,20);
        display.setFont(defaultFont);

        bold = new JCheckBox("Bold",false);
        bold.setOpaque(false);
        italic = new JCheckBox("Italic",false);
        italic.setOpaque(false);

        //Color itemBackground =

        funnyQuote = new JRadioButton("Funny",true);
        funnyQuote.setOpaque(false);
        seriousQuote = new JRadioButton("Serious");
        seriousQuote.setOpaque(false);
        politicalQuote = new JRadioButton("Political");
        politicalQuote.setOpaque(false);

        quotes = new ButtonGroup();
        quotes.add(funnyQuote);
        quotes.add(seriousQuote);
        quotes.add(politicalQuote);

        JPanel primary = new JPanel();
        primary.setPreferredSize(new Dimension(550, 100));

        Dimension standard = new Dimension(500, 30);

        JPanel radioButtonsPanel = new JPanel();
        radioButtonsPanel.setPreferredSize(standard);
        radioButtonsPanel.setBackground(Color.green);
        radioButtonsPanel.add(funnyQuote);
        radioButtonsPanel.add(seriousQuote);
        radioButtonsPanel.add(politicalQuote);

        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setPreferredSize(standard);
        checkBoxPanel.setBackground(Color.green);
        checkBoxPanel.add(bold);
        checkBoxPanel.add(italic);

        primary.add(display);
        primary.add(radioButtonsPanel);
        primary.add(checkBoxPanel);

        //Add Action Listener To test Radio Buttons
        funnyQuote.addActionListener(new ActionListen());
        seriousQuote.addActionListener(new ActionListen());
        politicalQuote.addActionListener(new ActionListen());

        //Add Item Listener to test Radio Buttons
        funnyQuote.addItemListener(new ItemListen());
        seriousQuote.addItemListener(new ItemListen());
        politicalQuote.addItemListener(new ItemListen());

        //Add Action Listener to test Check Boxes
        bold.addActionListener(new ActionListen());
        italic.addActionListener(new ActionListen());

        //Add Item Listener to test Check Boxes
        bold.addItemListener(new ItemListen());
        italic.addItemListener(new ItemListen());

        //adds primary JPanel to this JPanel Object
        add(primary);   
    }

    private class ActionListen implements ActionListener{

        public void actionPerformed(ActionEvent e) {

         /*
         Different Get Methods from  ItemEvent 
         e.getWhen()
         e.getModifiers()
         e.getActionCommand()*/

            /*int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }*/
        }
    }
    private class ItemListen implements ItemListener {

        public void itemStateChanged(ItemEvent arg0) {

            /*
            Different Get Methods from ActionEvent
            arg0.getItemSelectable()
            arg0.getStateChange()
            arg0.getItem()*/


            int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }

        }

    }
}

Can't install any packages in Node.js using "npm install"

Npm repository is currently down. See issue #2694 on npm github

EDIT:
To use a mirror in the meanwhile:

 npm set registry http://ec2-46-137-149-160.eu-west-1.compute.amazonaws.com

you can reset this later with:

 npm set registry https://registry.npmjs.org/

source

Validation to check if password and confirm password are same is not working

Step 1 :

Create ts : app/_helpers/must-match.validator.ts

import { FormGroup } from '@angular/forms';

export function MustMatch(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) { 
            return;
        } 
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
        } else {
            matchingControl.setErrors(null);
        }
    }
}

Step 2 :

Use in your component.ts

import { MustMatch } from '../_helpers/must-match.validator'; 

ngOnInit() {
    this.loginForm = this.formbuilder.group({
      Password: ['', [Validators.required, Validators.minLength(6)]], 
      ConfirmPassword: ['', [Validators.required]],
    }, {
      validator: MustMatch('Password', 'ConfirmPassword')
    });
  } 

Step 3 :

Use In View/Html

<input type="password" formControlName="Password" class="form-control" autofocus>
                <div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
                    <div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div> 
                    <div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
                </div> 


 <input type="password" formControlName="ConfirmPassword" class="form-control" >
                <div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
                    <div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div> 
                    <div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
                </div> 

Pass Multiple Parameters to jQuery ajax call

I successfully passed multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I had the same problem, but while using a library project. The issue has been solved in r17: Instead of using the package's namespace:

xmlns:app="http://schemas.android.com/apk/res/hu.droidium.exercises"

One has to use a dummy namespace:

xmlns:app="http://schemas.android.com/apk/res-auto"

This will fix the problem of the attributes not being accessible from the referencing project.

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Find (and kill) process locking port 3000 on Mac

In your .bash_profile, create a shortcut for terminate the 3000 process:

terminate(){
  lsof -P | grep ':3000' | awk '{print $2}' | xargs kill -9 
}

Then, call $terminate if it's blocked.

CSS center display inline block?

Just use:

line-height:50px

Replace "50px" with the same height as your div.

How to use filesaver.js

It works in my react project:

import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
    FileSaver.saveAs(blob, "hello world.txt");
}

How to access the request body when POSTing using Node.js and Express?

Try this:

response.write(JSON.stringify(request.body));

That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.

Synchronous Requests in Node.js

Aredridels answer is relatively good (upvoted it), but I think it lacks the loop equivalent. This should help you:

Sync code equivalent:

while (condition) {
  var data = request(url);
  <math here>
}
return result;

Async code for serial execution:

function continueLoop() {
  if (!condition) return cb(result);
  request(url, function(err, res, body) {
    <math here>
    continueLoop()
  })
}
continueLoop()

Django 1.7 - makemigrations not detecting changes

Maybe that can help someone, I had the same problem.

I've already created two tables with the serializer class and the views. So when I wanted to updated, I had this error.

I followed this steps:

  1. I made .\manage.py makemigrations app
  2. I executed .\manage.py migrate
  3. I erased both tables of my models.py
  4. I erased all reference to my tables from serializer and view class.
  5. I executed step 1 and 2.
  6. I retrieved my changes just in the models.py
  7. I executed again step 5.
  8. I restored all my changes.

If you're working with Pycharm, local history is very helpfull.

Count the occurrences of DISTINCT values

What about something like this:

SELECT
  name,
  count(*) AS num
FROM
  your_table
GROUP BY
  name
ORDER BY
  count(*)
  DESC

You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.

Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.

Getting a directory name from a filename

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();

java howto ArrayList push, pop, shift, and unshift

Underscore-java library contains methods push(values), pop(), shift() and unshift(values).

Code example:

import com.github.underscore.U:

List<String> strings = Arrays.asList("one", "two", " three");
List<String> newStrings = U.push(strings, "four", "five");
// ["one", " two", "three", " four", "five"]
String newPopString = U.pop(strings).fst();
// " three"
String newShiftString = U.shift(strings).fst();
// "one"
List<String> newUnshiftStrings = U.unshift(strings, "four", "five");
// ["four", " five", "one", " two", "three"]

Random strings in Python

random_name = lambda length: ''.join(random.sample(string.letters, length))

length must be <= len(string.letters) = 53. result example

   >>> [random_name(x) for x in range(1,20)]
['V', 'Rq', 'YtL', 'AmUF', 'loFdS', 'eNpRFy', 'iWFGtDz', 'ZTNgCvLA', 'fjUDXJvMP', 'EBrPcYKUvZ', 'GmxPKCnbfih', 'nSiNmCRktdWZ', 'VWKSsGwlBeXUr', 'i
stIFGTUlZqnav', 'bqfwgBhyTJMUEzF', 'VLXlPiQnhptZyoHq', 'BXWATvwLCUcVesFfk', 'jLngHmTBtoOSsQlezV', 'JOUhklIwDBMFzrTCPub']
>>> 

Enjoy. ;)

Comparing two files in linux terminal

You can also use:

sdiff file1 file2

To display differences side by side within your terminal!

How do I close an Android alertdialog

Use Dialog instead of AlertDialog

AlertDialog doesn't have dismiss() but AlertDialog has some methods for button like setPositiveButton().

I recommend to use Dialog if you want customized dialog.

python dict to numpy structured array

You could use np.array(list(result.items()), dtype=dtype):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)

print(repr(array))

yields

array([(0.0, 1.1181753789488595), (1.0, 0.5566080288678394),
       (2.0, 0.4718269778030734), (3.0, 0.48716683119447185), (4.0, 1.0),
       (5.0, 0.1395076201641266), (6.0, 0.20941558441558442)], 
      dtype=[('id', '<f8'), ('data', '<f8')])

If you don't want to create the intermediate list of tuples, list(result.items()), then you could instead use np.fromiter:

In Python2:

array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))

In Python3:

array = np.fromiter(result.items(), dtype=dtype, count=len(result))

Why using the list [key,val] does not work:

By the way, your attempt,

numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)

was very close to working. If you change the list [key, val] to the tuple (key, val), then it would have worked. Of course,

numpy.array([(key,val) for (key,val) in result.iteritems()], dtype)

is the same thing as

numpy.array(result.items(), dtype)

in Python2, or

numpy.array(list(result.items()), dtype)

in Python3.


np.array treats lists differently than tuples: Robert Kern explains:

As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.

Since (0.0, 1.1181753789488595) is considered one of those atomic elements, it should be a tuple, not a list.

MySQL IF ELSEIF in select query

For your question :

SELECT id, 
   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.

Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

Git copy file preserving history

In my case, I made the change on my hard drive (cut/pasted about 200 folders/files from one path in my working copy to another path in my working copy), and used SourceTree (2.0.20.1) to stage both the detected changes (one add, one remove), and as long as I staged both the add and remove together, it automatically combined into a single change with a pink R icon (rename I assume).

I did notice that because I had such a large number of changes at once, SourceTree was a little slow detecting all the changes, so some of my staged files look like just adds (green plus) or just deletes (red minus), but I kept refreshing the file status and kept staging new changes as they eventually popped up, and after a few minutes, the whole list was perfect and ready for commit.

I verified that the history is present, as long as when I look for history, I check the "Follow renamed files" option.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

First do steps 4 and 5 then you can run your project. If you do not get the result (with steps 4 and 5) do the following steps

1- Try to downgrade your Node version (current version is 12.13.1)

  choco uninstall nodejs
  choco install nodejs --version 12.8

2- Add the path of npm module (C:\Users\your user name\AppData\Roaming\npm) to system variables instead of user variables

3- Install react native globally by using command

  npm install -g react-native-cli

4- Go to the root of your project directory and run the following command :

  react-native start

5- Open another terminal in the root of your project and run the following command :

   react-native run-android 

EDIT :

You are using Genymotion ? If yes, do the following step :

After above step if you get the following error ?

error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.

Open your genymotion and go to :

genymotion menu -> Settings -> ADB -> Then select use custom android sdk tools (click on browse to find sdk location)

Finally , run you project again ..

curl.h no such file or directory

Instead of downloading curl, down libcurl.

curl is just the application, libcurl is what you need for your C++ program

http://packages.ubuntu.com/quantal/curl

Load content with ajax in bootstrap modal

Easily done in Bootstrap 3 like so:

<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

Tkinter module not found on Ubuntu

What worked for me in Ubuntu was actually just:

sudo apt-get install python3-tk

For python 3.6:

sudo apt-get install python3.6-tk

I didn't read anywhere, I simply tried it, as onteria_'s method didn't seem to work for me.

Django URL Redirect

The other methods work fine, but you can also use the good old django.shortcut.redirect.

The code below was taken from this answer.

In Django 2.x:

from django.shortcuts import redirect
from django.urls import path, include

urlpatterns = [
    # this example uses named URL 'hola-home' from app named hola
    # for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
    path('', lambda request: redirect('hola/', permanent=True)),
    path('hola/', include('hola.urls')),
]

Commenting out code blocks in Atom

Edit your keymap.cson file and add

Windows

'.platform-win32 .editor':
  'ctrl-/': 'editor:toggle-line-comments'

Mac

'.platform-darwin .editor':
  'cmd-/': 'editor:toggle-line-comments'

Now just highlight the text you want to comment and hit the keybinding.

Better way to Format Currency Input editText?

In case someone is interested in a way of doing it using RxBinding and Kotlin:

var isEditing = false

RxTextView.textChanges(dollarValue)
            .filter { !isEditing }
            .filter { it.isNotBlank() }
            .map { it.toString().filter { it.isDigit() } }
            .map { BigDecimal(it).setScale(2, BigDecimal.ROUND_FLOOR).divide(100.toBigDecimal(), BigDecimal.ROUND_FLOOR) }
            .map { NumberFormat.getCurrencyInstance(Locale("pt", "BR")).format(it) }
            .subscribe {
                isEditing = true
                dollarValue.text = SpannableStringBuilder(it)
                dollarValue.setSelection(it.length)
                isEditing = false
            }

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

To open hyperlink in the same tab, use:

$(document).on('click', "a.classname", function() {
    var form = $("<form></form>");
    form.attr(
    {
        id     : "formid",
        action : $(this).attr("href"),
        method : "GET",
    });

    $("body").append(form);
    $("#formid").submit();
    $("#formid").remove();
    return false;
});

Switch between python 2.7 and python 3.5 on Mac OS X

OSX's Python binary (version 2) is located at /usr/bin/python

if you use which python it will tell you where the python command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin (which takes precedence, by default over /usr/bin). To fix, you can either run /usr/bin/python directly to use 2.x or find the errant redefinition (probably in /usr/local/bin or somewhere else in your PATH)

How do I get length of list of lists in Java?

Java 8

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

public class HelloWorld{

     public static void main(String []args){
            List<List<String>> stringListList = new ArrayList<>();
            stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
            stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
            stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));

            int count=stringListList.stream().mapToInt(i -> i.size()).sum();

            System.out.println("stringListList count: "+count);
     }
}

IE 8: background-size fix

As pointed by @RSK IE8 doesn't support background-size. To figure out a way to deal with this, I used some IE specific hacks as showed here:

//IE8.0 Hack!
@media \0screen {
    .brand {
        background-image: url("./images/logo1.png");
        margin-top: 8px;
    }

    .navbar .brand {
        margin-left: -2px;
        padding-bottom: 2px;
    }
}

//IE7.0 Hack!
*+html .brand {
    background-image: url("./images/logo1.png");
    margin-top: 8px;
}

*+html .navbar .brand {
    margin-left: -2px;
    padding-bottom: 2px;
}

Using this I was able to change my logo image to a ugly resided picture. But the final result is fine. I suggest u try something like this.

Deploying my application at the root in Tomcat

In my server I am using this and root autodeploy works just fine:

   <Host name="mysite" autoDeploy="true" appBase="webapps" unpackWARs="true" deployOnStartup="true">
        <Alias>www.mysite.com</Alias>
        <Valve className="org.apache.catalina.valves.RemoteIpValve" protocolHeader="X-Forwarded-Proto"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="mysite_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
        <Context path="/mysite" docBase="mysite" reloadable="true"/>
    </Host>

Can't stop rails server

One super easy way would be

gem install shutup

then go in the current folder of your rails project and run

shutup # this will kill the Rails process currently running

You can use the command 'shutup' every time you want

DICLAIMER: I am the creator of this gem

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

PHP find difference between two datetimes

Sorry my previous answer was wrong. If you are trying to take total elapsed time between time and timeout in the format Y-m-d H:i:s format, take diff between timeout and time in using DateTime object and format it as '%y-%m-%d %H:%i:%s'.

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

I created the following Method to create reusable One Liner:

public void oneMethodToCloseThemAll(ResultSet resultSet, Statement statement, Connection connection) {
    if (resultSet != null) {
        try {
            if (!resultSet.isClosed()) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            if (!statement.isClosed()) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if (connection != null) {
        try {
            if (!connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

I use this Code in a parent Class thats inherited to all my classes that send DB Queries. I can use the Oneliner on all Queries, even if i do not have a resultSet.The Method takes care of closing the ResultSet, Statement, Connection in the correct order. This is what my finally block looks like.

finally {
    oneMethodToCloseThemAll(resultSet, preStatement, sqlConnection);
}

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Java: Find .txt files in specified folder

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

How to display a pdf in a modal window?

you can use iframe within your modal form so when u open the iframe window it open inside your your modal form . i hope you are rendering to some pdf opener with some url , if u have the pdf contents simply add the contents in a div in the modal form .

Connection refused to MongoDB errno 111

This done the trick for me

sudo service mongod restart

Plot yerr/xerr as shaded region rather than error bars

This is basically the same answer provided by Evert, but extended to show-off some cool options of fill_between

enter image description here

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')


x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)    
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)



y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)  
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)



pl.show()

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Compiling PIL on Windows x64 is apparently a bit of a pain. (Well, compiling anything on Windows is a bit of a pain in my experience. But still.) As well as PIL itself you'll need to build many dependencies. See these notes from the mailing list too.

There's an unofficial precompiled binary for x64 linked from this message, but I haven't tried it myself. Might be worth a go if you don't mind the download being from one of those slightly dodgy file-upload sites. Other than that... well, you could always give up and instead the 32-bit Python binary instead.

Response to preflight request doesn't pass access control check

There are some caveats when it comes to CORS. First, it does not allow wildcards * but don't hold me on this one I've read it somewhere and I can't find the article now.

If you are making requests from a different domain you need to add the allow origin headers.

 Access-Control-Allow-Origin: www.other.com 

If you are making requests that affect server resources like POST/PUT/PATCH, and if the mime type is different than the following application/x-www-form-urlencoded, multipart/form-data, or text/plain the browser will automatically make a pre-flight OPTIONS request to check with the server if it would allow it.

So your API/server needs to handle these OPTIONS requests accordingly, you need to respond with the appropriate access control headers and the http response status code needs to be 200.

The headers should be something like this, adjust them for your needs:

   Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
   Access-Control-Allow-Headers: Content-Type
   Access-Control-Max-Age: 86400

The max-age header is important, in my case, it wouldn't work without it, I guess the browser needs the info for how long the "access rights" are valid.

In addition, if you are making e.g. a POST request with application/json mime from a different domain you also need to add the previously mentioned allow origin header, so it would look like this:

   Access-Control-Allow-Origin: www.other.com 
   Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
   Access-Control-Allow-Headers: Content-Type
   Access-Control-Max-Age: 86400

When the pre-flight succeeds and gets all the needed info your actual request will be made.

Generally speaking, whatever Access-Control headers are requested in the initial or pre-flight request, should be given in the response in order for it to work.

There is a good example in the MDN docs here on this link, and you should also check out this SO post

preferredStatusBarStyle isn't called

Note that when using the self.navigationController.navigationBar.barStyle = UIBarStyleBlack; solution

be sure to go to your plist and set "View controller-based status bar appearance" to YES. If its NO it will not work.

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Could fix this by adding

compile 'com.android.support:support-v4:18.0.0'

to the dependencies in the vertretungsplan build.gradle, compile and then remove this line and compile again.

now it works

How do I get the APK of an installed app without root access?

  1. check the list of installed apk's (following command also list the path where it is installed and package name). adb shell pm list packages -f
  2. use adb pull /package_path/package name /path_in_pc (package path and package name one can get from above command 1.)

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Create a folder and sub folder in Excel VBA

Sub MakeAllPath(ByVal PS$)
    Dim PP$
    If PS <> "" Then
        ' chop any end  name
        PP = Left(PS, InStrRev(PS, "\") - 1)
        ' if not there so build it
        If Dir(PP, vbDirectory) = "" Then
            MakeAllPath Left(PP, InStrRev(PS, "\") - 1)
            ' if not back to drive then  build on what is there
            If Right(PP, 1) <> ":" Then MkDir PP
        End If
    End If
End Sub


'Martins loop version above is better than MY recursive version
'so improve to below

Sub MakeAllDir(PathS$)            

  ' format "K:\firstfold\secf\fold3"

  If Dir(PathS) = vbNullString Then     

 ' else do not bother

   Dim LI&, MYPath$, BuildPath$, PathStrArray$()

   PathStrArray = Split(PathS, "\")

      BuildPath = PathStrArray(0) & "\"    '

      If Dir(BuildPath) = vbNullString Then 

' trap problem of no drive :\  path given

         If vbYes = MsgBox(PathStrArray(0) & "< not there for >" & PathS & " try to append to " & CurDir, vbYesNo) Then
            BuildPath = CurDir & "\"
         Else
            Exit Sub
         End If
      End If
      '
      ' loop through required folders
      '
      For LI = 1 To UBound(PathStrArray)
         BuildPath = BuildPath & PathStrArray(LI) & "\"
         If Dir(BuildPath, vbDirectory) = vbNullString Then MkDir BuildPath
      Next LI
   End If 

 ' was already there

End Sub

' use like
'MakeAllDir "K:\bil\joan\Johno"

'MakeAllDir "K:\bil\joan\Fredso"

'MakeAllDir "K:\bil\tom\wattom"

'MakeAllDir "K:\bil\herb\watherb"

'MakeAllDir "K:\bil\herb\Jim"

'MakeAllDir "bil\joan\wat" ' default drive

How do I tell Spring Boot which main class to use for the executable jar?

Add your start class in your pom:

<properties>
    <!-- The main class to start by executing java -jar -->
    <start-class>com.mycorp.starter.HelloWorldApplication</start-class>
</properties>

or

<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>             
        <configuration>    
            <mainClass>com.mycorp.starter.HelloWorldApplication</mainClass>
        </configuration>
    </plugin>
</plugins>
</build>

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Example: Communication between Activity and Service using Messaging

Message msg = Message.obtain(null, 2, 0, 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("names", names);
                    bundle.putString("captions",captions); 
                    msg.setData(bundle);

So you send it to the service. Afterward receive.

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

Add items to comboBox in WPF

Use this

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

How to get javax.comm API?

Use RXTX.

On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

Fixing a systemd service 203/EXEC failure (no such file or directory)

When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.

How to use LINQ to select object with minimum or maximum property value

I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.

var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));

Cannot ignore .idea/workspace.xml - keeps popping up

In the same dir where you see the file appear do:

  • rm .idea/workspace.xml
  • git rm -f .idea/workspace.xml (as suggested by chris vdp)
  • vi .gitignore
  • i (to edit), add .idea/workspace.xml in one of the lines, Esc, :wq

You should be good now

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

Use jQuery to hide a DIV when the user clicks outside of it

Toggle for regular and touch devices

I read some answers here a while back and created some code I use for div's that function as popup bubbles.

$('#openPopupBubble').click(function(){
    $('#popupBubble').toggle();

    if($('#popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$('#popupBubble').find('*').is(e.target)){
                $('#popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

You can also make this more abstract using classes and select the correct popup bubble based on the button that triggered the click event.

$('body').on('click', '.openPopupBubble', function(){
    $(this).next('.popupBubble').toggle();

    if($(this).next('.popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($(this).is(e.target) || $(this).find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$(this).next('.popupBubble').find('*').is(e.target)){
                $(this).next('.popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

Joining three tables using MySQL

Don't join like that. It's a really really bad practice!!! It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000 times. It had to fetch for 1 million times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It's up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join --> 100x100= 10000 times and suppose we get 5 matching result. And then we join the third table with the result --> 5x100 = 500. Total fetch = 10000+500 = 10200 times only. And thus, the performance went up!!!

Regular expression for first and last name

The following expression will work on any language supported by UTF-16 and will ensure that there's a minimum of two components to the name (i.e. first + last), but will also allow any number of middle names.

/^(\S+ )+\S+$/u

At the time of this writing it seems none of the other answers meet all of that criteria. Even ^\p{L}{2,}$, which is the closest, falls short because it will also match "invisible" characters, such as U+FEFF (Zero Width No-Break Space).

How do I export a project in the Android studio?

Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.

You don't need to harcode android:debuggable="false" in your application tag. Infact for me studio complaints -

Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)

It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.

Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.

enter image description here

Now you should see a prompt to select release build or debug build.

For production always select release build!

enter image description here

And you are done. Signed APK exported.

enter image description here

PS : Don't forget to increment your versionCode in manifest file before uploading to playstore :)

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

System.MissingMethodException: Method not found?

I got this exception while testing out some code a coworker had written. Here is a summary of the exception info.:

Method not found: "System.Threading.Tasks.Task1<Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry1<System_Canon>> Microsoft.EntityFrameworkCore.DbSet`1.AddAsync...

This was in Visual Studio 2019 in a class library targeting .NET Core 3.1. The fix was to use the Add method instead of AddAsync on the DbSet.

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

onChange and onSelect in DropDownList

Simply & Easy : JavaScript code :

function JoinedOrNot(){
    var cat = document.getElementById("mySelect");
    if(cat.value == "yes"){
        document.getElementById("mySelect1").disabled = false;
    }else{
        document.getElementById("mySelect1").disabled = true;
    }
}

just add in this line [onChange="JoinedOrNot()"] : <select id="mySelect" onchange="JoinedOrNot()">

it's work fine ;)

Best way to add Gradle support to IntelliJ Project

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done

Hide all elements with class using plain Javascript

There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.

1.forEach and querySelectorAll('.classname')

document.querySelectorAll('.classname').forEach(function(el) {
   el.style.display = 'none';
});

2.for...of with getElementsByClassName

for (let element of document.getElementsByClassName("classname")){
   element.style.display="none";
}

3.Array.protoype.forEach getElementsByClassName

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
    // Do something amazing below
    el.style.display = 'none';
});

4.[ ].forEach and getElementsByClassName

[].forEach.call(document.getElementsByClassName("classname"), function (el) {
    el.style.display = 'none';
});

i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.

Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.

Convert hex to binary

>>> bin( 0xABC123EFFF )

'0b1010101111000001001000111110111111111111'

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

If u want to Selected text clear then using to this code i will make by my self ;)

If e.KeyCode = Keys.Delete Then
    TextBox1.SelectedText = ""
End If

thats it

How to read file binary in C#?

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

Simplest way to detect a mobile device in PHP

Here is a source:

Code:

<?php

$useragent=$_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

header('Location: http://detectmobilebrowser.com/mobile');

?>

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @TimeinSecond INT
SET @TimeinSecond = 340 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2)  + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

How to replace ${} placeholders in a text file?

Create rendertemplate.sh:

#!/usr/bin/env bash

eval "echo \"$(cat $1)\""

And template.tmpl:

Hello, ${WORLD}
Goodbye, ${CHEESE}

Render the template:

$ export WORLD=Foo
$ CHEESE=Bar ./rendertemplate.sh template.tmpl 
Hello, Foo
Goodbye, Bar

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Python: Differentiating between row and column vectors

You can make the distinction explicit by adding another dimension to the array.

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14

Now force it to be a column vector:

>>> a.shape = (3,1)
>>> a
array([[1],
       [2],
       [3]])
>>> a.transpose()
array([[1, 2, 3]])
>>> a.dot(a.transpose())
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Another option is to use np.newaxis when you want to make the distinction:

>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[:, np.newaxis]
array([[1],
       [2],
       [3]])
>>> a[np.newaxis, :]
array([[1, 2, 3]])

Clearing a text field on button click

Something like this will add a button and let you use it to clear the values

<div>           
<input type="text" id="textfield1" size="5"/>         
</div>

<div>          
<input type="text" id="textfield2" size="5"/>           
</div>

<div>
    <input type="button" onclick="clearFields()" value="Clear">
</div>


<script type="text/javascript">
function clearFields() {
    document.getElementById("textfield1").value=""
    document.getElementById("textfield2").value=""
}
</script>

How to print variable addresses in C?

When you intend to print the memory address of any variable or a pointer, using %d won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878 is surely not a number, but an address.

What you should use is %p. e.g.,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}

Good luck!

Adding value labels on a matplotlib bar chart

Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:

# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height() / 2

    # Number of points between bar and label. Change to your liking.
    space = 5
    # Vertical alignment for positive values
    ha = 'left'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'right'

    # Use X value as label and format number with one decimal place
    label = "{:.1f}".format(x_value)

    # Create annotation
    plt.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='center',                # Vertically center label
        ha=ha)                      # Horizontally align label differently for
                                    # positive and negative values.

plt.savefig("image.png")

horizontal bar plot with annotations

Find a string between 2 known values

To get Single/Multiple values without regular expression

// For Single
var value = inputString.Split("<tag1>", '</tag1>')[1];

// For Multiple
var values = inputString.Split("<tag1>", '</tag1>').Where((_, index) => index % 2 != 0);

Moving all files from one directory to another using Python

def copy_myfile_dirOne_to_dirSec(src, dest, ext): 

    if not os.path.exists(dest):    # if dest dir is not there then we create here
        os.makedirs(dest);
        
    for item in os.listdir(src):
        if item.endswith(ext):
            s = os.path.join(src, item);
            fd = open(s, 'r');
            data = fd.read();
            fd.close();
            
            fname = str(item); #just taking file name to make this name file is destination dir     
            
            d = os.path.join(dest, fname);
            fd = open(d, 'w');
            fd.write(data);
            fd.close();
    
    print("Files are copyed successfully")

PHP7 : install ext-dom issue

For whom want to install ext-dom on php 7.1 and up run this command:

sudo apt install php-xml

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

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

Please try this code

new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df

I think that code will add a column called 'count it' which count of each group

Creating a button in Android Toolbar

I have added text in ToolBar :

menu_skip.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/text_skip"
        app:showAsAction="never" />
</menu>

MainActivity.java

@Override
boolean onCreateOptionsMenu(Menu menu) {
    inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_otp_skip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.menu_item_skip:
            Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }
    return true;
}

Good Free Alternative To MS Access

You may want to look into SQLite (http://sqlite.org/). All depends on your usage though. Concurrency for example is not its greatest virtue. But for example Firefox uses it to store settings etc..

ASP.NET Web Site or ASP.NET Web Application?

Web Site is what you deploy to an ASP.NET web server such as IIS. Just a bunch of files and folders. There’s nothing in a Web Site that ties you to Visual Studio (there’s no project file). Code-generation and compilation of web pages (such as .aspx, .ascx, .master) is done dynamically at runtime, and changes to these files are detected by the framework and automatically re-compiled. You can put code that you want to share between pages in the special App_Code folder, or you can pre-compile it and put the assembly in the Bin folder.

Web Application is a special Visual Studio project. The main difference with Web Sites is that when you build the project all the code files are compiled into a single assembly, which is placed in the bin directory. You don’t deploy code files to the web server. Instead of having a special folder for shared code files you can put them anywhere, just like you would do in class library. Because Web Applications contains files that are not meant to be deployed, such as project and code files, there’s a Publish command in Visual Studio to output a Web Site to a specified location.

App_Code vs Bin

Deploying shared code files is generally a bad idea, but that doesn’t mean you have to choose Web Application. You can have a Web Site that references a class library project that holds all the code for the Web Site. Web Applications is just a convenient way to do it.

CodeBehind

This topic is specific to .aspx and .ascx files. This topic is decreasingly relevant in new application frameworks such as ASP.NET MVC and ASP.NET Web Pages which do not use codebehind files.

By having all code files compiled into a single assembly, including codebehind files of .aspx pages and .ascx controls, in Web Applications you have to re-build for every little change, and you cannot make live changes. This can be a real pain during development, since you have to keep re-building to see the changes, while with Web Sites changes are detected by the runtime and pages/controls are automatically recompiled.

Having the runtime manage the codebehind assemblies is less work for you, since you don't need to worry about giving pages/controls unique names, or organizing them into different namespaces.

I’m not saying deploying code files is always a good idea (specially not in the case of shared code files), but codebehind files should only contain code that perform UI specific tasks, wire-up events handlers, etc. Your application should be layered so that important code always end up in the Bin folder. If that is the case then deploying codebehind files shouldn't be considered harmful.

Another limitation of Web Applications is that you can only use the language of the project. In Web Sites you can have some pages in C#, some in VB, etc. No need for special Visual Studio support. That’s the beauty of the build provider extensibility.

Also, in Web Applications you don't get error detection in pages/controls as the compiler only compiles your codebehind classes and not the markup code (in MVC you can fix this using the MvcBuildViews option), which is compiled at runtime.

Visual Studio

Because Web Applications are Visual Studio projects you get some features not available in Web Sites. For instance, you can use build events to perform a variety of tasks, e.g. minify and/or combine Javascript files.

Another nice feature introduced in Visual Studio 2010 is Web.config transformation. This is also not available in Web Sites. Now works with Web Sites in VS 2013.

Building a Web Application is faster than building a Web Site, specially for large sites. This is mainly because Web Applications do not compile the markup code. In MVC if you set MvcBuildViews to true then it compiles the markup code and you get error detection, which is very useful. The down side is that every time you build the solution it builds the complete site, which can be slow and inefficient, specially if you are not editing the site. l find myself turning MvcBuildViews on and off (which requires a project unload). On the other hand, with Web Sites you can choose if you want to build the site as part of the solution or not. If you choose not to, then building the solution is very fast, and you can always click on the Web Site node and select Build, if you’ve made changes.

In an MVC Web Application project you have extra commands and dialogs for common tasks, like ‘Add View’, ‘Go To View’, ‘Add Controller’, etc. These are not available in an MVC Web Site.

If you use IIS Express as the development server, in Web Sites you can add virtual directories. This option is not available in Web Applications.

NuGet Package Restore does not work on Web Sites, you have to manually install packages listed on packages.config Package Restore now works with Web Sites starting NuGet 2.7

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

javascript - match string against the array of regular expressions

Consider breaking this problem up into two pieces:

  1. filter out the items that match the given regular expression
  2. determine if that filtered list has 0 matches in it
const sampleStringData = ["frog", "pig", "tiger"];

const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));

if (matches.length === 0) {
  console.log("No matches");
}

app-release-unsigned.apk is not signed

What finally worked for me, and I have no idea why, is:

  • Went to LastPass (the service I use to keep all my passwords)
  • Select my password by putting the cursor on top of the password and double clicking
  • Once selected I press cmd C to copy
  • Went to Android study and cmd V to paste

Notice I did try to copy many times by selecting the password by clicking at the end of the password and selecting the password by moving the mouse.

It is strange but it only worked by double clicking on top of the password to copy it.

Also I did use the Open Module Settings > Signing... method explained by @NightFury on this post.

How to show google.com in an iframe?

Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

Minimum and maximum value of z-index?

It's the maximum value of a 32 bits integer: 2147483647

Also see the docs: https://www.w3.org/TR/CSS22/visuren.html#z-index (Negative numbers are allowed)

Make DateTimePicker work as TimePicker only in WinForms

You want to set its 'Format' property to be time and add a spin button control to it:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

navbar color in Twitter Bootstrap

If you havent got time to learn "less" or do it properly, here's a dirty hack...

Add this above where you render the bootstrap nav bar HTML - update the colours as required..

<style type="text/css">   

.navbar-inner {
    background-color: red;
    background-image: linear-gradient(to bottom, blue, green);
    background-repeat: repeat-x;
    border: 1px solid yellow;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.067);
    min-height: 40px;
    padding-left: 20px;
    padding-right: 20px;
}

.dropdown-menu {
    background-clip: padding-box;
    background-color: red;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 6px 6px 6px 6px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    display: none;
    float: left;
    left: 0;
    list-style: none outside none;
    margin: 2px 0 0;
    min-width: 160px;
    padding: 5px 0;
    position: absolute;
    top: 100%;
    z-index: 1000;
}

.btn-group.open .btn.dropdown-toggle {
  background-color: red;
}

.btn-group.open .btn.dropdown-toggle {
  background-color:lime;
}

.navbar .nav li.dropdown.open > .dropdown-toggle,
.navbar .nav li.dropdown.active > .dropdown-toggle,
.navbar .nav li.dropdown.open.active > .dropdown-toggle {
  color:white;
  background-color:Teal;
}

.navbar .nav > li > a {
    color: white;
    float: none;
    padding: 10px 15px;
    text-decoration: none;
    text-shadow: 0 0px 0 #ffffff;
}

.navbar .brand {
  display: block;
  float: left;
  padding: 10px 20px 10px;
  margin-left: -20px;
  font-size: 20px;
  font-weight: 200;
  color: white;
  text-shadow: 0 0px 0 #ffffff;
}

.navbar .nav > li > a:focus,
.navbar .nav > li > a:hover {
  color: white;
  text-decoration: none;
  background-color: transparent;
}

.navbar-text {
  margin-bottom: 0;
  line-height: 40px;
  color: white;
}

.dropdown-menu li > a {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 20px;
  color: white;
  white-space: nowrap;
}

.navbar-link {
  color: white;
}

.navbar-link:hover {
  color: white;
}

</style>

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

How to handle windows file upload using Selenium WebDriver?

There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.

Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.

    StringSelection s = new StringSelection("Path to the file");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
    Robot robot = new Robot();
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
    robot.keyPress(java.awt.event.KeyEvent.VK_V);
    robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
    Thread.sleep(3000);
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

CR LF notepad++ removal

enter image description hereGoto View -> Show Symbol Select as per screen-shot, you will get correct

NSString with \n or line break

In case \n or \r is not working and if you are working with uiwebview and trying to load html using < br > tag to insert new line. Don't just use < br > tag in NSString stringWithFormat.

Instead use the same by appending. i.e by using stringByAppendingString

 yourNSString = [yourNSString stringByAppendingString:@"<br>"];

Javascript .querySelector find <div> by innerTEXT

Since you have asked it in javascript so you can have something like this

function contains(selector, text) {
  var elements = document.querySelectorAll(selector);
  return Array.prototype.filter.call(elements, function(element){
    return RegExp(text).test(element.textContent);
  });
}

And then call it like this

contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

Image inside div has extra space below the image

You can use several methods for this issue like

  1. Using line-height

    #wrapper {  line-height: 0px;  }
    
  2. Using display: flex

    #wrapper {  display: flex;         }
    #wrapper {  display: inline-flex;  }
    
  3. Using display: block, table, flex and inherit

    #wrapper img {  display: block;    }
    #wrapper img {  display: table;    }
    #wrapper img {  display: flex;     }
    #wrapper img {  display: inherit;  }
    

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

TL;DR

In several occasions, I've solved this kind of errors by just closing my terminal session and opening a new one before retrying the failing command.

Long explanation

In some SOs (such as MacOS) there is already a pre-installed, system-wide version of ruby. If you are using a version manager, such as rbenv or asdf, they work by playing with the environment of your current session so that the relevant commands point to the binaries installed by the version manager.

When installing a new binary, the version manager installs it in a special location, usually somewhere under the user's home directory. It then configures everything in your PATH so that you get the freshly installed binaries when you issue a command, instead of the ones that came with your system. However, if you don't restart the session (there are other ways of getting your environment updated, but that's the easiest one) you don't get the new configuration and you will be using the original installation.

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

jQuery call function after load

$(window).bind("load", function() {
  // write your code here
});

SimpleDateFormat parsing date with 'Z' literal

With regards to JSR-310 another project of interest might be threetenbp.

JSR-310 provides a new date and time library for Java SE 8. This project is the backport to Java SE 6 and 7.

In case you are working on an Android project you might want to checkout the ThreeTenABP library.

compile "com.jakewharton.threetenabp:threetenabp:${version}"

JSR-310 was included in Java 8 as the java.time.* package. It is a full replacement for the ailing Date and Calendar APIs in both Java and Android. JSR-310 was backported to Java 6 by its creator, Stephen Colebourne, from which this library is adapted.

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

How to get the current date without the time?

DateTime.Now.ToString("dd/MM/yyyy");

How do I clone into a non-empty directory?

I got the same issues when trying to clone to c/code

But this folder contains a whole bunch of projects.

I created a new folder in c/code/newproject and mapped my clone to this folder.

git for desktop then asked of my user and then cloned fine.

Change R default library path using .libPaths in Rprofile.site fails to work

If you do not have admin-rights, it can also be helpful to open the Rprofile.site-file located in \R-3.1.0\etc and add:

.First <- function(){
  .libPaths("your path here")
}

This evaluates the .libPath() command directly at start

PHP function to make slug (URL string)

I didn't know which one to use so I made a quick bench on phptester.net

<?php

// First test
// https://stackoverflow.com/a/42740874/10232729
function slugify(STRING $string, STRING $separator = '-'){
    
    $accents_regex = '~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i';
    $special_cases = [ '&' => 'and', "'" => ''];
    $string = mb_strtolower( trim( $string ), 'UTF-8' );
    $string = str_replace( array_keys($special_cases), array_values( $special_cases), $string );
    $string = preg_replace( $accents_regex, '$1', htmlentities( $string, ENT_QUOTES, 'UTF-8' ) );
    $string = preg_replace('/[^a-z0-9]/u', $separator, $string);
    
    return preg_replace('/['.$separator.']+/u', $separator, $string);
}

// Second test
// https://stackoverflow.com/a/13331948/10232729
function slug(STRING $string, STRING $separator = '-'){
    
    $string = transliterator_transliterate('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();', $string);
        
    return str_replace(' ', $separator, $string);;
}

// Third test - My choice
// https://stackoverflow.com/a/38066136/10232729
function slugbis($text){

    $replace = [
        '<' => '', '>' => '', '-' => ' ', '&' => '',
        '"' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä'=> 'Ae',
        'Ä' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
        'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
        'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
        'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
        'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
        'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
        'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
        'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
        'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
        'Ö' => 'Oe', 'Ö' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
        'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
        'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
        '?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
        'Ü' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
        'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
        'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
        'ä' => 'ae', 'ä' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
        'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
        'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
        'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
        'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
        'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
        'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
        'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
        '?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
        '?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
        'ö' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
        'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
        'û' => 'u', 'ü' => 'ue', 'u' => 'u', 'ü' => 'ue', 'u' => 'u', 'u' => 'u',
        'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
        'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
        '?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
        '?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
        '?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
        '?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
        '?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
        '?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
        '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
        '?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
        '?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
        '?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
        '?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
        '?' => 'yu', '?' => 'ya'
    ];

    // make a human readable string
    $text = strtr($text, $replace);

    // replace non letter or digits by -
    $text = preg_replace('~[^\pL\d.]+~u', '-', $text);

    // trim
    $text = trim($text, '-');

    // remove unwanted characters
    $text = preg_replace('~[^-\w.]+~', '', $text);

    return strtolower($text);
}

// Fourth test
// https://stackoverflow.com/a/2955521/10232729
function slugagain($string){
    
    $table = [
        'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'd'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
        'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'R'=>'R', 'r'=>'r', ' '=>'-'
    ];

    return strtr($string, $table);
}

// Fifth test
// https://stackoverflow.com/a/27396804/10232729
function slugifybis($url){
    $url = trim($url);

    $url = str_replace(' ', '-', $url);
    $url = str_replace('/', '-slash-', $url);
    
    return rawurlencode($url);
}

// Sixth and last test
// https://stackoverflow.com/a/39442034/10232729
setlocale( LC_ALL, "en_US.UTF8" );  
function slugifyagain($string){
    
    $string = iconv('utf-8', 'us-ascii//translit//ignore', $string); // transliterate
    $string = str_replace("'", '', $string);
    $string = preg_replace('~[^\pL\d]+~u', '-', $string); // replace non letter or non digits by "-"
    $string = preg_replace('~[^-\w]+~', '', $string); // remove unwanted characters
    $string = preg_replace('~-+~', '-', $string); // remove duplicate "-"
    $string = trim($string, '-'); // trim "-"
    $string = trim($string); // trim
    $string = mb_strtolower($string, 'utf-8'); // lowercase
    
    return urlencode($string); // safe;
};

$string = $newString = "¿ Àñdréß l'affreux garçon & nøël en forêt !";

$max = 10000;

echo '<pre>';
echo 'Beginning :';
echo '<br />';
echo '<br />';    
echo '> Slugging '.$max.' iterations of following :';
echo '<br />';
echo '>> ' . $string;
echo '<br />';  
echo '<br />';
echo 'Output results :';
echo '<br />';
echo '<br />';  

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slugify($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> First test passed in **' . round($time, 2) . 'ms**';
echo '<br />';  
echo '>> Result : ' . $newString;
echo '<br />';
echo '<br />';

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slug($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> Second test passed in **' . round($time, 2) . 'ms**';
echo '<br />';
echo '>> Result : ' . $newString;
echo '<br />';
echo '<br />';

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slugbis($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> Third test passed in **' . round($time, 2) . 'ms**';
echo '<br />';
echo '>> Result : ' . $newString;
echo '<br />';
echo '<br />';

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slugagain($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> Fourth test passed in **' . round($time, 2) . 'ms**';
echo '<br />';
echo '>> Result : ' . $newString;
echo '<br />';
echo '<br />';

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slugifybis($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> Fifth test passed in **' . round($time, 2) . 'ms**';
echo '<br />';
echo '>> Result : ' . $newString;
echo '<br />';
echo '<br />';

$start = microtime(true);

for($i = 0 ; $i < $max ; $i++){
    
    $newString = slugifyagain($string);
}

$time = (microtime(true) - $start) * 1000;

echo '> Sixth test passed in **' . round($time, 2) . 'ms**';
echo '<br />';
echo '>> Result : ' . $newString;
echo '</pre>';

Beginning :

Slugging 10000 iterations of following :

¿ Àñdréß l'affreux garçon & nøël en forêt !

Output results :

First test passed in 120.78ms

Result : -iquest-andresz-laffreux-arcon-and-noel-en-foret-

Second test passed in 3883.82ms

Result : -andreß-laffreux-garcon--nøel-en-foret-

Third test passed in 56.83ms

Result : andress-l-affreux-garcon-noel-en-foret

Fourth test passed in 18.93ms

Result : ¿-AndreSs-l'affreux-garcon-&-noel-en-foret-!

Fifth test passed in 6.45ms

Result : %C2%BF-%C3%80%C3%B1dr%C3%A9%C3%9F-l%27affreux-%C4%9Far%C3%A7on-%26-n%C3%B8%C3%ABl-en-for%C3%AAt-%21

Sixth test passed in 112.42ms

Result : andress-laffreux-garcon-n-el-en-foret

Further tests needed.

Edit : less iterations test

Beginning :

Slugging 100 iterations of following :

¿ Àñdréß l'affreux garçon & nøël en forêt !

Output results :

First test passed in 1.72ms

Result : -iquest-andresz-laffreux-arcon-and-noel-en-foret-

Second test passed in 48.59ms

Result : -andreß-laffreux-garcon--nøel-en-foret-

Third test passed in 0.91ms

Result : andress-l-affreux-garcon-noel-en-foret

Fourth test passed in 0.3ms

Result : ¿-AndreSs-l'affreux-garcon-&-noel-en-foret-!

Fifth test passed in 0.14ms

Result : %C2%BF-%C3%80%C3%B1dr%C3%A9%C3%9F-l%27affreux-%C4%9Far%C3%A7on-%26-n%C3%B8%C3%ABl-en-for%C3%AAt-%21

Sixth test passed in 1.4ms

Result : andress-laffreux-garcon-n-el-en-foret

LINQ orderby on date field in descending order

This statement will definitely help you:

env = env.OrderByDescending(c => c.ReportDate).ToList();

Remove portion of a string after a certain character

By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

remove white space from the end of line in linux

sed -i 's/[[:blank:]]\{1,\}$//' YourFile

[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)

Keep SSH session alive

We can keep our ssh connection alive by having following Global configurations

Add the following line to the /etc/ssh/ssh_config file:

ServerAliveInterval 60

What are best practices that you use when writing Objective-C and Cocoa?

Simple but oft-forgotten one. According to spec:

In general, methods in different classes that have the same selector (the same name) must also share the same return and argument types. This constraint is imposed by the compiler to allow dynamic binding.

in which case all the same named selectors, even if in different classes, will be regarded as to have identical return/argument types. Here is a simple example.

@interface FooInt:NSObject{}
-(int) print;
@end

@implementation FooInt
-(int) print{
    return 5;
}
@end

@interface FooFloat:NSObject{}
-(float) print;
@end

@implementation FooFloat
-(float) print{
    return 3.3;
}
@end

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
    id f1=[[FooFloat alloc]init];
    //prints 0, runtime considers [f1 print] to return int, as f1's type is "id" and FooInt precedes FooBar
    NSLog(@"%f",[f1 print]);

    FooFloat* f2=[[FooFloat alloc]init];
    //prints 3.3 expectedly as the static type is FooFloat
    NSLog(@"%f",[f2 print]);

    [f1 release];
    [f2 release]
    [pool drain];

    return 0;
}   

How can I update the current line in a C# Windows Console App?

So far we have three competing alternatives for how to do this:

Console.Write("\r{0}   ", value);                      // Option 1: carriage return
Console.Write("\b\b\b\b\b{0}", value);                 // Option 2: backspace
{                                                      // Option 3 in two parts:
    Console.SetCursorPosition(0, Console.CursorTop);   // - Move cursor
    Console.Write(value);                              // - Rewrite
}

I've always used Console.CursorLeft = 0, a variation on the third option, so I decided to do some tests. Here's the code I used:

public static void CursorTest()
{
    int testsize = 1000000;

    Console.WriteLine("Testing cursor position");
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < testsize; i++)
    {
        Console.Write("\rCounting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using \\r: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    int top = Console.CursorTop;
    for (int i = 0; i < testsize; i++)
    {
        Console.SetCursorPosition(0, top);        
        Console.Write("Counting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("\nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    Console.Write("Counting:          ");
    for (int i = 0; i < testsize; i++)
    {        
        Console.Write("\b\b\b\b\b\b\b\b{0,8}", i);
    }

    sw.Stop();
    Console.WriteLine("\nTime using \\b: {0}", sw.ElapsedMilliseconds);
}

On my machine, I get the following results:

  • Backspaces: 25.0 seconds
  • Carriage Returns: 28.7 seconds
  • SetCursorPosition: 49.7 seconds

Additionally, SetCursorPosition caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible, and thanks for teaching me a faster way to do this, SO!


Update: In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of \b over \r and SetCursorPosition.

How are Anonymous inner classes used in Java?

By an "anonymous class", I take it you mean anonymous inner class.

An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.

I tend to use it as a shortcut for attaching an event listener:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});

Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.

I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.

Can I use wget to check , but not download

You can use the following option to check for the files:

wget --delete-after URL

Get a Windows Forms control by name in C#

this.Controls.Find(name, searchAllChildren) doesn't find ToolStripItem because ToolStripItem is not a Control

  using SWF = System.Windows.Forms;
  using NUF = NUnit.Framework;
  namespace workshop.findControlTest {
     [NUF.TestFixture]
     public class FormTest {
        [NUF.Test]public void Find_menu() {
           // == prepare ==
           var fileTool = new SWF.ToolStripMenuItem();
           fileTool.Name = "fileTool";
           fileTool.Text = "File";

           var menuStrip = new SWF.MenuStrip();
           menuStrip.Items.Add(fileTool);

           var form = new SWF.Form();
           form.Controls.Add(menuStrip);

           // == execute ==
           var ctrl = form.Controls.Find("fileTool", true);

           // == not found! ==
           NUF.Assert.That(ctrl.Length, NUF.Is.EqualTo(0)); 
        }
     }
  }

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Virtual/pure virtual explained

From Wikipedia's Virtual function ...

In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.

Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class calls a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.

This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.

whereas..

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.

When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class must define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.

A virtual provides a way to override the functionality of the base class, and a pure-virtual requires it.

Serializing to JSON in jQuery

No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.