Programs & Examples On #Doxywizard

a GUI front-end for configuring and running doxygen.

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

Redirect website after certain amount of time

If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.

Here is a very basic approach using setTimeout()

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
    <p>You will be redirected in 3 seconds</p>_x000D_
    <script>_x000D_
        var timer = setTimeout(function() {_x000D_
            window.location='http://example.com'_x000D_
        }, 3000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Font Awesome & Unicode

For those who may stumble across this post, you need to set

font-family: FontAwesome; 

as a property in your CSS selector and then unicode will work fine in CSS

Bash loop ping successful

I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.

echo "Testing..."

PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"

eval $PING_CMD

if [[ $? -eq 0 ]]; then
    echo "Already connected."
else
    echo -n "Waiting for connection..."

    while true; do
        eval $PING_CMD

        if [[ $? -eq 0 ]]; then
            echo
            echo Connected.
            break
        else
            sleep 0.5
            echo -n .
        fi
    done
fi

I also have a Gist of this script which I'll update with fixes and improvements as needed.

C# Return Different Types?

May be you need "dynamic" type?

public dynamic GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return /*what boject you needed*/ ;`enter code here`   
}

PowerShell to remove text from a string

Another way to do this is with operator -replace.

$TestString = "test=keep this, but not this."

$NewString = $TestString -replace ".*=" -replace ",.*"

.*= means any number of characters up to and including an equals sign.

,.* means a comma followed by any number of characters.

Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

How to center form in bootstrap 3

A simple way is to add

.center_div{
    margin: 0 auto;
    width:80% /* value of your choice which suits your alignment */
}

to you class .container.Add width:xx % to it and you get perfectly centered div!

eg :

<div class="container center_div">

but i feel that by default container is centered in BS!

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

Checkbox angular material checked by default

You can either set with ngModel either with [checked] attribute. ngModel binded property should be set to 'true':

1.

  <mat-checkbox class = "example-margin" [(ngModel)] = "myModel"> 
    <label>Printer </label> 
  </mat-checkbox>

2.

<mat-checkbox [checked]= "myModel" class = "example-margin" > 
    <label>Printer </label> 
</mat-checkbox>

3.

<mat-checkbox [ngModel]="myModel" class="example-margin">
    <label>Printer </label> 
</mat-checkbox>

DEMO

Cannot find vcvarsall.bat when running a Python script

Install Visual Studio Express 2008 (9.0) from here: http://go.microsoft.com/?linkid=7729279

That's what fixed it for me.

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:

$comment = "$_POST['comment']";

Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:

$comment = "$_POST[comment]";

but dropping either pair of quotes works; it's a matter of style I suppose :)

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Can a normal Class implement multiple interfaces?

It is true that a java class can implement multiple interfaces at the same time, but there is a catch here. If in a class, you are trying to implement two java interfaces, which contains methods with same signature but diffrent return type, in that case you will get compilation error.

interface One
{
    int m1();
}
interface Two
{
    float m1();
}
public class MyClass implements One, Two{
    int m1() {}
    float m1() {}
    public static void main(String... args) {

    }
}

output :

prog.java:14: error: method m1() is already defined in class MyClass
    public float m1() {}
                 ^
prog.java:11: error: MyClass is not abstract and does not override abstract method m1() in Two
public class MyClass implements One, Two{
       ^
prog.java:13: error: m1() in MyClass cannot implement m1() in Two
    public int m1() {}
               ^
  return type int is not compatible with float
3 errors

How to get selected value from Dropdown list in JavaScript

Here is a simple example to get the selected value of dropdown in javascript

First we design the UI for dropdown

<div class="col-xs-12">
<select class="form-control" id="language">
    <option>---SELECT---</option>
    <option>JAVA</option>
    <option>C</option>
    <option>C++</option>
    <option>PERL</option>
</select>

Next we need to write script to get the selected item

<script type="text/javascript">
$(document).ready(function () {
    $('#language').change(function () {
        var doc = document.getElementById("language");
        alert("You selected " + doc.options[doc.selectedIndex].value);
    });
});

Now When change the dropdown the selected item will be alert.

Find and replace entire mysql database

Another option (depending on the use case) would be to use DataMystic's TextPipe and DataPipe products. I've used them in the past, and they've worked great in the complex replacement scenarios, and without having to export data out of the database for find-and-replace.

Check if a String contains numbers Java

try this

str.matches(".*\\d.*");

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

How to $http Synchronous call with AngularJS

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

Best practice to look up Java Enum

If you want the lookup to be case insensitive you can loop through the values making it a little more friendly:

 public enum MyEnum {
   A, B, C, D;

      public static MyEnum lookup(String id) {
        boolean found = false;
        for(MyEnum enum: values()){
           if(enum.toString().equalsIgnoreCase(id)) found = true;
        }  
        if(!found) throw new RuntimeException("Invalid value for my enum: " +id);
       }
}

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

Simple pthread! C++

Linkage. Try this:

extern "C" void *print_message() {...

Difference between style = "position:absolute" and style = "position:relative"

Absolute positioning is based on co-ordiantes of the display:

position:absolute;
top:0px;
left:0px;

^ places the element top left of the window.


Relative position is relative to where the element is placed:

position:relative;
top:1px;
left:1px;

^ places the element 1px down and 1px from the left of where it originally sat :)

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

How to config routeProvider and locationProvider in angularJS?

@Simple-Solution

I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run

python -m SimpleHTTPServer 8080

And that sets up the simple server on port 8080 letting you visit localhost:8080 on your browser to view the app in development.

Hope that helped!

Declaring and using MySQL varchar variables

try this:

declare @foo    varchar(7),
        @oldFoo varchar(7)

set @foo = '138'
set @oldFoo = '0' + @foo

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Zero an array in C code

Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));

DataSet panel (Report Data) in SSRS designer is gone

If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.

  1. Click inside the actual report layout.

  2. Now select "View" from the main menu bar.

  3. Now select "Report Data" which is the last item.

Invoking a PHP script from a MySQL trigger

Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)

How do I run Redis on Windows?

I don't run redis on windows. There's too much hassle involved in keeping up with the ports, and they lag behind redis-stable by a version or two all the time.

Instead I run redis on a Vagrant virtual machine that runs redis for me. I've bundled up the whole thing into a simple github repo so everyone can get in on the fun without too much hassle. The whole thing is an automated build so there's no mess. I blogged about the details here.

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

string.IsNullOrEmpty(str) - if you'd like to check string value has been provided

string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).

My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.

How to import existing Android project into Eclipse?

In my Android Project folder .project file was missing. Restoring the .project file,which will be hidden in Unix OS environment resolved the error.

Round to at most 2 decimal places (only if necessary)

number=(parseInt((number +0.005)*100))/100;     

add 0.005 if you want to normal round (2 decimals)

8.123 +0.005=> 8.128*100=>812/100=>8.12   

8.126 +0.005=> 8.131*100=>813/100=>8.13   

How to convert an array into an object using stdClass()

The quick and dirty way is using json_encode and json_decode which will turn the entire array (including sub elements) into an object.

$clasa = json_decode(json_encode($clasa)); //Turn it into an object

The same can be used to convert an object into an array. Simply add , true to json_decode to return an associated array:

$clasa = json_decode(json_encode($clasa), true); //Turn it into an array

An alternate way (without being dirty) is simply a recursive function:

function convertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = convertToObject($value);
        }
        $object->$key = $value;
    }
    return $object;
}

or in full code:

<?php
    function convertToObject($array) {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = convertToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    $clasa = array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
    );

    $obj = convertToObject($clasa);
    print_r($obj);
?>

which outputs (note that there's no arrays - only stdClass's):

stdClass Object
(
    [e1] => stdClass Object
        (
            [nume] => Nitu
            [prenume] => Andrei
            [sex] => m
            [varsta] => 23
        )

    [e2] => stdClass Object
        (
            [nume] => Nae
            [prenume] => Ionel
            [sex] => m
            [varsta] => 27
        )

    [e3] => stdClass Object
        (
            [nume] => Noman
            [prenume] => Alice
            [sex] => f
            [varsta] => 22
        )

    [e4] => stdClass Object
        (
            [nume] => Geangos
            [prenume] => Bogdan
            [sex] => m
            [varsta] => 23
        )

    [e5] => stdClass Object
        (
            [nume] => Vasile
            [prenume] => Mihai
            [sex] => m
            [varsta] => 25
        )

)

So you'd refer to it by $obj->e5->nume.

DEMO

How to Set the Background Color of a JButton on the Mac OS

If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:

 try {
    UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
 } catch (Exception e) {
            e.printStackTrace();
 }

That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

How can I tell which button was clicked in a PHP form submit?

In HTML:

<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />

In PHP:

if (isset($_POST["btnSubmit"])){
  // "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
  // "Delete" clicked
}

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $(".classname").hide();
  });
</script>

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

Difference between Fact table and Dimension table?

Super simple explanation:

Fact table: a data table that maps lookup IDs together. Is usually one of the main tables central to your application.

Dimension table: a lookup table used to store values (such as city names or states) that are repeated frequently in the fact table.

Rotate image with javascript

i have seen your running code .There is one line correction in your code.

Write:

$("#wrapper").rotate(angle); 

instead of:

$("#image").rotate(angle);

and you will get your desired output,hope this is what you want.

Laravel 5: Retrieve JSON array from $request

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());

How to style HTML5 range input to have different color before and after slider?

A small update to this one:

if you use the following it will update on the fly rather than on mouse release.

"change mousemove", function"

<script>
$('input[type="range"]').on("change mousemove", function () {
    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));

    $(this).css('background-image',
                '-webkit-gradient(linear, left top, right top, '
                + 'color-stop(' + val + ', #2f466b), '
                + 'color-stop(' + val + ', #d3d3db)'
                + ')'
                );
});</script>

How to extract the first two characters of a string in shell scripting?

You can use printf:

$ original='USCAGoleta9311734.5021-120.1287855805'
$ printf '%-.2s' "$original"
US

How can I scroll up more (increase the scroll buffer) in iTerm2?

Solution: In order to increase your buffer history on iterm bash terminal you've got two options:

Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)

Option 1. select the checkbox Unlimited scrollback

Option 2. type the selected Scrollback lines numbers you'd like your terminal buffer to cache (See image below)

enter image description here

How can I select random files from a directory in bash?

I use this: it uses temporary file but goes deeply in a directory until it find a regular file and return it.

# find for a quasi-random file in a directory tree:

# directory to start search from:
ROOT="/";  

tmp=/tmp/mytempfile    
TARGET="$ROOT"
FILE=""; 
n=
r=
while [ -e "$TARGET" ]; do 
    TARGET="$(readlink -f "${TARGET}/$FILE")" ; 
    if [ -d "$TARGET" ]; then
      ls -1 "$TARGET" 2> /dev/null > $tmp || break;
      n=$(cat $tmp | wc -l); 
      if [ $n != 0 ]; then
        FILE=$(shuf -n 1 $tmp)
# or if you dont have/want to use shuf:
#       r=$(($RANDOM % $n)) ; 
#       FILE=$(tail -n +$(( $r + 1 ))  $tmp | head -n 1); 
      fi ; 
    else
      if [ -f "$TARGET"  ] ; then
        rm -f $tmp
        echo $TARGET
        break;
      else 
        # is not a regular file, restart:
        TARGET="$ROOT"
        FILE=""
      fi
    fi
done;

Animate visibility modes, GONE and VISIBLE

To animate layout changes, you can add the following attribute to your LinearLayout

android:animateLayoutChanges="true"

and it will animate changes automatically for you.


For information, if android:animateLayoutChanges="true" is used, then custom animation via anim xml will not work.

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

How to get the number of characters in a std::string?

For Unicode

Several answers here have addressed that .length() gives the wrong results with multibyte characters, but there are 11 answers and none of them have provided a solution.

The case of Z??????a???????_l?`?¨???????g????????o???¯????????

First of all, it's important to know what you mean by "length". For a motivating example, consider the string "Z??????a???????_l?`?¨???????g????????o???¯????????" (note that some languages, notably Thai, actually use combining diacritical marks, so this isn't just useful for 15-year-old memes, but obviously that's the most important use case). Assume it is encoded in UTF-8. There are 3 ways we can talk about the length of this string:

95 bytes

00000000: 5acd a5cd accc becd 89cc b3cc ba61 cc92  Z............a..
00000010: cc92 cd8c cc8b cdaa ccb4 cd95 ccb2 6ccd  ..............l.
00000020: a4cc 80cc 9acc 88cd 9ccc a8cd 8ecc b0cc  ................
00000030: 98cd 89cc 9f67 cc92 cd9d cd85 cd95 cd94  .....g..........
00000040: cca4 cd96 cc9f 6fcc 90cd afcc 9acc 85cd  ......o.........
00000050: aacc 86cd a3cc a1cc b5cc a1cc bccd 9a    ...............

50 codepoints

LATIN CAPITAL LETTER Z
COMBINING LEFT ANGLE BELOW
COMBINING DOUBLE LOW LINE
COMBINING INVERTED BRIDGE BELOW
COMBINING LATIN SMALL LETTER I
COMBINING LATIN SMALL LETTER R
COMBINING VERTICAL TILDE
LATIN SMALL LETTER A
COMBINING TILDE OVERLAY
COMBINING RIGHT ARROWHEAD BELOW
COMBINING LOW LINE
COMBINING TURNED COMMA ABOVE
COMBINING TURNED COMMA ABOVE
COMBINING ALMOST EQUAL TO ABOVE
COMBINING DOUBLE ACUTE ACCENT
COMBINING LATIN SMALL LETTER H
LATIN SMALL LETTER L
COMBINING OGONEK
COMBINING UPWARDS ARROW BELOW
COMBINING TILDE BELOW
COMBINING LEFT TACK BELOW
COMBINING LEFT ANGLE BELOW
COMBINING PLUS SIGN BELOW
COMBINING LATIN SMALL LETTER E
COMBINING GRAVE ACCENT
COMBINING DIAERESIS
COMBINING LEFT ANGLE ABOVE
COMBINING DOUBLE BREVE BELOW
LATIN SMALL LETTER G
COMBINING RIGHT ARROWHEAD BELOW
COMBINING LEFT ARROWHEAD BELOW
COMBINING DIAERESIS BELOW
COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW
COMBINING PLUS SIGN BELOW
COMBINING TURNED COMMA ABOVE
COMBINING DOUBLE BREVE
COMBINING GREEK YPOGEGRAMMENI
LATIN SMALL LETTER O
COMBINING SHORT STROKE OVERLAY
COMBINING PALATALIZED HOOK BELOW
COMBINING PALATALIZED HOOK BELOW
COMBINING SEAGULL BELOW
COMBINING DOUBLE RING BELOW
COMBINING CANDRABINDU
COMBINING LATIN SMALL LETTER X
COMBINING OVERLINE
COMBINING LATIN SMALL LETTER H
COMBINING BREVE
COMBINING LATIN SMALL LETTER A
COMBINING LEFT ANGLE ABOVE

5 graphemes

Z with some s**t
a with some s**t
l with some s**t
g with some s**t
o with some s**t

Finding the lengths using ICU

There are C++ classes for ICU, but they require converting to UTF-16. You can use the C types and macros directly to get some UTF-8 support:

#include <memory>
#include <iostream>
#include <unicode/utypes.h>
#include <unicode/ubrk.h>
#include <unicode/utext.h>

//
// C++ helpers so we can use RAII
//
// Note that ICU internally provides some C++ wrappers (such as BreakIterator), however these only seem to work
// for UTF-16 strings, and require transforming UTF-8 to UTF-16 before use.
// If you already have UTF-16 strings or can take the performance hit, you should probably use those instead of
// the C functions. See: http://icu-project.org/apiref/icu4c/
//
struct UTextDeleter { void operator()(UText* ptr) { utext_close(ptr); } };
struct UBreakIteratorDeleter { void operator()(UBreakIterator* ptr) { ubrk_close(ptr); } };
using PUText = std::unique_ptr<UText, UTextDeleter>;
using PUBreakIterator = std::unique_ptr<UBreakIterator, UBreakIteratorDeleter>;

void checkStatus(const UErrorCode status)
{
    if(U_FAILURE(status))
    {
        throw std::runtime_error(u_errorName(status));
    }
}

size_t countGraphemes(UText* text)
{
    // source for most of this: http://userguide.icu-project.org/strings/utext
    UErrorCode status = U_ZERO_ERROR;
    PUBreakIterator it(ubrk_open(UBRK_CHARACTER, "en_us", nullptr, 0, &status));
    checkStatus(status);
    ubrk_setUText(it.get(), text, &status);
    checkStatus(status);
    size_t charCount = 0;
    while(ubrk_next(it.get()) != UBRK_DONE)
    {
        ++charCount;
    }
    return charCount;
}

size_t countCodepoints(UText* text)
{
    size_t codepointCount = 0;
    while(UTEXT_NEXT32(text) != U_SENTINEL)
    {
        ++codepointCount;
    }
    // reset the index so we can use the structure again
    UTEXT_SETNATIVEINDEX(text, 0);
    return codepointCount;
}

void printStringInfo(const std::string& utf8)
{
    UErrorCode status = U_ZERO_ERROR;
    PUText text(utext_openUTF8(nullptr, utf8.data(), utf8.length(), &status));
    checkStatus(status);

    std::cout << "UTF-8 string (might look wrong if your console locale is different): " << utf8 << std::endl;
    std::cout << "Length (UTF-8 bytes): " << utf8.length() << std::endl;
    std::cout << "Length (UTF-8 codepoints): " << countCodepoints(text.get()) << std::endl;
    std::cout << "Length (graphemes): " << countGraphemes(text.get()) << std::endl;
    std::cout << std::endl;
}

void main(int argc, char** argv)
{
    printStringInfo(u8"Hello, world!");
    printStringInfo(u8"????????????");
    printStringInfo(u8"\xF0\x9F\x90\xBF");
    printStringInfo(u8"Z??????a???????_l?`?¨???????g????????o???¯????????");
}

This prints:

UTF-8 string (might look wrong if your console locale is different): Hello, world!
Length (UTF-8 bytes): 13
Length (UTF-8 codepoints): 13
Length (graphemes): 13

UTF-8 string (might look wrong if your console locale is different): ????????????
Length (UTF-8 bytes): 36
Length (UTF-8 codepoints): 12
Length (graphemes): 10

UTF-8 string (might look wrong if your console locale is different): 
Length (UTF-8 bytes): 4
Length (UTF-8 codepoints): 1
Length (graphemes): 1

UTF-8 string (might look wrong if your console locale is different): Z??????a???????_l?`?¨???????g????????o???¯????????
Length (UTF-8 bytes): 95
Length (UTF-8 codepoints): 50
Length (graphemes): 5

Boost.Locale wraps ICU, and might provide a nicer interface. However, it still requires conversion to/from UTF-16.

How to create the most compact mapping n ? isprime(n) up to a limit N?

import math
import time


def check_prime(n):

    if n == 1:
        return False

    if n == 2:
        return True

    if n % 2 == 0:
        return False

    from_i = 3
    to_i = math.sqrt(n) + 1

    for i in range(from_i, int(to_i), 2):
        if n % i == 0:
            return False
    return True

Send a ping to each IP on a subnet

FOR /L %i in (1,1,254) DO PING 192.168.1.%i -n 1 -w 100 | for /f "tokens=3 delims=: " %j in ('find /i "TTL="') do echo %j>>IPsOnline.txt

Check whether there is an Internet connection available on Flutter app

For anyone else who lands here I'd like to add on to Günter Zöchbauer's answer this was my solution for implementing a utility to know if there's internet or not regardless of anything else.

Disclaimer:

I'm new to both Dart and Flutter so this may not be the best approach, but would love to get feedback.


Combining flutter_connectivity and Günter Zöchbauer's connection test

My requirements

I didn't want to have a bunch of repeated code anywhere I needed to check the connection and I wanted it to automatically update components or anything else that cared about the connection whenever there was a change.

ConnectionStatusSingleton

First we setup a Singleton. If you're unfamiliar with this pattern there's a lot of good info online about them. But the gist is that you want to make a single instance of a class during the application life cycle and be able to use it anywhere.

This singleton hooks into flutter_connectivity and listens for connectivity changes, then tests the network connection, then uses a StreamController to update anything that cares.

It looks like this:

import 'dart:io'; //InternetAddress utility
import 'dart:async'; //For StreamController/Stream

import 'package:connectivity/connectivity.dart';

class ConnectionStatusSingleton {
    //This creates the single instance by calling the `_internal` constructor specified below
    static final ConnectionStatusSingleton _singleton = new ConnectionStatusSingleton._internal();
    ConnectionStatusSingleton._internal();

    //This is what's used to retrieve the instance through the app
    static ConnectionStatusSingleton getInstance() => _singleton;

    //This tracks the current connection status
    bool hasConnection = false;

    //This is how we'll allow subscribing to connection changes
    StreamController connectionChangeController = new StreamController.broadcast();

    //flutter_connectivity
    final Connectivity _connectivity = Connectivity();

    //Hook into flutter_connectivity's Stream to listen for changes
    //And check the connection status out of the gate
    void initialize() {
        _connectivity.onConnectivityChanged.listen(_connectionChange);
        checkConnection();
    }

    Stream get connectionChange => connectionChangeController.stream;

    //A clean up method to close our StreamController
    //   Because this is meant to exist through the entire application life cycle this isn't
    //   really an issue
    void dispose() {
        connectionChangeController.close();
    }

    //flutter_connectivity's listener
    void _connectionChange(ConnectivityResult result) {
        checkConnection();
    }

    //The test to actually see if there is a connection
    Future<bool> checkConnection() async {
        bool previousConnection = hasConnection;

        try {
            final result = await InternetAddress.lookup('google.com');
            if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
                hasConnection = true;
            } else {
                hasConnection = false;
            }
        } on SocketException catch(_) {
            hasConnection = false;
        }

        //The connection status changed send out an update to all listeners
        if (previousConnection != hasConnection) {
            connectionChangeController.add(hasConnection);
        }

        return hasConnection;
    }
}

Usage

Initialization

First we have to make sure we call the initialize of our singleton. But only once. This parts up to you but I did it in my app's main():

void main() {
    ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
    connectionStatus.initialize();

    runApp(MyApp());

    //Call this if initialization is occuring in a scope that will end during app lifecycle
    //connectionStatus.dispose();   
}

In Widget or elsewhere

import 'dart:async'; //For StreamSubscription

...

class MyWidgetState extends State<MyWidget> {
    StreamSubscription _connectionChangeStream;

    bool isOffline = false;

    @override
    initState() {
        super.initState();

        ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
        _connectionChangeStream = connectionStatus.connectionChange.listen(connectionChanged);
    }

    void connectionChanged(dynamic hasConnection) {
        setState(() {
            isOffline = !hasConnection;
        });
    }

    @override
    Widget build(BuildContext ctxt) {
        ...
    }
}

Hope somebody else finds this useful!


Example github repo: https://github.com/dennmat/flutter-connectiontest-example

Toggle airplane mode in the emulator to see the result

Create two blank lines in Markdown

If you are using a library like markdown-it or PythonMarkdown this can also be solved by replacing two line breaks (in Regex /\n\n$/gm) with a line break and an invisible character (\n ) before rendering. Note that the character after \n is an Alt+0160 or an invisible character.

For example, using markdown-it (although it work for any other lib too) with the input:

1

2


3


4



5

Rendered with md.render(string.data.replace(/\n\n$/gm, "\n ")) you will get:

enter image description here

java.sql.SQLException: Exhausted Resultset

I've seen this error while trying to access a column value after processing the resultset.

if (rs != null) {
  while (rs.next()) {
    count = rs.getInt(1);
  }
  count = rs.getInt(1); //this will throw Exhausted resultset
}

Hope this will help you :)

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

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

How do you dynamically allocate a matrix?

 #include <iostream>

    int main(){
        int rows=4;
        int cols=4;
        int **arr;

        arr = new int*[rows];
        for(int i=0;i<rows;i++){
           arr[i]=new int[cols];
        }
        // statements

        for(int i=0;i<rows;i++){
           delete []arr[i];
        }
        delete []arr;
        return 0;
     }

Using CSS :before and :after pseudo-elements with inline CSS?

You can't create pseudo elements in inline css.

However, if you can create a pseudo element in a stylesheet, then there's a way to style it inline by setting an inline style to its parent element, and then using inherit keyword to style the pseudo element, like this:

<parent style="background-image:url(path/to/file); background-size:0px;"></p>

<style> 
   parent:before{
      content:'';
      background-image:inherit;
      (other)
   }
</style>

sometimes this can be handy.

process.env.NODE_ENV is undefined

You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.

In the project root, run:

npm install cross-env

Then in your package.json, under scripts, add:

"start": "cross-env NODE_ENV=dev node your-app-name.js"

Then in your terminal, at the project root, start your app by running:

npm start

The environment variable will then be available in your app as process.env.NODE_ENV, so you could do something like:

if (process.env.NODE_ENV === 'dev') {
  // Your dev-only logic goes here
}

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Here is the ng repeat with ng click function and to append with slider

<script>
var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
        $scope.employees = [
            { 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
            { 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
            { 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
            { 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
            { 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
        ]

            //This will hide the DIV by default.
                $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
</script>
</head>

<body>

<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
                    <div class="MS-content">
                        <div class="item"  ng-repeat="emps in employees"  ng-show = "IsVisible">
                          <div class="subitem">
        <p>{{emps.id}}</p>
        <p>{{emps.name}}</p>
        <p>{{emps.age}}</p>
        </div>
                        </div>


                    </div>
                    <div class="MS-controls">
                        <button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
                        <button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
                    </div>
                </div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
<script src="js/multislider.js"></script> 
<script>

        $('#mixedSlider').multislider({
            duration: 750,
            interval: false
        });
</script>

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.

COUNT(*) - Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null

COUNT(1) - Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE matches.

COUNT(PK) - The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.

From this you can see the first count is the slowest and the last count is the fastest in Oracle.

TypeError: 'list' object is not callable in python

You may have used built-in name 'list' for a variable in your code. If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal. In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.

Used Built-in list name for my list

Change my list name to my_list but still get error, Shift+Tab shows that list still hold the values of my_list

Restart Kernal and it's all good

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

Set font-weight using Bootstrap classes

In Bootstrap 4:

class="font-weight-bold"

Or:

<strong>text</strong>

android adb turn on wifi via adb

If you are locked out and WiFi is turned off in your Androud device then one solution is to connect your phone to a PC (connected to internet) and try to login with your google account. - it worked for me.

Git mergetool generates unwanted .orig files

I use this to clean up all files ending in ".orig":

function git-clean-orig {
    git status -su | grep -e"\.orig$" | cut -f2 -d" " | xargs rm -r
}

If you are a scaredy-cat :) you could leave the last part off just to list them (or leave off the -r if you want to approve each delete):

function git-show-orig {
    git status -su | grep -e"\.orig$" | cut -f2 -d" "
}

Checking if a worksheet-based checkbox is checked

Try: Controls("Check Box 1") = True

I can't find my git.exe file in my Github folder

run github that you downloaded, click tools and options symbol(top right), click about github for windows and then open the debug log. under DIAGNOSTICS look for Git Executable Exists:

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

First of all, enable the less secure app in your Gmail account from which you will send emails using this link:- https://myaccount.google.com/lesssecureapps?pli=1

Then you simply add the following code in your session creation. It will work fine then.

Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

if you want the more elaborated one use the following:-

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

    public Properties mailProperties() {
        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "your_email");
        props.setProperty("mail.smtp.password", "your_password");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.auth", "true");

        return props;
    }

    public String sendMail(String from, String to, String subject, String msgBody) {
        Properties props = mailProperties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

        mailSession.setDebug(false);

        try {
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            message.setFrom(new InternetAddress(from));
            message.addRecipients(Message.RecipientType.TO, to);

            MimeMultipart multipart = new MimeMultipart();

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(msgBody, "text/html");

            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            transport.connect();
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();
            return "SUCCESS";
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            return "INVALID_EMAIL";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

    public static void main(String args[]) {
        System.out.println(new MailSender().sendMail("your_email/from_email", "to_email", "Subject", "Message"));
    }
}

Hope! it helps. Thanks!

How to get Wikipedia content using Wikipedia's API?

To GET first paragraph of an article:

https://en.wikipedia.org/w/api.php?action=query&titles=Belgrade&prop=extracts&format=json&exintro=1

I have created short Wikipedia API docs for my own needs. There are working examples on how to get article(s), image(s) and similar.

How to replace values at specific indexes of a python list?

Why not just:

map(s.__setitem__, a, m)

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Spring 3 RequestMapping: Get path value

You need to use built-in pathMatcher:

@RequestMapping("/{id}/**")
public void test(HttpServletRequest request, @PathVariable long id) throws Exception {
    ResourceUrlProvider urlProvider = (ResourceUrlProvider) request
            .getAttribute(ResourceUrlProvider.class.getCanonicalName());
    String restOfUrl = urlProvider.getPathMatcher().extractPathWithinPattern(
            String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)),
            String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)));

Qt Creator color scheme

My Dark Color scheme for QtCreator is at:

https://github.com/borzh/qt-creator-css/blob/master/qt-creator.css

To use with Vim (dark) scheme.

Hope it is useful for someone.

Possible to iterate backwards through a foreach?

Elaborateling slighty on the nice answer by Jon Skeet, this could be versatile:

public static IEnumerable<T> Directional<T>(this IList<T> items, bool Forwards) {
    if (Forwards) foreach (T item in items) yield return item;
    else for (int i = items.Count-1; 0<=i; i--) yield return items[i];
}

And then use as

foreach (var item in myList.Directional(forwardsCondition)) {
    .
    .
}

Create a GUID in Java

Have a look at the UUID class bundled with Java 5 and later.

For example:

How do I make a textbox that only accepts numbers?

you can simply prevent adding non-numerical chars by this simple code

 if (long.TryParse(TextBox.Text,out long isparsable))
        {
          // your code to handle numbers
        }
        else
        {
            TextBox.Text="Only Numbers Allowed";
            TextBox.Focus();
            TextBox.SelectAll();
        }

Checking if a SQL Server login already exists

As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

Fast way to concatenate strings in nodeJS/JavaScript

The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.

Tested with the following code:

function a(){
    var s = "hello";
    var p = "world";
    s = s + p;
    return s;
}

function b(){
    var s = new Buffer("hello");
    var p = new Buffer("world");
    s = Buffer.concat([s,p]);
    return s;
}

var times = 100000;

var t1 = new Date();
for( var i = 0; i < times; i++){
    a();
}

var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
    b();
}

var t3 = new Date();

console.log("Buffer took: " + (t3-t2) + " ms.");

Output:

Normal took: 4 ms.
Buffer took: 458 ms.

Overcoming "Display forbidden by X-Frame-Options"

Solution for loading an external website into an iFrame even tough the x-frame option is set to deny on the external website.

If you want to load a other website into an iFrame and you get the Display forbidden by X-Frame-Options” error then you can actually overcome this by creating a server side proxy script.

The src attribute of the iFrame could have an url looking like this: /proxy.php?url=https://www.example.com/page&key=somekey

Then proxy.php would look something like:

if (isValidRequest()) {
   echo file_get_contents($_GET['url']);
}

function isValidRequest() {
    return $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['key']) && 
    $_GET['key'] === 'somekey';
}

This by passes the block, because it is just a GET request that might as wel have been a ordinary browser page visit.

Be aware: You might want to improve the security in this script. Because hackers could start loading in webpages via your proxy script.

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

How to know the git username and email saved during configuration?

Considering what @Robert said, I tried to play around with the config command and it seems that there is a direct way to know both the name and email.

To know the username, type:

git config user.name

To know the email, type:

git config user.email

These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.

Sound alarm when code finishes

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

Create a tag in a GitHub repository

Using Sourcetree

Here are the simple steps to create a GitHub Tag, when you release build from master.

  1. Open source_tree tab

    step 1

  2. Right click on Tag sections from Tag which appear on left navigation section

    step 2

  3. Click on New Tag()

  4. A dialog appears to Add Tag and Remove Tag
  5. Click on Add Tag from give name to tag (preferred version name of the code)

    step 3

  6. If you want to push the TAG on remote, while creating the TAG ref: step 5 which gives checkbox push TAG to origin check it and pushed tag appears on remote repository

  7. In case while creating the TAG if you have forgotten to check the box Push to origin, you can do it later by right-clicking on the created TAG, click on Push to origin. enter image description here

Enable PHP Apache2

You can use a2enmod or a2dismod to enable/disable modules by name.

From terminal, run: sudo a2enmod php5 to enable PHP5 (or some other module), then sudo service apache2 reload to reload the Apache2 configuration.

`getchar()` gives the same output as the input string

getchar() reads a single character of input and returns that character as the value of the function. If there is an error reading the character, or if the end of input is reached, getchar() returns a special value, represented by EOF.

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

How can I convert an Integer to localized month name in Java?

import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

How to read lines of a file in Ruby

how about gets ?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end

Python: How do I make a subclass from a superclass?

class BankAccount:

  def __init__(self, balance=0):
    self.balance = int(balance)

  def checkBalance(self): ## Checking opening balance....
    return self.balance

  def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
    self.deposit_amount = deposit_amount
    self.balance += deposit_amount
    return self.balance

  def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
    if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
        return 'invalid transaction'
    else:
      self.balance -= withdraw_amount
      return self.balance


class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class

    def __init__(self,balance=0, minimum_balance=500):
        BankAccount.__init__(self, balance=0)
        self.minimum_balance = minimum_balance
        self.balance = balance - minimum_balance
        #print "Subclass MinimumBalanceAccount of the BankAccount class created!"

    def MinimumBalance(self):
        return self.minimum_balance

c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))

b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())

How to add reference to a method parameter in javadoc?

I guess you could write your own doclet or taglet to support this behaviour.

Taglet Overview

Doclet Overview

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

In Visual Studio Code How do I merge between two local branches?

Update June 2017 (from VSCode 1.14)

The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch" command.
And PR 27405 added handling the diff3-style merge correctly.

Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers

https://code.visualstudio.com/assets/updates/1_18/merge.png

From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.


Original answer 2016:

The Version Control doc does not mention merge commands, only merge status and conflict support.

Even the latest 1.3 June release does not bring anything new to the VCS front.

This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool, because:

Is this feature being included in the next iteration, by any chance?

Probably not, this is a big endeavour, since a merge UI needs to be implemented.

That leaves the actual merge to be initiated from command line only.

Laravel Eloquent - Get one Row

Laravel 5.2

$sql = "SELECT * FROM users WHERE email = $email";

$user = collect(\User::select($sql))->first();

or

$user = User::table('users')->where('email', $email)->pluck();

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Set icon for Android application

1-Create Your icon in Photoshop Or Coreldraw by size 256*256

note that use PNG file format if you want to have a transparent icon

2-Upload Your icon in https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

3-Set your setting on this site enter image description here

4-Download the zip file automatically created by the webpage by clicking on download button enter image description here

5-Extract the zip file and copy res folder to you project library enter image description here

note that res folder contain all size icon

6-finally you need to set the manifest to use icon

<application android:icon="@drawable/your_icon" >
.... 
</application>

When should you use constexpr capability in C++11?

From Stroustrup's speech at "Going Native 2012":

template<int M, int K, int S> struct Unit { // a unit in the MKS system
       enum { m=M, kg=K, s=S };
};

template<typename Unit> // a magnitude with a unit 
struct Value {
       double val;   // the magnitude 
       explicit Value(double d) : val(d) {} // construct a Value from a double 
};

using Speed = Value<Unit<1,0,-1>>;  // meters/second type
using Acceleration = Value<Unit<1,0,-2>>;  // meters/second/second type
using Second = Unit<0,0,1>;  // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second 

constexpr Value<Second> operator"" s(long double d)
   // a f-p literal suffixed by ‘s’
{
  return Value<Second> (d);  
}   

constexpr Value<Second2> operator"" s2(long double d)
  // a f-p literal  suffixed by ‘s2’ 
{
  return Value<Second2> (d); 
}

Speed sp1 = 100m/9.8s; // very fast for a human 
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)  
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit) 
Acceleration acc = sp1/0.5s; // too fast for a human

JavaScript: Alert.Show(message) From ASP.NET Code-behind

if you are using ScriptManager on the page then you can also try using this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);

How do I remove the non-numeric character from a string in java?

Simple way without using Regex:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

How to match "any character" in regular expression?

I work this Not always dot is means any char. Exception when single line mode. \p{all} should be

String value = "|°¬<>!\"#$%&/()=?'\\¡¿/*-+_@[]^^{}";
String expression = "[a-zA-Z0-9\\p{all}]{0,50}";
if(value.matches(expression)){
    System.out.println("true");
} else {
    System.out.println("false");
}

How to increase code font size in IntelliJ?

To change the font size in the current version of IntelliJ IDEA, go to File → Settings → Editor → General. In the dialog box, and check the item labeled "Change font size (Zoom) with Ctrl+Mouse Wheel".

What is the preferred/idiomatic way to insert into a map?

Since C++17 std::map offers two new insertion methods: insert_or_assign() and try_emplace(), as also mentioned in the comment by sp2danny.

insert_or_assign()

Basically, insert_or_assign() is an "improved" version of operator[]. In contrast to operator[], insert_or_assign() doesn't require the map's value type to be default constructible. For example, the following code doesn't compile, because MyClass does not have a default constructor:

class MyClass {
public:
    MyClass(int i) : m_i(i) {};
    int m_i;
};

int main() {
    std::map<int, MyClass> myMap;

    // VS2017: "C2512: 'MyClass::MyClass' : no appropriate default constructor available"
    // Coliru: "error: no matching function for call to 'MyClass::MyClass()"
    myMap[0] = MyClass(1);

    return 0;
}

However, if you replace myMap[0] = MyClass(1); by the following line, then the code compiles and the insertion takes place as intended:

myMap.insert_or_assign(0, MyClass(1));

Moreover, similar to insert(), insert_or_assign() returns a pair<iterator, bool>. The Boolean value is true if an insertion occurred and false if an assignment was done. The iterator points to the element that was inserted or updated.

try_emplace()

Similar to the above, try_emplace() is an "improvement" of emplace(). In contrast to emplace(), try_emplace() doesn't modify its arguments if insertion fails due to a key already existing in the map. For example, the following code attempts to emplace an element with a key that is already stored in the map (see *):

int main() {
    std::map<int, std::unique_ptr<MyClass>> myMap2;
    myMap2.emplace(0, std::make_unique<MyClass>(1));

    auto pMyObj = std::make_unique<MyClass>(2);    
    auto [it, b] = myMap2.emplace(0, std::move(pMyObj));  // *

    if (!b)
        std::cout << "pMyObj was not inserted" << std::endl;

    if (pMyObj == nullptr)
        std::cout << "pMyObj was modified anyway" << std::endl;
    else
        std::cout << "pMyObj.m_i = " << pMyObj->m_i <<  std::endl;

    return 0;
}

Output (at least for VS2017 and Coliru):

pMyObj was not inserted
pMyObj was modified anyway

As you can see, pMyObj no longer points to the original object. However, if you replace auto [it, b] = myMap2.emplace(0, std::move(pMyObj)); by the the following code, then the output looks different, because pMyObj remains unchanged:

auto [it, b] = myMap2.try_emplace(0, std::move(pMyObj));

Output:

pMyObj was not inserted
pMyObj pMyObj.m_i = 2

Code on Coliru

Please note: I tried to keep my explanations as short and simple as possible to fit them into this answer. For a more precise and comprehensive description, I recommend reading this article on Fluent C++.

What is PECS (Producer Extends Consumer Super)?

In a nutshell, three easy rules to remember PECS:

  1. Use the <? extends T> wildcard if you need to retrieve object of type T from a collection.
  2. Use the <? super T> wildcard if you need to put objects of type T in a collection.
  3. If you need to satisfy both things, well, don’t use any wildcard. As simple as that.

How do I use Spring Boot to serve static content located in Dropbox folder?

Note that WebMvcConfigurerAdapter is deprecated now (see WebMvcConfigurerAdapter). Due to Java 8 default methods, you only have to implement WebMvcConfigurer.

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

Your question "what are they" is already answered above.

As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:

_isnan(), _isfinite(), and _fpclass()

On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).

How to hide elements without having them take space on the page?

here's a different take on putting them back after display:none. don't use display:block/inline etc. Instead (if using javascript) set css property display to '' (i.e. blank)

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

React-Native: Application has not been registered error

This solution worked for me after 2 days of debugging. Change this :

AppRegistry.registerComponent('AppName', () => App);

to

AppRegistry.registerComponent('main', () => App);

How to convert int to float in C?

Change your code to:

int total=0, number=0;
float percentage=0.0f;

percentage=((float)number/total)*100f;
printf("%.2f", (double)percentage);

Detect the Enter key in a text input field

$(".input1").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        // Do something
    }
});

// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.

Connecting to Microsoft SQL server using Python

here's the one that works for me:

from sqlalchemy import create_engine
import urllib

conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')

quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

I solved the problem with this code:

using System.IO;

var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")))

In Subversion can I be a user other than my login name?

I believe if you use the file:// method to access your subversion repository, your changes are always performed under the user which accesses the repository. You need to use a method that supports authentication such as http:// or svn://.

See http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.serverconfig.choosing

What does O(log n) mean exactly?

The complete binary example is O(ln n) because the search looks like this:

1 2 3 4 5 6 7 8 9 10 11 12

Searching for 4 yields 3 hits: 6, 3 then 4. And log2 12 = 3, which is a good apporximate to how many hits where needed.

I want to exception handle 'list index out of range.'

You have two options; either handle the exception or test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

or

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

Use the first if there often is no second item, the second if there sometimes is no second item.

C# string does not contain possible?

This should do the trick for you.

For one word:

if (!string.Contains("One"))

For two words:

if (!(string.Contains("One") && string.Contains("Two")))

Getting the object's property name

Use Object.keys():

_x000D_
_x000D_
var myObject = { a: 'c', b: 'a', c: 'b' };_x000D_
var keyNames = Object.keys(myObject);_x000D_
console.log(keyNames); // Outputs ["a","b","c"]
_x000D_
_x000D_
_x000D_

Object.keys() gives you an array of property names belonging to the input object.

IE7 Z-Index Layering Issues

I found that I had to place a special z-index designation on div in a ie7 specific styelsheet:

div { z-index:10; }

For the z-index of unrelated divs, such as a nav, to show above the slider. I could not simply add a z-index to the slider div itself.

Expected corresponding JSX closing tag for input Reactjs

This error also happens if you have got the order of your components wrong.

Example: this wrong:

 <ComponentA> 
    <ComponentB> 

    </ComponentA> 
 </ComponentB> 

correct way:

  <ComponentA> 
    <ComponentB>

    </ComponentB>  
  </ComponentA> 

The requested resource does not support HTTP method 'GET'

Resolved this issue by using http(s) when accessing the endpoint. The route I was accessing was not available over http. So I would say verify the protocols for which the route is available.

Set Text property of asp:label in Javascript PROPER way

Place HiddenField Control in your Form.

<asp:HiddenField ID="hidden" runat="server" />

Create a Property in the Form

protected String LabelProperty
{
    get
    {
        return hidden.Value;
    }
    set
    {
        hidden.Value = value;
    }
}

Update the Hidden Field value from JavaScript

<script>
   function UpdateControl() {
            document.getElementById('<%=hidden.ClientID %>').value = '12';
   }
</script>

Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .

Batch Renaming of Files in a Directory

If you don't mind using regular expressions, then this function would give you much power in renaming files:

import re, glob, os

def renamer(files, pattern, replacement):
    for pathname in glob.glob(files):
        basename= os.path.basename(pathname)
        new_filename= re.sub(pattern, replacement, basename)
        if new_filename != basename:
            os.rename(
              pathname,
              os.path.join(os.path.dirname(pathname), new_filename))

So in your example, you could do (assuming it's the current directory where the files are):

renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")

but you could also roll back to the initial filenames:

renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")

and more.

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

IIS7 folder permissions for web application

http://forums.iis.net/t/1187650.aspx has the answer. Setting the iis authentication to appliction pool identity will resolve this.

In IIS Authentication, Anonymous Authentication was set to "Specific User". When I changed it to Application Pool, I can access the site.

To set, click on your website in IIS and double-click "Authentication". Right-click on "Anonymous Authentication" and click "Edit..." option. Switch from "Specific User" to "Application pool identity". Now you should be able to set file and folder permissions using the IIS AppPool\{Your App Pool Name}.

How to get the path of the batch script in Windows?

I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.

I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.

#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

How can I add an image file into json object?

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    messageText = (TextView) findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"
            + uploadFileName + "'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "",
                    "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("uploading started.....");
                        }
                    });

                    uploadFile(uploadFilePath + "" + uploadFileName);

                }
            }).start();
        }
    });
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
                + uploadFileName);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        + uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false); // Don't use a Cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(connection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            // + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + " http://www.androidexample.com/media/uploads/"
                                + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(UploadToServer.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadToServer.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadToServer.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

PHP FILE

<?php
$target_path  = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>

POST request with JSON body

If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...

Is there a way to provide named parameters in a function call in JavaScript?

Lot's of people say to just use the "Pass an object" trick so that you have named parameters.

/**
 * My Function
 *
 * @param {Object} arg1 Named arguments
 */
function myFunc(arg1) { }

myFunc({ param1 : 70, param2 : 175});

And that works great, except..... when it comes to most IDEs out there, a lot of us developers rely on type / argument hints within our IDE. I personally use PHP Storm (Along with other JetBrains IDEs like PyCharm for python and AppCode for Objective C)

And the biggest problem with using the "Pass an object" trick is that when you are calling the function, the IDE gives you a single type hint and that's it... How are we supposed to know what parameters and types should go into the arg1 object?

I have no idea what parameters should go in arg1

So... the "Pass an object" trick doesn't work for me... It actually causes more headaches with having to look at each function's docblock before I know what parameters the function expects.... Sure, it's great for when you are maintaining existing code, but it's horrible for writing new code.

Well, this is the technique I use.... Now, there may be some issues with it, and some developers may tell me I'm doing it wrong, and I have an open mind when it comes to these things... I am always willing to look at better ways of accomplishing a task... So, if there is an issue with this technique, then comments are welcome.

/**
 * My Function
 *
 * @param {string} arg1 Argument 1
 * @param {string} arg2 Argument 2
 */
function myFunc(arg1, arg2) { }

var arg1, arg2;
myFunc(arg1='Param1', arg2='Param2');

This way, I have the best of both worlds... new code is easy to write as my IDE gives me all the proper argument hints... And, while maintaining code later on, I can see at a glance, not only the value passed to the function, but also the name of the argument. The only overhead I see is declaring your argument names as local variables to keep from polluting the global namespace. Sure, it's a bit of extra typing, but trivial compared to the time it takes to look up docblocks while writing new code or maintaining existing code.

Now, I have all the parameters and types when creating new code

UIView touch event in controller

Just an update to above answers :

If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...

class ClickableUIView: UIView {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.

}//class closes here

Also, call this Class from Storyboard & ViewController as:

@IBOutlet weak var panVerificationUIView:ClickableUIView!

Why am I getting "void value not ignored as it ought to be"?

The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)


error: void value not ignored as it ought to be

This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.

Example:

void myFunction()
{
   //...stuff...
}

int main()
{
   int myInt = myFunction(); //Compile error!

    return 0;
}

You aren't allowed to assign void to integers, or any other type.

In the OP's situation:

int a = srand(time(NULL));

...is not allowed. srand(), according to the documentation, returns void.

This question is a duplicate of:

I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.

Concatenate two NumPy arrays vertically

A not well known feature of numpy is to use r_. This is a simple way to build up arrays quickly:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]

The purpose of a[None,:] is to add an axis to array a.

String literals and escape characters in postgresql

The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.

AndroidStudio: Failed to sync Install build tools

I had the same issue, with Build Tools revision 24.0.0-rc4. The fix was to install the package using the command line.

~/Android/Sdk| ls -1 build-tools/
23.0.3
24.0.0-rc4
~/Android/Sdk| ./tools/android list sdk -a | grep "SDK Build-tools"
   4- Android SDK Build-tools, revision 24 rc4
   5- Android SDK Build-tools, revision 23.0.3
   6- Android SDK Build-tools, revision 23.0.2
   7- Android SDK Build-tools, revision 23.0.1
   8- Android SDK Build-tools, revision 23 (Obsolete)
   ...
~/Android/Sdk| ./tools/android update sdk -a -u -t 4
   ...
~/Android/Sdk| ls -1 build-tools/
23.0.3
24.0.0-preview
24.0.0-rc4

(note that 4 in the android update sdk command above refers to the preceding list's number for the desired version, found at the beginning of the line).

The directory build-tools/24.0.0-rc4/ had been created when I installed the package from Android Studio's SDK Manager. The above method created build-tools/24.0.0-preview/.

My app-level build.gradle script uses the -rc4 version, as specified in the setup guide:

android {
    compileSdkVersion 'android-N'
    buildToolsVersion '24.0.0-rc4'
}

I do not understand the correlation between -rc4 and -preview or why specifying 24.0.0-rc4 picks up the -preview package, but it did fix the issue for me.

How to add 10 days to current time in Rails

This definitely works and I use this wherever I need to add days to the current date:

Date.today + 5

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

Rails Root directory path?

In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

Rails.root + '/app/assets/...'

You could use something like join

Rails.root.join('app', 'assets')

If you want a string use this:

Rails.root.join('app', 'assets').to_s

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

After so much time i got it solved this way

My laravel installation path was not the same as set in the config file session.php

'domain' => env('SESSION_DOMAIN', 'example.com'),

Using the "animated circle" in an ImageView while loading stuff

For the ones developing in Kotlin, there is a sweet method provided by the Anko library that makes the process of displaying a ProgressDialog a breeze!

Based on that link:

val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
dialog.show()
//....
dialog.dismiss()

This will show a Progress Dialog with the progress % displayed (for which you have to pass the init parameter also to calculate the progress).

There is also the indeterminateProgressDialog() method, which provides the Spinning Circle animation indefinitely until dismissed:

indeterminateProgressDialog("Loading...").show()

Shout out to this blog which led me to this solution.

Removing rounded corners from a <select> element in Chrome/Webkit

One way to keep it simple and avoid messing with the arrows and other such features is just to house it in a div with the same background color as the select tag.

Detecting an undefined object property

This is probably the only explicit form of determining if the existing property-name has an explicit and intended value of undefined; which is, nonetheless, a JavaScript type.

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true \ false

This expression will only return true if the property name of the given context exists (truly) and only if its intended value is explicitly undefined.

There will be no false positives like with empty or blank strings zeros nulls or empty arrays and alike. This does exactly that. Checks i.e., makes sure the property name exists (otherwise it would be a false positive), than it explicitly checks if its value is undefined e.g. of an undefined JavaScript type in it's string representation form (literally "undefined") therefore == instead of === because no further conversion is possible. And this expression will only return true if both, that is all conditions are met. E.g. if the property-name doesn't exist, - it will return false. Which is the only correct return since nonexistent properties can't have values, not even an undefined one.

Example:

containerObject = { propertyName: void "anything" }
>> Object { propertyName: undefined }

// Now the testing

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true

/* Which makes sure that nonexistent property will not return a false positive
 * unless it is previously defined  */

"foo" in containerObject && ""+containerObject["foo"] == "undefined";
>> false

In JPA 2, using a CriteriaQuery, how to count results

As others answers are correct, but too simple, so for completeness I'm presenting below code snippet to perform SELECT COUNT on a sophisticated JPA Criteria query (with multiple joins, fetches, conditions).

It is slightly modified this answer.

public <T> long count(final CriteriaBuilder cb, final CriteriaQuery<T> selectQuery,
        Root<T> root) {
    CriteriaQuery<Long> query = createCountQuery(cb, selectQuery, root);
    return this.entityManager.createQuery(query).getSingleResult();
}

private <T> CriteriaQuery<Long> createCountQuery(final CriteriaBuilder cb,
        final CriteriaQuery<T> criteria, final Root<T> root) {

    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<T> countRoot = countQuery.from(criteria.getResultType());

    doJoins(root.getJoins(), countRoot);
    doJoinsOnFetches(root.getFetches(), countRoot);

    countQuery.select(cb.count(countRoot));
    countQuery.where(criteria.getRestriction());

    countRoot.alias(root.getAlias());

    return countQuery.distinct(criteria.isDistinct());
}

@SuppressWarnings("unchecked")
private void doJoinsOnFetches(Set<? extends Fetch<?, ?>> joins, Root<?> root) {
    doJoins((Set<? extends Join<?, ?>>) joins, root);
}

private void doJoins(Set<? extends Join<?, ?>> joins, Root<?> root) {
    for (Join<?, ?> join : joins) {
        Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
        joined.alias(join.getAlias());
        doJoins(join.getJoins(), joined);
    }
}

private void doJoins(Set<? extends Join<?, ?>> joins, Join<?, ?> root) {
    for (Join<?, ?> join : joins) {
        Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
        joined.alias(join.getAlias());
        doJoins(join.getJoins(), joined);
    }
}

Hope it saves somebody's time.

Because IMHO JPA Criteria API is not intuitive nor quite readable.

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

"Please provide a valid cache path" error in laravel

My 2 cents

Remove everything inside storage and then do this:

> cd storage/
> mkdir -p framework/{sessions,views,cache}
> chmod -R 777 framework

// This last line depends on your user group settings so 
// it may not be applicable to you.
> chown -R www-data:www-data framework

Worked for me =)

Loop code for each file in a directory

Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.

$directory = 'my_directory/';
$extension = '.txt';

if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn\'t exist!';
}

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

How to sort an associative array by its values in Javascript?

Instead of correcting you on the semantics of an 'associative array', I think this is what you want:

function getSortedKeys(obj) {
    var keys = keys = Object.keys(obj);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

for really old browsers, use this instead:

function getSortedKeys(obj) {
    var keys = []; for(var key in obj) keys.push(key);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

You dump in an object (like yours) and get an array of the keys - eh properties - back, sorted descending by the (numerical) value of the, eh, values of the, eh, object.

This only works if your values are numerical. Tweek the little function(a,b) in there to change the sorting mechanism to work ascending, or work for string values (for example). Left as an exercise for the reader.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

On Windows:

  1. Add USER Environment variables:

NOTE: Path should be appended

JAVA_HOME           %ProgramFiles%\Android\Android Studio\jre
ANDROID_SDK_ROOT    %LocalAppData%\Android\Sdk
Path                %LocalAppData%\Android\Sdk
  1. Run the below command to accept licenses:

NOTE: Accept all licenses (say y)

%ANDROID_SDK_ROOT%/tools/bin/sdkmanager.bat --licenses
  1. Now run your app:

(like below, or another command that failed for you):

cd \myapp\
react-native run-android

How to resolve "Server Error in '/' Application" error?

You may get this error when trying to browse an ASP.NET application.

The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."

However, this error occurs primarily out of two scenarios.

  1. When you create an new web application using Visual Studio .NET, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

  1. When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly, we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).

How do I set the selected item in a drop down box

This is the solution that I came up with...

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">   
    <select name="select_month">
        <?php
            if (isset($_POST['select_month'])) {
                if($_POST["select_month"] == "January"){
                    echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
                }
                elseif($_POST["select_month"] == "February"){
                    echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
                }
            }
            else{
                echo '<option value="January">January</option><option value="February">February</option>';
            }
        ?>
    </select>
    <input name="submit_button" type="submit" value="Search Month">
</form>

How can I read a large text file line by line using Java?

You need to use the readLine() method in class BufferedReader. Create a new object from that class and operate this method on him and save it to a string.

BufferReader Javadoc

Open Cygwin at a specific folder

When a fresh install is needed, I create a Windows "user environment variable " named HOME and assigns it the path of wherever "My Documents" reside.

The cygwin installer detects the HOME variable, automatically translates this into a cygpath and selects this it to be my ~ directory.

This has worked fine for every workstation I have used professionally the last 5 years (about 3 or 4, Win7). I have always been the only user on these machines, cannot say what the effect is.

Why don’t my SVG images scale using the CSS "width" property?

Open SVG using any text editor and remove width and height attributes from the root node.

Before

<svg width="12px" height="20px" viewBox="0 0 12 20" ...

After

<svg viewBox="0 0 12 20" ...

Now the image will always fill all the available space and will scale using CSS width and height. It will not stretch though so it will only grow to available space.

JavaFX Panel inside Panel auto resizing

If you are using Scene Builder, you will see at the right an accordion panel which normally has got three options ("Properties", "Layout" and "Code"). In the second one ("Layout"), you will see an option called "[parent layout] Constraints" (in your case "AnchorPane Constrainsts").

You should put "0" in the four sides of the element wich represents the parent layout.

Embedding VLC plugin on HTML page

I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/

function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =  
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' + 
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr + 
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */

Greets

Gee

I reduce the whole crap now to:

function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};

Didn't get it to work in ie as well... 2b continued...

Greets

Gee

Why write <script type="text/javascript"> when the mime type is set by the server?

Because, at least in HTML 4.01 and XHTML 1(.1), the type attribute for <script> elements is required.

In HTML 5, type is no longer required.

In fact, while you should use text/javascript in your HTML source, many servers will send the file with Content-type: application/javascript. Read more about these MIME types in RFC 4329.

Notice the difference between RFC 4329, that marked text/javascript as obsolete and recommending the use of application/javascript, and the reality in which some browsers freak out on <script> elements containing type="application/javascript" (in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type defaults to text/javascript), read these messages with subject Will you consider about RFC 4329?

Difference between View and ViewGroup in Android

In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.

How to write text in ipython notebook?

Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:

Esc then m then Enter so that you gain focus again and can start typing.

Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.

Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.

You can then move on to your next cells. :)

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

for each project in your solution make sure that

Properties > Config. Properties > General > Platform Toolset

is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012

you also may be working on v100 from visual studio 2012

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

How to return a html page from a restful controller in spring boot?

@Controller
public class HomeController {

    @RequestMapping(method = RequestMethod.GET, value = "/")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login.html");
        return modelAndView;
    }
}

This will return the Login.html File. The Login.html should be inside the static Folder.

Note: thymeleaf dependency is not added

@RestController
public class HomeController {

    @RequestMapping(method = RequestMethod.GET, value = "/")
    public String welcome() {
        return "login";
    }
}

This will return the String login

How to hide status bar in Android

Use this code for hiding the status bar in your app and easy to use

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Change Project Namespace in Visual Studio

Right click properties, Application tab, then see the assembly name and default namespace

Can Javascript read the source of any web page?

You can use fetch:

_x000D_
_x000D_
const URL = 'https://www.sap.com/belgique/index.html';
fetch(URL)
.then(res => res.text())
.then(text => {
    console.log(text);
})
.catch(err => console.log(err));
_x000D_
_x000D_
_x000D_

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

Amazon Interview Question: Design an OO parking lot

Here is a quick start to get the gears turning...

ParkingLot is a class.

ParkingSpace is a class.

ParkingSpace has an Entrance.

Entrance has a location or more specifically, distance from Entrance.

ParkingLotSign is a class.

ParkingLot has a ParkingLotSign.

ParkingLot has a finite number of ParkingSpaces.

HandicappedParkingSpace is a subclass of ParkingSpace.

RegularParkingSpace is a subclass of ParkingSpace.

CompactParkingSpace is a subclass of ParkingSpace.

ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.

ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()

Parker is a class.

Parker can Park().

Parker can Unpark().

Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.

Parker has a ParkingSpace.

Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().

Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().

HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)

In this solution, it is possible that Parker should be renamed to be Car.

sqlite copy data from one table to another

INSERT INTO Destination SELECT * FROM Source;

See SQL As Understood By SQLite: INSERT for a formal definition.

Darkening an image with CSS (In any shape)

Webkit only solution

Quick solution, relies on the -webkit-mask-image property. -webkit-mask-image sets a mask image for an element.

There are a few gotchas with this method:

  • Obviously, only works in Webkit browsers
  • Requires an additional wrapper to apply the :after psuedo-element (IMG tags can't have :before/:after pseudo elements, grr)
  • Because there's an additional wrapper, I'm not sure how to use the attr(…) CSS function to get the IMG tag URL, so it's hard-coded into the CSS separately.

If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).

How to save public key from a certificate in .pem format

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

Bound method error

For this thing you can use @property as an decorator, so you could use instance methods as attributes. For example:

class Word_Parser:
    def __init__(self, sentences):
        self.sentences = sentences

    @property
    def parser(self):
        self.word_list = self.sentences.split()

    @property
    def sort_word_list(self):
        self.sorted_word_list = self.word_list.sort()

    @property
    def num_words(self):
        self.num_words = len(self.word_list)

test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words

so you can use access the attributes without calling (i.e., without the ()).

How to change the URL from "localhost" to something else, on a local system using wampserver?

for new version of Wamp

<VirtualHost *:80>
  ServerName domain.local
  DocumentRoot C:/wamp/www/domain/
  <Directory "C:/wamp/www/domain/">
      Options +Indexes +FollowSymLinks +MultiViews
      AllowOverride All
      Require local
  </Directory>
</VirtualHost>

How do I make a simple crawler in PHP?

It's an old question. A lot of good things happened since then. Here are my two cents on this topic:

  1. To accurately track the visited pages you have to normalize URI first. The normalization algorithm includes multiple steps:

    • Sort query parameters. For example, the following URIs are equivalent after normalization: GET http://www.example.com/query?id=111&cat=222 GET http://www.example.com/query?cat=222&id=111
    • Convert the empty path. Example: http://example.org ? http://example.org/

    • Capitalize percent encoding. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive. Example: http://example.org/a%c2%B1b ? http://example.org/a%C2%B1b

    • Remove unnecessary dot-segments. Example: http://example.org/../a/b/../c/./d.html ? http://example.org/a/c/d.html

    • Possibly some other normalization rules

  2. Not only <a> tag has href attribute, <area> tag has it too https://html.com/tags/area/. If you don't want to miss anything, you have to scrape <area> tag too.

  3. Track crawling progress. If the website is small, it is not a problem. Contrarily it might be very frustrating if you crawl half of the site and it failed. Consider using a database or a filesystem to store the progress.

  4. Be kind to the site owners. If you are ever going to use your crawler outside of your website, you have to use delays. Without delays, the script is too fast and might significantly slow down some small sites. From sysadmins perspective, it looks like a DoS attack. A static delay between the requests will do the trick.

If you don't want to deal with that, try Crawlzone and let me know your feedback. Also, check out the article I wrote a while back https://www.codementor.io/zstate/this-is-how-i-crawl-n98s6myxm

Error importing SQL dump into MySQL: Unknown database / Can't create database

It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.

Android Studio gradle takes too long to build

In Android Studio go to File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle

(if on mac) Android Studio -> preferences... -> Build, Execution, Deployment -> Build Tools -> Gradle

Check the 'Offline work' under 'Global Gradle settings'

Note: In newer version of Android studio, View->Tool Windows->Gradle->Toggle button of online/offline

It will reduce 90% gradle build time.

check this to reduce build time

if you just added a new dependency in your gradle you will have to uncheck the offline work or gradle will not be able to resolve the dependencies. After the complete resolving then you you can check the offline work for a faster build

Powershell folder size of folders without listing Subdirectories

The solution posted by @Linga: "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum" is nice and short. However, it only computes the size of 'directory_path', without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File option to avoid errors for empty sub-directories)

foreach ($d in gci -Directory -Force) {
  '{0:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d" 
}

How to open Visual Studio Code from the command line on OSX?

I have a ~/bin/code shell script that matches the command @BengaminPasero wrote.

#!/bin/bash
VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*

I prefix ~/bin: to my $PATH which allows me to add a bunch of one off scripts without polluting my ~/.bash_profile script.

Eclipse : Failed to connect to remote VM. Connection refused.

  • The port number in the Eclipse configuration and the port number of your application might not be the same.
  • You might not have been started your application with the right parameters.

    Those are the simple problems when I have faced "Connection refused" error.

How does one generate a random number in Apple's Swift language?

 let MAX : UInt32 = 9
 let MIN : UInt32 = 1

    func randomNumber()
{
    var random_number = Int(arc4random_uniform(MAX) + MIN)
    print ("random = ", random_number);
}

How to make layout with View fill the remaining space?

When using a relative layout, you can make a view stretch by anchoring it to both of the views it's supposed to stretch toward. Although the specified height will be disregarded, Android still requires a height attribute, which is why I wrote "0dp". Example:

<View
    android:id="@+id/topView"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="8dp"/>

<View
    android:id="@+id/stretchableView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_below="@id/topView"
    android:layout_above="@+id/bottomView"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:adjustViewBounds="true"/>

<View
    android:id="@id/bottomView"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="16dp"/>