Programs & Examples On #Curve

In mathematics, a curve (also called a curved line in older texts) is, generally speaking, an object similar to a line but which is not required to be straight.

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Could not load file or assembly 'Microsoft.Web.Infrastructure,

I don't know what happened with my project but it referenced the wrong path to the DLL. Nuget installed it properly and it was indeed on my file system along with the other packages but just referenced incorrectly.

The packages folder exists two directories up from my project and it was only going up one by starting the path with ..\packages\. I changed the path to start with ..\..\packages\ and it fixed my problem.

Set width of a "Position: fixed" div relative to parent div

Use this CSS:

#container {
    width: 400px;
    border: 1px solid red;
}

#fixed {
    position: fixed;
    width: inherit;
    border: 1px solid green;
}

The #fixed element will inherit it's parent width, so it will be 100% of that.

isset in jQuery?

if (($("#one").length > 0)){
   alert('yes');
}

if (($("#two").length > 0)){
   alert('yes');
}

if (($("#three").length > 0)){
   alert('yes');
}

if (($("#four")).length == 0){
   alert('no');
}

This is what you need :)

How to get the anchor from the URL using jQuery?

For current window, you can use this:

var hash = window.location.hash.substr(1);

To get the hash value of the main window, use this:

var hash = window.top.location.hash.substr(1);

If you have a string with an URL/hash, the easiest method is:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

var hash = $(location).attr('hash');

Efficient evaluation of a function at every cell of a NumPy array

If you are working with numbers and f(A(i,j)) = f(A(j,i)), you could use scipy.spatial.distance.cdist defining f as a distance between A(i) and A(j).

Random color generator

Use distinct-colors.

It generates a palette of visually distinct colors.

distinct-colors is highly configurable:

  • Choose how many colors are in the palette
  • Restrict the hue to a specific range
  • Restrict the chroma (saturation) to a specific range
  • Restrict the lightness to a specific range
  • Configure general quality of the palette

How to check if a specified key exists in a given S3 bucket using Java

Using the AWS SDK use the getObjectMetadata method. The method will throw an AmazonServiceException if the key doesn't exist.

private AmazonS3 s3;
...
public boolean exists(String path, String name) {
    try {
        s3.getObjectMetadata(bucket, getS3Path(path) + name); 
    } catch(AmazonServiceException e) {
        return false;
    }
    return true;
}

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

What is the purpose of Android's <merge> tag in XML layouts?

blazeroni already made it pretty clear, I just want to add few points.

  • <merge> is used for optimizing layouts.It is used for reducing unnecessary nesting.
  • when a layout containing <merge> tag is added into another layout,the <merge> node is removed and its child view is added directly to the new parent.

Why is Git better than Subversion?

Git also makes branching and merging really easy. Subversion 1.5 just added merge tracking, but Git is still better. With Git branching is very fast and cheap. It makes creating a branch for each new feature more feasible. Oh and Git repositories are very efficient with storage space as compared to Subversion.

Open Sublime Text from Terminal in macOS

I achieve this with just one line in terminal (with Sublime 3):

alias subl='/usr/local/bin/sublime'

How to compare numbers in bash?

Like this:

#!/bin/bash

a=2462620
b=2462620

if [ "$a" -eq "$b" ]; then
  echo "They're equal";
fi

Integers can be compared with these operators:

-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal

See this cheatsheet: https://devhints.io/bash#conditionals

Get table names using SELECT statement in MySQL

This below query worked for me. This can able to show the databases,tables,column names,data types and columns count.

**select table_schema Schema_Name ,table_name TableName,column_name ColumnName,ordinal_position "Position",column_type DataType,COUNT(1) ColumnCount
FROM information_schema.columns
GROUP by table_schema,table_name,column_name,ordinal_position, column_type;**

Python Dictionary contains List as Value - How to update?

dictionary["C1"]=map(lambda x:x+10,dictionary["C1"]) 

Should do it...

How to tell if homebrew is installed on Mac OS X

use either the which or type built-in tools.

i.e.: which brew or type brew

Google reCAPTCHA: How to get user response and validate in the server side?

Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:

 <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
 <span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) {

var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
 if(v.length != 0)
 {
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
 }
}

Can you call ko.applyBindings to bind a partial view?

ko.applyBindings accepts a second parameter that is a DOM element to use as the root.

This would let you do something like:

<div id="one">
  <input data-bind="value: name" />
</div>

<div id="two">
  <input data-bind="value: name" />
</div>

<script type="text/javascript">
  var viewModelA = {
     name: ko.observable("Bob")
  };

  var viewModelB = {
     name: ko.observable("Ted")
  };

  ko.applyBindings(viewModelA, document.getElementById("one"));
  ko.applyBindings(viewModelB, document.getElementById("two"));
</script>

So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings multiple times on the same elements, as you will get multiple event handlers attached.

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

How to match "any character" in regular expression?

No, * will match zero-or-more characters. You should use +, which matches one-or-more instead.

This expression might work better for you: [A-Z]+123

How do I compare 2 rows from the same table (SQL Server)?

SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a

If you got two rows, they different, if one - the same.

shuffling/permutating a DataFrame in pandas

This might be more useful when you want your index shuffled.

def shuffle(df):
    index = list(df.index)
    random.shuffle(index)
    df = df.ix[index]
    df.reset_index()
    return df

It selects new df using new index, then reset them.

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

Java8: sum values from specific field of the objects in a list

You can do this method: "IntSummaryStatistics"

IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();

How to send a GET request from PHP?

In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:

https://github.com/romanpitak/PHP-REST-Client

So, getting the xml file:

$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

regular expression to validate datetime format (MM/DD/YYYY)

The answer marked is perfect but for one scenario, where in the dd and mm are actually single digits. the following regex is perfect in this case:

_x000D_
_x000D_
    function validateDate(testdate) {_x000D_
        var date_regex = /^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;_x000D_
        return date_regex.test(testdate);_x000D_
    }
_x000D_
_x000D_
_x000D_

How do I find all files containing specific text on Linux?

grep (GNU or BSD)

You can use grep tool to search recursively the current folder, like:

grep -r "class foo" .

Note: -r - Recursively search subdirectories.

You can also use globbing syntax to search within specific files such as:

grep "class foo" **/*.c

Note: By using globbing option (**), it scans all the files recursively with specific extension or pattern. To enable this syntax, run: shopt -s globstar. You may also use **/*.* for all files (excluding hidden and without extension) or any other pattern.

If you've the error that your argument is too long, consider narrowing down your search, or use find syntax instead such as:

find . -name "*.php" -execdir grep -nH --color=auto foo {} ';'

Alternatively, use ripgrep.

ripgrep

If you're working on larger projects or big files, you should use ripgrep instead, like:

rg "class foo" .

Checkout the docs, installation steps or source code on the GitHub project page.

It's much quicker than any other tool like GNU/BSD grep, ucg, ag, sift, ack, pt or similar, since it is built on top of Rust's regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast.

It supports ignore patterns specified in .gitignore files, so a single file path can be matched against multiple glob patterns simultaneously.


You can use common parameters such as:

  • -i - Insensitive searching.
  • -I - Ignore the binary files.
  • -w - Search for the whole words (in the opposite of partial word matching).
  • -n - Show the line of your match.
  • -C/--context (e.g. -C5) - Increases context, so you see the surrounding code.
  • --color=auto - Mark up the matching text.
  • -H - Displays filename where the text is found.
  • -c - Displays count of matching lines. Can be combined with -H.

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

How can I iterate over files in a given directory?

You can try using glob module:

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

and since Python 3.5 you can search subdirectories as well:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

From the docs:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

Oracle SQL : timestamps in where clause

For everyone coming to this thread with fractional seconds in your timestamp use:

to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')

AngularJS routing without the hash '#'

The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag For Example:

There are 2 things that need to be done.

  • Configuring $locationProvider

  • Setting our base for relative links

  • $location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.

https://docs.angularjs.org/api/ng/service/$location

$locationProvider and html5Mode

  • We will use the $locationProvider module and set html5Mode to true.
  • We will do this when defining your Angular application and configuring your routes.

    angular.module('noHash', [])
    
    .config(function($routeProvider, $locationProvider) {
    
       $routeProvider
           .when('/', {
               templateUrl : 'partials/home.html',
               controller : mainController
           })
           .when('/about', {
               templateUrl : 'partials/about.html',
               controller : mainController
           })
           .when('/contact', {
               templateUrl : 'partials/contact.html',
               controller : mainController
           });
    
       // use the HTML5 History API
       $locationProvider.html5Mode(true); });
    

What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:

http://diveintohtml5.info/history.html

Setting For Relative Links

  • To link around your application using relative links, you will need to set the <base> in the <head> of your document. This may be in the root index.html file of your Angular app. Find the <base> tag, and set it to the root URL you'd like for your app.

For example: <base href="/">

  • There are plenty of other ways to configure this, and the HTML5 mode set to true should automatically resolve relative links. If your root of your application is different than the url (for instance /my-base, then use that as your base.

Fallback for Older Browsers

  • The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
  • This happens transparently to you and you won’t have to configure anything for it to work. From the Angular $location docs, you can see the fallback method and how it works.

In Conclusion

  • This is a simple way to get pretty URLs and remove the hashtag in your Angular application. Have fun making those super clean and super fast Angular apps!

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

 if(Auth::check() && Auth::user()->role->id == 2){ 
         $tags = Tag::latest()->get();
        return view('admin.tag.index',compact('tags'));
    }

RSA encryption and decryption in Python

Here is my implementation for python 3 and pycrypto

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)

C# adding a character in a string

Remember a string is immutable so you will need to create a new string.

Strings are IEnumerable so you should be able to run a for loop over it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            var builder = new StringBuilder();
            int count = 0;
            foreach (var c in alpha)
            {
                builder.Append(c);
                if ((++count % 5) == 0)
                {
                    builder.Append('-');
                }
            }
            Console.WriteLine("Before: {0}", alpha);
            alpha = builder.ToString();
            Console.WriteLine("After: {0}", alpha);
        }
    }
}

Produces this:

Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z

\n or \n in php echo not print

PHP only interprets escaped characters (with the exception of the escaped backslash \\ and the escaped single quote \') when in double quotes (")

This works (results in a newline):

"\n"

This does not result in a newline:

'\n'

How to delete cookies on an ASP.NET website

This is what I use:

    private void ExpireAllCookies()
    {
        if (HttpContext.Current != null)
        {
            int cookieCount = HttpContext.Current.Request.Cookies.Count;
            for (var i = 0; i < cookieCount; i++)
            {
                var cookie = HttpContext.Current.Request.Cookies[i];
                if (cookie != null)
                {
                    var expiredCookie = new HttpCookie(cookie.Name) {
                        Expires = DateTime.Now.AddDays(-1),
                        Domain = cookie.Domain
                    };
                    HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
                }
            }

            // clear cookies server side
            HttpContext.Current.Request.Cookies.Clear();
        }
    }

Multiple models in a view

Use a view model that contains multiple view models:

   namespace MyProject.Web.ViewModels
   {
      public class UserViewModel
      {
          public UserDto User { get; set; }
          public ProductDto Product { get; set; }
          public AddressDto Address { get; set; }
      }
   }

In your view:

  @model MyProject.Web.ViewModels.UserViewModel

  @Html.LabelFor(model => model.User.UserName)
  @Html.LabelFor(model => model.Product.ProductName)
  @Html.LabelFor(model => model.Address.StreetName)

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

How to get only time from date-time C#

You can use this

lblTime.Text = DateTime.Now.TimeOfDay.ToString(); 

It is realtime with milliseconds value and it sets to time only.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

You need to setup a SDK for Java projects, like @rizzletang said, but you don't need to create a new project, you can do it from the Welcome screen.

On the bottom right, select Configure > Project Defaults > Project Structure: enter image description here

Picking the Project tab on the left will show that you have no SDK selected:

enter image description here

Just click the New... button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should just show up.

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.

<PropertyGroup>
  <Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>

<ItemGroup>
  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>

<Target Name="GenerateNetcoreExe"
        AfterTargets="Build"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
  <Exec
    ConsoleToMSBuild="true"
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
  </Exec>
  <Copy
    SourceFiles="@(BootStrapFiles)"
    DestinationFolder="$(OutputPath)"
  />

</Target>

I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole

TypeError: 'list' object cannot be interpreted as an integer

since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.

use this

for i in range(len(myList)):

with this, we get the singular integer value which can be used easily

jQuery - Sticky header that shrinks when scrolling down

Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.

JS:

$(window).on("scroll touchmove", function () {
  $('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});

CSS:

.header {
  width:100%;
  height:100px;
  background: #26b;
  color: #fff;
  position:fixed;
  top:0;
  left:0;
  transition: height 500ms, background 500ms;
}
.header.tiny {
  height:40px;
  background: #aaa;
}

http://jsfiddle.net/sinky/S8Fnq/

On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.

CSS transition attribute animates the "height" and "background" attribute nicely.

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

Applying a single font to an entire website with CSS

in Bootstrap, web inspector says the Headings are set to 'inherit'

all i needed to set my page to the new font was

div, p {font-family: Algerian}

that's in .scss

Return index of highest value in an array

Something like this should do the trick

function array_max_key($array) {
  $max_key = -1;
  $max_val = -1;

  foreach ($array as $key => $value) {
    if ($value > $max_val) {
      $max_key = $key;
      $max_val = $value;
    }
  }

  return $max_key;
}

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

This is a problem not specific to java. Using == to compare two floats/doubles/any decimal type number can potentially cause problems because of the way they are stored. A single-precision float (as per IEEE standard 754) has 32 bits, distributed as follows:

1 bit - Sign (0 = positive, 1 = negative)
8 bits - Exponent (a special (bias-127) representation of the x in 2^x)
23 bits - Mantisa. The actuall number that is stored.

The mantisa is what causes the problem. It's kinda like scientific notation, only the number in base 2 (binary) looks like 1.110011 x 2^5 or something similar. But in binary, the first 1 is always a 1 (except for the representation of 0)

Therefore, to save a bit of memory space (pun intended), IEEE deccided that the 1 should be assumed. For example, a mantisa of 1011 really is 1.1011.

This can cause some issues with comparison, esspecially with 0 since 0 cannot possibly be represented exactly in a float. This is the main reason the == is discouraged, in addition to the floating point math issues described by other answers.

Java has a unique problem in that the language is universal across many different platforms, each of which could have it's own unique float format. That makes it even more important to avoid ==.

The proper way to compare two floats (not-language specific mind you) for equality is as follows:

if(ABS(float1 - float2) < ACCEPTABLE_ERROR)
    //they are approximately equal

where ACCEPTABLE_ERROR is #defined or some other constant equal to 0.000000001 or whatever precision is required, as Victor mentioned already.

Some languages have this functionality or this constant built in, but generally this is a good habit to be in.

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

What does the 'b' character do in front of a string literal?

To quote the Python 2.x documentation:

A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.

The Python 3 documentation states:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

Markdown and including multiple files

The short answer is no. The long answer is yes. :-)

Markdown was designed to allow people to write simple, readable text that could be easily converted to a simple HTML markup. It doesn't really do document layout. For example, there's no real way to align an image to the right or left. As to your question, there's no markdown command to include a single link from one file to another in any version of markdown (so far as I know).

The closest you could come to this functionality is Pandoc. Pandoc allows you to merge files as a part of the transformation, which allows you to easily render multiple files into a single output. For example, if you were creating a book, then you could have chapters like this:

01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md

You can merge them by doing executing this command within the same directory:

pandoc *.md > markdown_book.html

Since pandoc will merge all the files prior to doing the translation, you can include your links in the last file like this:

01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md
06_links.md

So part of your 01_preface.md could look like this:

I always wanted to write a book with [markdown][mkdnlink].

And part of your 02_introduction.md could look like this:

Let's start digging into [the best text-based syntax][mkdnlink] available.

As long as your last file includes the line:

[mkdnlink]: http://daringfireball.net/projects/markdown

...the same command used before will perform the merge and conversion while including that link throughout. Just make sure you leave a blank line or two at the beginning of that file. The pandoc documentation says that it adds a blank line between files that are merged this way, but this didn't work for me without the blank line.

How to see the changes in a Git commit?

From the man page for git-diff(1):

git diff [options] [<commit>] [--] [<path>…]
git diff [options] --cached [<commit>] [--] [<path>…]
git diff [options] <commit> <commit> [--] [<path>…]
git diff [options] <blob> <blob>
git diff [options] [--no-index] [--] <path> <path>

Use the 3rd one in the middle:

git diff [options] <parent-commit> <commit>

Also from the same man page, at the bottom, in the Examples section:

$ git diff HEAD^ HEAD      <3>

Compare the version before the last commit and the last commit.

Admittedly it's worded a little confusingly, it would be less confusing as

Compare the most recent commit with the commit before it.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Try this code to watch for, and report, a possible net::ERR_INSECURE_RESPONSE

I was having this issue as well, using a self-signed certificate, which I have chosen not to save into the Chrome Settings. After accessing the https domain and accepting the certificate, the ajax call works fine. But once that acceptance has timed-out or before it has first been accepted, the jQuery.ajax() call fails silently: the timeout parameter does not seem help and the error() function never gets called.

As such, my code never receives a success() or error() call and therefore hangs. I believe this is a bug in jquery's handling of this error. My solution is to force the error() call after a specified timeout.

This code does assume a jquery ajax call of the form jQuery.ajax({url: required, success: optional, error: optional, others_ajax_params: optional}).

Note: You will likely want to change the function within the setTimeout to integrate best with your UI: rather than calling alert().

const MS_FOR_HTTPS_FAILURE = 5000;
$.orig_ajax = $.ajax;
$.ajax = function(params)
{
  var complete = false;
  var success = params.success;
  var error = params.error;
  params.success = function() {
    if(!complete) {
      complete = true;
      if(success) success.apply(this,arguments);
    }
  }
  params.error = function() {
    if(!complete) {
      complete = true;
      if(error) error.apply(this,arguments);
    }
  }
  setTimeout(function() {
    if(!complete) {
      complete = true;
      alert("Please ensure your self-signed HTTPS certificate has been accepted. "
        + params.url);
      if(params.error)
        params.error( {},
          "Connection failure",
          "Timed out while waiting to connect to remote resource. " +
          "Possibly could not authenticate HTTPS certificate." );
    }
  }, MS_FOR_HTTPS_FAILURE);

  $.orig_ajax(params);
}

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;

you might want to use CEIL() if A is always a floating point value > 0 and <= 2

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

How to Merge Two Eloquent Collections?

All do not work for me on eloquent collections, laravel eloquent collections use the key from the items I think which causes merging issues, you need to get the first collection back as an array, put that into a fresh collection and then push the others into the new collection;

public function getFixturesAttribute()
{
    $fixtures = collect( $this->homeFixtures->all() );
    $this->awayFixtures->each( function( $fixture ) use ( $fixtures ) {
        $fixtures->push( $fixture );
    });
    return $fixtures;
}

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

"ABCDEFG".split("").each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split("").each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

"ABCDEFG".each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

Copy mysql database from remote server to local computer

Please check this gist.

https://gist.github.com/ecdundar/789660d830d6d40b6c90

#!/bin/bash

# copymysql.sh

# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200

MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"

REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "

LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "

IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema'  ;"

# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`

# COPY ALL TABLES
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
    IGNOREVIEWS=""
    for view in $views; do
        IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view " 
    done
    echo "TABLES "$db
    $MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
    $MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert  --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction  $db | mysql $LOCALCONNECTION  $db 
done

# COPY ALL PROCEDURES
for db in $databases; do
    echo "PROCEDURES "$db
    #PROCEDURES
    $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL TRIGGERS
for db in $databases; do
    echo "TRIGGERS "$db
    #TRIGGERS
    $MYSQLDUMP $REMOTECONNECTIONSTR  --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL VIEWS
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
    MYVIEWS=""
    for view in $views; do
        MYVIEWS=${MYVIEWS}" "$view" " 
    done
    echo "VIEWS "$db    
    if [ -n "$MYVIEWS" ]; then
      #VIEWS
      $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
      sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g'  | mysql $LOCALCONNECTION  $db  
    fi    
done

echo   "OK!"

Draw a connecting line between two elements

Joining lines with svgs was worth a shot for me, and it worked perfectly... first of all, Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. SVG images and their behaviors are defined in XML text files. you can create an svg in HTML using <svg> tag. Adobe Illustrator is one of the best software used to create an complex svgs using paths.

Procedure to join two divs using a line :

  1. create two divs and give them any position as you need

    <div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>
    <div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>
    

    (for the sake of explanation I am doing some inline styling but it is always good to make a separate css file for styling)

  2. <svg><line id="line1"/></svg>

    Line tag allows us to draw a line between two specified points(x1,y1) and (x2,y2). (for a reference visit w3schools.) we haven't specified them yet. because we will be using jQuery to edit the attributes (x1,y1,x2,y2) of line tag.

  3. in <script> tag write

    line1 = $('#line1');   
    div1 = $('#div1');   
    div2 = $('#div2');
    

    I used selectors to select the two divs and line...

    var pos1 = div1.position();
    var pos2 = div2.position();
    

    jQuery position() method allows us to obtain the current position of an element. For more information, visit https://api.jquery.com/position/ (you can use offset() method too)

Now as we have obtained all the positions we need we can draw line as follows...

line1
  .attr('x1', pos1.left)
  .attr('y1', pos1.top)
  .attr('x2', pos2.left)
  .attr('y2', pos2.top);

jQuery .attr() method is used to change attributes of the selected element.

All we did in above line is we changed attributes of line from

x1 = 0
y1 = 0
x2 = 0
y2 = 0

to

x1 = pos1.left
y1 = pos1.top
x2 = pos2.left
y2 = pos2.top

as position() returns two values, one 'left' and other 'top', we can easily access them using .top and .left using the objects (here pos1 and pos2) ...

Now line tag has two distinct co-ordinates to draw line between two points.

Tip: add event listeners as you need to divs

Tip: make sure you import jQuery library first before writing anything in script tag

After adding co-ordinates through JQuery ... It will look something like this

Following snippet is for demonstration purpose only, please follow steps above to get correct solution

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="50" stroke="red"/></svg>
_x000D_
_x000D_
_x000D_

How to construct a REST API that takes an array of id's for the resources

 api.com/users?id=id1,id2,id3,id4,id5
 api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.

RESTful attempt:

POST http://example.com/api/batchtask

   [
    {
      method : "GET",
      headers : [..],
      url : "/users/id1"
    },
    {
      method : "GET",
      headers : [..],
      url : "/users/id2"
    }
   ]

Server will reply URI of newly created batchtask resource.

201 Created
Location: "http://example.com/api/batchtask/1254"

Now client can fetch batch response or task progress by polling

GET http://example.com/api/batchtask/1254


This is how others attempted to solve this issue:

How do I generate a random integer between min and max in Java?

This generates a random integer of size psize

public static Integer getRandom(Integer pSize) {

    if(pSize<=0) {
        return null;
    }
    Double min_d = Math.pow(10, pSize.doubleValue()-1D);
    Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
    int min = min_d.intValue();
    int max = max_d.intValue();
    return RAND.nextInt(max-min) + min;
}

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Check if you have entered the correct URL Mapping as specified in the Web.xml

For example:

In the web.xml, your servlet declaration maybe:

<servlet>
        <servlet-name>ControllerA</servlet-name>
        <servlet-class>PackageName.ControllerA</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>ControllerA</servlet-name>
        <url-pattern>/theController</url-pattern>
</servlet-mapping>

What this snippet does is <url-pattern>/theController</url-pattern>will set the name that will be used to call the servlet from the front end (eg: form) through the URL. Therefore when you reference the servlet in the front end, in order to ensure that the request goes to the servlet "ControllerA", it should refer the specified URL Pattern "theController" from the form.

eg:

<form action="theController" method="POST">
</form>

Best implementation for Key Value Pair Data Structure?

One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:

public class TokenTree : Dictionary<string, string>
{
    public IDictionary<string, string> SubPairs;
}

This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).

And yup you got the concept of the constructor right :)

Split string on the first white space occurrence

Just split the string into an array and glue the parts you need together. This approach is very flexible, it works in many situations and it is easy to reason about. Plus you only need one function call.

arr = str.split(' ');             // ["72", "tocirah", "sneab"]
strA = arr[0];                    // "72"
strB = arr[1] + ' ' + arr[2];     // "tocirah sneab"

Alternatively, if you want to cherry-pick what you need directly from the string you could do something like this:

strA = str.split(' ')[0];                    // "72";
strB = str.slice(strA.length + 1);           // "tocirah sneab"

Or like this:

strA = str.split(' ')[0];                    // "72";
strB = str.split(' ').splice(1).join(' ');   // "tocirah sneab"

However I suggest the first example.

Working demo: jsbin

.crx file install in chrome

Update: appears to have stopped working since Chrome 80

Drag & Drop the '.crx' file on to the 'Extensions' page

  1. Settings - icon > Tools > Extensions
    ( the 'hamburger' icon in the top-right corner )

  2. Enable Developer Mode ( toggle button in top-right corner )

  3. Drag and drop the '.crx' extension file onto the Extensions page from step 1
    ( crx file should likely be in your Downloads directory )

  4. Install

Source: Chrome YouTube Downloader - install instructions

How do I install PyCrypto on Windows?

PyCryptodome is an almost-compatible fork of PyCrypto with Windows wheels available on pypi.

You can install it with a simple:

pip install pycryptodome

The website includes instructions to build it from sources with the Microsoft compilers too.

How can I calculate the difference between two ArrayLists?

Although this is a very old question in Java 8 you could do something like

 List<String> a1 = Arrays.asList("2009-05-18", "2009-05-19", "2009-05-21");
 List<String> a2 = Arrays.asList("2009-05-18", "2009-05-18", "2009-05-19", "2009-05-19", "2009-05-20", "2009-05-21","2009-05-21", "2009-05-22");

 List<String> result = a2.stream().filter(elem -> !a1.contains(elem)).collect(Collectors.toList());

Print specific part of webpage

Try this awesome ink-html library

import print from 'ink-html'
// const print = require('ink-html').default

// js
print(window.querySelector('#printable'))
// Vue.js
print(this.$refs.printable.$el)

Determine whether an array contains a value

Wow, there are a lot of great answers to this question.

I didn't see one that takes a reduce approach so I'll add it in:

var searchForValue = 'pig';

var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
    return previous || searchForValue === current ? true : false;
}, false);

console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);

Here's a fiddle of it in action.

Jquery click event not working after append method

The .on() method is used to delegate events to elements, dynamically added or already present in the DOM:

_x000D_
_x000D_
// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
  var $td = $(this).closest('tr').find('td');_x000D_
  var part_name = $td.eq(1).text();_x000D_
  console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
  var first_name = $.trim( $('#f_name_participant').val() );_x000D_
  var last_name  = $.trim( $('#l_name_participant').val() );_x000D_
  var role       = $('#new_participant_role').val();_x000D_
  var email      = $('#email_participant').val();_x000D_
  _x000D_
  if(!first_name && !last_name) return;_x000D_
_x000D_
  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Form</th>_x000D_
      <th>Name</th>_x000D_
      <th>Role</th>_x000D_
      <th>Progress </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
      <td>Smith Johnson</td>_x000D_
      <td>Parent</td>_x000D_
      <td>60% done</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
  <option>Parent</option>_x000D_
  <option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Read more: http://api.jquery.com/on/

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How to send email from MySQL 5.1

If you have vps or dedicated server, You can code your own module using C programming.

para.h

/* 
 * File:   para.h
 * Author: rahul
 *
 * Created on 10 February, 2016, 11:24 AM
 */

#ifndef PARA_H
#define  PARA_H

#ifdef  __cplusplus
extern "C" {
#endif


#define From "<[email protected]>"
#define To "<[email protected]>" 
#define From_header "Rahul<[email protected]>"   
#define TO_header "Mini<[email protected]>"   
#define UID "smtp server account ID"
#define PWD "smtp server account PWD"
#define domain "dfgdfgdfg.com"


#ifdef  __cplusplus
}
#endif

#endif  
/* PARA_H */

main.c

/* 
 * File:   main.c
 * Author: rahul
 *
 * Created on 10 February, 2016, 10:29 AM
 */
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "time.h"
#include "para.h"

/*
 * 
 */

my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message);
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused)));
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error);

/*
 * base64
 */
int Base64encode_len(int len);
int Base64encode(char * coded_dst, const char *plain_src,int len_plain_src);

int Base64decode_len(const char * coded_src);
int Base64decode(char * plain_dst, const char *coded_src);

/* aaaack but it's fast and const should make it shared text page. */
static const unsigned char pr2six[256] =
{
    /* ASCII table */
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
    64,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
    64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};

int Base64decode_len(const char *bufcoded)
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;
    while (pr2six[*(bufin++)] <= 63);

    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    return nbytesdecoded + 1;
}

int Base64decode(char *bufplain, const char *bufcoded)
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register unsigned char *bufout;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;
    while (pr2six[*(bufin++)] <= 63);
    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    bufout = (unsigned char *) bufplain;
    bufin = (const unsigned char *) bufcoded;

    while (nprbytes > 4) {
    *(bufout++) =
        (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
    *(bufout++) =
        (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
    *(bufout++) =
        (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
    bufin += 4;
    nprbytes -= 4;
    }

    /* Note: (nprbytes == 1) would be an error, so just ingore that case */
    if (nprbytes > 1) {
    *(bufout++) =
        (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
    }
    if (nprbytes > 2) {
    *(bufout++) =
        (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
    }
    if (nprbytes > 3) {
    *(bufout++) =
        (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
    }

    *(bufout++) = '\0';
    nbytesdecoded -= (4 - nprbytes) & 3;
    return nbytesdecoded;
}

static const char basis_64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int Base64encode_len(int len)
{
    return ((len + 2) / 3 * 4) + 1;
}

int Base64encode(char *encoded, const char *string, int len)
{
    int i;
    char *p;

    p = encoded;
    for (i = 0; i < len - 2; i += 3) {
    *p++ = basis_64[(string[i] >> 2) & 0x3F];
    *p++ = basis_64[((string[i] & 0x3) << 4) |
                    ((int) (string[i + 1] & 0xF0) >> 4)];
    *p++ = basis_64[((string[i + 1] & 0xF) << 2) |
                    ((int) (string[i + 2] & 0xC0) >> 6)];
    *p++ = basis_64[string[i + 2] & 0x3F];
    }
    if (i < len) {
    *p++ = basis_64[(string[i] >> 2) & 0x3F];
    if (i == (len - 1)) {
        *p++ = basis_64[((string[i] & 0x3) << 4)];
        *p++ = '=';
    }
    else {
        *p++ = basis_64[((string[i] & 0x3) << 4) |
                        ((int) (string[i + 1] & 0xF0) >> 4)];
        *p++ = basis_64[((string[i + 1] & 0xF) << 2)];
    }
    *p++ = '=';
    }

    *p++ = '\0';
    return p - encoded;
}

/*
 end of base64
 */

const char* GetIPAddress(const char* target_domain) {
    const char* target_ip;
    struct in_addr *host_address;
    struct hostent *raw_list = gethostbyname(target_domain);
    int i = 0;
    for (i; raw_list->h_addr_list[i] != 0; i++) {
        host_address = raw_list->h_addr_list[i];
        target_ip = inet_ntoa(*host_address);
    }
    return target_ip;
}

char * MailHeader(const char* from, const char* to, const char* subject, const char* mime_type, const char* charset) {

    time_t now;
    time(&now);
    char *app_brand = "Codevlog Test APP";
    char* mail_header = NULL;
    char date_buff[26];
    char Branding[6 + strlen(date_buff) + 2 + 10 + strlen(app_brand) + 1 + 1];
    char Sender[6 + strlen(from) + 1 + 1];
    char Recip[4 + strlen(to) + 1 + 1];
    char Subject[8 + 1 + strlen(subject) + 1 + 1];
    char mime_data[13 + 1 + 3 + 1 + 1 + 13 + 1 + strlen(mime_type) + 1 + 1 + 8 + strlen(charset) + 1 + 1 + 2];

    strftime(date_buff, (33), "%a , %d %b %Y %H:%M:%S", localtime(&now));

    sprintf(Branding, "DATE: %s\r\nX-Mailer: %s\r\n", date_buff, app_brand);
    sprintf(Sender, "FROM: %s\r\n", from);
    sprintf(Recip, "To: %s\r\n", to);
    sprintf(Subject, "Subject: %s\r\n", subject);
    sprintf(mime_data, "MIME-Version: 1.0\r\nContent-type: %s; charset=%s\r\n\r\n", mime_type, charset);

    int mail_header_length = strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject) + strlen(mime_data) + 10;

    mail_header = (char*) malloc(mail_header_length);

    memcpy(&mail_header[0], &Branding, strlen(Branding));
    memcpy(&mail_header[0 + strlen(Branding)], &Sender, strlen(Sender));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender)], &Recip, strlen(Recip));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip)], &Subject, strlen(Subject));
    memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject)], &mime_data, strlen(mime_data));
    return mail_header;
}

my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message){
     if (!(arg->arg_count == 2)) {
        strcpy(message, "Expected two arguments");
        return 1;
    }

    arg->arg_type[0] = STRING_RESULT;// smtp server address
    arg->arg_type[1] = STRING_RESULT;// email body
    initid->ptr = (char*) malloc(2050 * sizeof (char));
    memset(initid->ptr, '\0', sizeof (initid->ptr));
    return 0;
}

void SendEmail_deinit(UDF_INIT *initid __attribute__((unused))){
    if (initid->ptr) {
        free(initid->ptr);
    }
}

char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error){
   char *header = MailHeader(From_header, TO_header, "Hello Its a test Mail from Codevlog", "text/plain", "US-ASCII");
    int connected_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof (addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(25);
    if (inet_pton(AF_INET, GetIPAddress(arg->args[0]), &addr.sin_addr) == 1) {
        connect(connected_fd, (struct sockaddr*) &addr, sizeof (addr));
    }
    if (connected_fd != -1) {
        int recvd = 0;
        const char recv_buff[4768];
        int sdsd;
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char buff[1000];
        strcpy(buff, "EHLO "); //"EHLO sdfsdfsdf.com\r\n"
        strcat(buff, domain);
        strcat(buff, "\r\n");
        send(connected_fd, buff, strlen(buff), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd2[1000];
        strcpy(_cmd2, "AUTH LOGIN\r\n");
        int dfdf = send(connected_fd, _cmd2, strlen(_cmd2), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd3[1000];
        Base64encode(&_cmd3, UID, strlen(UID));
        strcat(_cmd3, "\r\n");
        send(connected_fd, _cmd3, strlen(_cmd3), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd4[1000];
        Base64encode(&_cmd4, PWD, strlen(PWD));
        strcat(_cmd4, "\r\n");
        send(connected_fd, _cmd4, strlen(_cmd4), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd5[1000];
        strcpy(_cmd5, "MAIL FROM: ");
        strcat(_cmd5, From);
        strcat(_cmd5, "\r\n");
        send(connected_fd, _cmd5, strlen(_cmd5), 0);
        char skip[1000];
        sdsd = recv(connected_fd, skip, sizeof (skip), 0);

        char _cmd6[1000];
        strcpy(_cmd6, "RCPT TO: ");
        strcat(_cmd6, To); //
        strcat(_cmd6, "\r\n");
        send(connected_fd, _cmd6, strlen(_cmd6), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd7[1000];
        strcpy(_cmd7, "DATA\r\n");
        send(connected_fd, _cmd7, strlen(_cmd7), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        send(connected_fd, header, strlen(header), 0);
        send(connected_fd, arg->args[1], strlen(arg->args[1]), 0);
        char _cmd9[1000];
        strcpy(_cmd9, "\r\n.\r\n.");
        send(connected_fd, _cmd9, sizeof (_cmd9), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
        recvd += sdsd;

        char _cmd10[1000];
        strcpy(_cmd10, "QUIT\r\n");
        send(connected_fd, _cmd10, sizeof (_cmd10), 0);
        sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);

        memcpy(initid->ptr, recv_buff, strlen(recv_buff));
        *length = recvd;
    }
    free(header);
    close(connected_fd);
    return initid->ptr;
}

To configure your project go through this video: https://www.youtube.com/watch?v=Zm2pKTW5z98 (Send Email from MySQL on Linux) It will work for any mysql version (5.5, 5.6, 5.7)

I will resolve if any error appear in above code, Just Inform in comment

Python 3 print without parenthesis

You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.

Nodejs - Redirect url

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

use this command /usr/libexec/java_home to check the JAVA_HOME

Nested classes' scope?

Easiest solution:

class OuterClass:
    outer_var = 1
    class InnerClass:
        def __init__(self):
            self.inner_var = OuterClass.outer_var

It requires you to be explicit, but doesn't take much effort.

Aborting a shell script if any command returns a non-zero value

The if statements in your example are unnecessary. Just do it like this:

dosomething1 || exit 1

If you take Ville Laurikari's advice and use set -e then for some commands you may need to use this:

dosomething || true

The || true will make the command pipeline have a true return value even if the command fails so the the -e option will not kill the script.

Client to send SOAP request and receive response

Call SOAP webservice in c#

using (var client = new UpdatedOutlookServiceReferenceAPI.OutlookServiceSoapClient("OutlookServiceSoap"))
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
    var result = client.UploadAttachmentBase64(GUID, FinalFileName, fileURL);

    if (result == true)
    {
        resultFlag = true;
    }
    else
    {
        resultFlag = false;
    }
    LogWriter.LogWrite1("resultFlag : " + resultFlag);
}

AngularJS: How to clear query parameters in the URL?

Just use

$location.url();

Instead of

$location.path();

Android AlertDialog Single Button

Kotlin?

  val dialogBuilder = AlertDialog.Builder(this.context)
  dialogBuilder.setTitle("Alert")
               .setMessage(message)
               .setPositiveButton("OK", null)
               .create()
               .show()

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

Round up to Second Decimal Place in Python

The python round function could be rounding the way not you expected.

You can be more specific about the rounding method by using Decimal.quantize

eg.

from decimal import Decimal, ROUND_HALF_UP
res = Decimal('0.25').quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
print(res) 
# prints 0.3

More reference:

https://gist.github.com/jackiekazil/6201722

Python: convert string from UTF-8 to Latin-1

Instead of .encode('utf-8'), use .encode('latin-1').

How do I print out the contents of a vector?

I think the best way to do this is to just overload operator<< by adding this function to your program:

#include <vector>
using std::vector;
#include <iostream>
using std::ostream;

template<typename T>
ostream& operator<< (ostream& out, const vector<T>& v) {
    out << "{";
    size_t last = v.size() - 1;
    for(size_t i = 0; i < v.size(); ++i) {
        out << v[i];
        if (i != last) 
            out << ", ";
    }
    out << "}";
    return out;
}

Then you can use the << operator on any possible vector, assuming its elements also have ostream& operator<< defined:

vector<string>  s = {"first", "second", "third"};
vector<bool>    b = {true, false, true, false, false};
vector<int>     i = {1, 2, 3, 4};
cout << s << endl;
cout << b << endl;
cout << i << endl;

Outputs:

{first, second, third}
{1, 0, 1, 0, 0}
{1, 2, 3, 4}

WinForms DataGridView font size

    private void UpdateFont()
    {
        //Change cell font
        foreach(DataGridViewColumn c in dgAssets.Columns)
        {
            c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
        }
    }

How do you use youtube-dl to download live streams (that are live)?

I'll be using this Live Event from NASA TV as an example:

https://www.youtube.com/watch?v=21X5lGlDOfg

First, list the formats for the video:

$  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code  extension  resolution note
91           mp4        256x144    HLS  197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92           mp4        426x240    HLS  338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93           mp4        640x360    HLS  829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94           mp4        854x480    HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300          mp4        1280x720   3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)

Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k for this example:

?  ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8

Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).

Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:

ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How to increment a variable on a for loop in jinja template?

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

You can defeat this behavior by using an object rather than a scalar for 'count':

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

Remove Server Response Header IIS7

To remove the Server: header, go to Global.asax, find/create the Application_PreSendRequestHeaders event and add a line as follows (thanks to BK and this blog this will also not fail on the Cassini / local dev):

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    // Remove the "Server" HTTP Header from response
    HttpApplication app = sender as HttpApplication;
    if (null != app && null != app.Request && !app.Request.IsLocal &&
        null != app.Context && null != app.Context.Response)
    {
        NameValueCollection headers = app.Context.Response.Headers;
        if (null != headers)
        {
            headers.Remove("Server");
        }
    }
}

If you want a complete solution to remove all related headers on Azure/IIS7 and also works with Cassini, see this link, which shows the best way to disable these headers without using HttpModules or URLScan.

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Hey Please use / in your web.xml (instead of /*)

How to Enable ActiveX in Chrome?

This could be pretty ugly, but doesn't Chrome use the NPAPI for plugins like Safari? In that case, you could write a wrapper plugin with the NPAPI that made the appropriate ActiveX creation and calls to run the plugin. If you do a lot of scripting against those plugins, you might have to be a bit of work to proxy those calls through to the wrapped ActiveX control.

Capitalize or change case of an NSString in Objective-C

Here ya go:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

Btw:
"april" is lowercase ? [NSString lowercaseString]
"APRIL" is UPPERCASE ? [NSString uppercaseString]
"April May" is Capitalized/Word Caps ? [NSString capitalizedString]
"April may" is Sentence caps ? (method missing; see workaround below)

Hence what you want is called "uppercase", not "capitalized". ;)

As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end

Catching multiple exception types in one catch block

As of PHP 8.0 you can use even cleaner way to catch your exceptions when you don't need to output the content of the error (from variable $e). However you must replace default Exception with Throwable.

try {
    /* something */
} catch (AError | BError) {
    handler1()
} catch (Throwable) {
    handler2()
}

nginx 502 bad gateway

Go to /etc/php5/fpm/pool.d/www.conf and if you are using sockets or this line is uncommented

listen = /var/run/php5-fpm.sock

Set couple of other values too:-

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Don't forget to restart php-fpm and nginx. Make sure you are using the same nginx owner and group name.

How can I generate a random number in a certain range?

Random r = new Random();
int i1 = r.nextInt(45 - 28) + 28;

This gives a random integer between 28 (inclusive) and 45 (exclusive), one of 28,29,...,43,44.

Can I concatenate multiple MySQL rows into one field?

In my case I had a row of Ids, and it was neccessary to cast it to char, otherwise, the result was encoded into binary format :

SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Difference between java.lang.RuntimeException and java.lang.Exception

  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception

ReferenceError: $ is not defined

You can install it by bower:

Node.js npm install underscore
Meteor.js meteor add underscore
Require.js require(["underscore"], ...
Bower bower install underscore
Component component install jashkenas/underscore

Here's the link to the oficial page http://underscorejs.org/

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

jQuery: Slide left and slide right

You can always just use jQuery to add a class, .addClass or .toggleClass. Then you can keep all your styles in your CSS and out of your scripts.

http://jsfiddle.net/B8L3x/1/

What are the most common naming conventions in C?

You should also think about the order of the words to make the auto name completion easier.

A good practice: library name + module name + action + subject

If a part is not relevant just skip it, but at least a module name and an action always should be presented.

Examples:

  • function name: os_task_set_prio, list_get_size, avg_get
  • define (here usually no action part): OS_TASK_PRIO_MAX

How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name

Facebook key hash does not match any stored key hashes

  1. Check your Key hash value.
  2. Uninstall the Facebook application from your phone.
  3. Then try again using SDK.

This solved my problem.

Auto detect mobile browser (via user-agent?)

Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.

Usage of MySQL's "IF EXISTS"

SELECT IF((
     SELECT count(*) FROM gdata_calendars 
     WHERE `group` =  ? AND id = ?)
,1,0);

For Detail explanation you can visit here

How do you change Background for a Button MouseOver in WPF?

To remove the default MouseOver behaviour on the Button you will need to modify the ControlTemplate. Changing your Style definition to the following should do the trick:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

Day Name from Date in JS

I'm not a fan of over-complicated solutions if anyone else comes up with something better, please let us know :)

any-name.js

var today = new Date().toLocaleDateString(undefined, {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    weekday: 'long'
});
any-name.html
<script>
    document.write(today);
</script>

Set custom HTML5 required field validation message

Use the attribute "title" in every input tag and write a message on it

REST API Best practices: Where to put parameters?

One "dimension" of this topic has been left out yet it's very important: there are times when the "best practices" have to come into terms with the plaform we are implementing or augmenting with REST capabilities.

Practical example:

Many web applications nowadays implement the MVC (Model, View, Controller) architecture. They assume a certain standard path is provided, even more so when those web applications come with an "Enable SEO URLs" option.

Just to mention a fairly famous web application: an OpenCart e-commerce shop. When the admin enables the "SEO URLs" it expects said URLs to come in a quite standard MVC format like:

http://www.domain.tld/special-offers/list-all?limit=25

Where

  • special-offers is the MVC controller that shall process the URL (showing the special-offers page)

  • list-all is the controller's action or function name to call. (*)

  • limit=25 is an option, stating that 25 items will be shown per page.

(*) list-all is a fictious function name I used for clarity. In reality, OpenCart and most MVC frameworks have a default, implied (and usually omitted in the URL) index function that gets called when the user wants a default action to be performed. So the real world URL would be:

http://www.domain.tld/special-offers?limit=25

With a now fairly standard application or frameworkd structure similar to the above, you'll often get a web server that is optimized for it, that rewrites URLs for it (the true "non SEOed URL" would be: http://www.domain.tld/index.php?route=special-offers/list-all&limit=25).

Therefore you, as developer, are faced into dealing with the existing infrastructure and adapt your "best practices", unless you are the system admin, know exactly how to tweak an Apache / NGinx rewrite configuration (the latter can be nasty!) and so on.

So, your REST API would often be much better following the referring web application's standards, both for consistency with it and ease / speed (and thus budget saving).

To get back to the practical example above, a consistent REST API would be something with URLs like:

http://www.domain.tld/api/special-offers-list?from=15&limit=25

or (non SEO URLs)

http://www.domain.tld/index.php?route=api/special-offers-list?from=15&limit=25

with a mix of "paths formed" arguments and "query formed" arguments.

How do you generate dynamic (parameterized) unit tests in Python?

Use the ddt library. It adds simple decorators for the test methods:

import unittest
from ddt import ddt, data
from mycode import larger_than_two

@ddt
class FooTestCase(unittest.TestCase):

    @data(3, 4, 12, 23)
    def test_larger_than_two(self, value):
        self.assertTrue(larger_than_two(value))

    @data(1, -3, 2, 0)
    def test_not_larger_than_two(self, value):
        self.assertFalse(larger_than_two(value))

This library can be installed with pip. It doesn't require nose, and works excellent with the standard library unittest module.

How to scale an Image in ImageView to keep the aspect ratio

To anyone else having this particular issue. You have an ImageView that you want to have a width of fill_parent and a height scaled proportionately:

Add these two attributes to your ImageView:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

And set the ImageView width to fill_parent and height to wrap_content.

Also, if you don't want your image to be cropped, try this:

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"

How to submit http form using C#

You can use the HttpWebRequest class to do so.

Example here:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Questions every good Database/SQL developer should be able to answer

Compare and contrast the differences between a sql/rdbms solution and nosql solution. You can't claim to be an expert in any technology without knowing its strengths and weaknesses as compared to its competitors.

How to implement swipe gestures for mobile devices?

Shameless plug I know, but you might want to consider a jQuery plugin that I wrote:

https://github.com/benmajor/jQuery-Mobile-Events

It does not require jQuery Mobile, only jQuery.

How to determine the current iPhone/device model?

You can use BDLocalizedDevicesModels framework to parse device info and get the name.

Then just call UIDevice.currentDevice.productName in your code.

cURL POST command line on WINDOWS RESTful service

I ran into the same issue on my win7 x64 laptop and was able to get it working using the curl release that is labeled Win64 - Generic w SSL by using the very similar command line format:

C:\Projects\curl-7.23.1-win64-ssl-sspi>curl -H "Content-Type: application/json" -X POST http://localhost/someapi -d "{\"Name\":\"Test Value\"}"

Which only differs from your 2nd escape version by using double-quotes around the escaped ones and the header parameter value. Definitely prefer the linux shell syntax more.

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

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

You have to run the create_tables.sql inside the examples/ folder on phpMyAdmin to create the tables needed for the advanced features. That or disable those features by commenting them on the config file.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

How to replace captured groups only?

A solution is to add captures for the preceding and following text:

str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.

Save document(name.docx) in word as single file webpage (name.mht) In your html use

<iframe src= "name.mht" width="100%" height="800"> </iframe>

Alter the heights and widths as you see fit.

How can I add comments in MySQL?

/* comment here */ 

here is an example: SELECT 1 /* this is an in-line comment */ + 1;

http://dev.mysql.com/doc/refman/5.0/en/comments.html

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

HTML Form: Select-Option vs Datalist-Option

To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select tags, then the options must be rendered for each select, for every row.

In such a case, I would consider using datalist with input, because the same datalist can be used for any number of inputs. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.

How do I join two lists in Java?

Off the top of my head, I can shorten it by one line:

List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

How do I give ASP.NET permission to write to a folder in Windows 7?

I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.

It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.

Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".

These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.

Hope that helps

How can I remove file extension from a website address?

First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.

You don't hide urls or extensions. What you do is create a NEW url that directs to the old one, for example

The URL to put on your web site will be yoursite.com/play?m=asdf

or better yet

yoursite.com/asdf

Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /play.php [L] 

Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be

/Some-Cool-Video (which equals product ID asdf)

The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?

I can't give you specifics of how to program this, but take the query string, strip off the end

yoursite.com/Some-Cool-Video 

turns into "asdf"

Then set the m variable to this

m=asdf

So both URL's will still go to the same product

yoursite.com/play.php?m=asdf 
yoursite.com/Some-Cool-Video 

mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)

Loading PictureBox Image from resource file with path (Part 3)

The accepted answer has major drawback!
If you loaded your image that way your PictureBox will lock the image,so if you try to do any future operations on that image,you will get error message image used in another application!
This article show solution in VB

and This is C# implementation

 FileStream fs = new System.IO.FileStream(@"Images\a.bmp", FileMode.Open, FileAccess.Read);
  pictureBox1.Image = Image.FromStream(fs);
  fs.Close();

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

Prepend text to beginning of string

you could also do it this way

"".concat("x","y")

Add a property to a JavaScript object using a variable as the name?

ajavascript have two type of annotation for fetching javascript Object properties:

Obj = {};

1) (.) annotation eg. Obj.id this will only work if the object already have a property with name 'id'

2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.

so for below example:

A new property will be created always when you write Obj[name]. And if the property already exist with the same name it will override it.

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })

Resolve absolute path from relative path and/or file name

I came across a similar need this morning: how to convert a relative path into an absolute path inside a Windows command script.

The following did the trick:

@echo off

set REL_PATH=..\..\
set ABS_PATH=

rem // Save current directory and change to target directory
pushd %REL_PATH%

rem // Save value of CD variable (current directory)
set ABS_PATH=%CD%

rem // Restore original directory
popd

echo Relative path: %REL_PATH%
echo Maps to path: %ABS_PATH%

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

FXCop typically prefers OrdinalIgnoreCase. But your requirements may vary.

For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.

OrdinalIgnoreCase

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx

InvariantCultureIgnoreCase

The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx

The invariant culture is the CultureInfo object returned by the InvariantCulture property.

The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.

Is HTML considered a programming language?

Well, L is for language, but it doesn't imply programming language. After all, English or French are (natural) languages too! ;-)

As said above, put them under a subsidiary section, Technology seems to be a good term.

(Looking at my own resume, not updated in a while) I have made a section just called "Languages", so I can't get wrong... :-D
I have put "(X)HTML and CSS, XML/DTD/Schema and SVG" at the end of the section, clearly separated.

In French, I have a section "Langages" (programming and markup) and another "Langues" (French/English). In the English version, I titled both at "Languages", which is clumsy now that I think of it, although context clarify this. I should find a better formulation.

Can you delete data from influxdb?

I'm surprised that nobody has mentioned InfluxDB retention policies for automatic data removal. You can set a default retention policy and also set them on a per-database level.

From the docs:

CREATE RETENTION POLICY <retention_policy_name> ON <database_name> DURATION <duration> REPLICATION <n> [DEFAULT]

Django datetime issues (default=datetime.now())

datetime.now() is being evaluated once, when your class is instantiated. Try removing the parenthesis so that the function datetime.now is returned and THEN evaluated. I had the same issue with setting default values for my DateTimeFields and wrote up my solution here.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

Converting BigDecimal to Integer

You would call myBigDecimal.intValueExact() (or just intValue()) and it will even throw an exception if you would lose information. That returns an int but autoboxing takes care of that.

The imported project "C:\Microsoft.CSharp.targets" was not found

I used to have this following line in the csproj file:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />

After deleting this file, it works fine.

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

How do I convert a PDF document to a preview image in PHP?

For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with exec() to convert a PDF to JPG, and manipulate the resulting file with imagecreatefromjpeg().

Run the ghostscript command:

exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=whatever.jpg input.pdf')

To manipulate, create a new placeholder image, $newimage = imagecreatetruecolor(...), and bring in the current image. $image = imagecreatefromjpeg('whatever.jpg'), and then you can use imagecopyresampled() to change the size, or any number of other built-in, non-imagemagick commands

Angularjs - ng-cloak/ng-show elements blink

It's better to use ng-if instead of ng-show. ng-if completely removes and recreates the element in the DOM and helps to avoid ng-shows blinking.

Is there a good jQuery Drag-and-drop file upload plugin?

I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.

http://code.google.com/p/dnd-file-upload/

Get int from String, also containing letters, in Java

You can also use Scanner :

Scanner s = new Scanner(MyString);
s.nextInt();

Extract data from log file in specified range of time

Use grep and regular expressions, for example if you want 4 minutes interval of logs:

grep "31/Mar/2002:19:3[1-5]" logfile

will return all logs lines between 19:31 and 19:35 on 31/Mar/2002. Supposing you need the last 5 days starting from today 27/Sep/2011 you may use the following:

grep "2[3-7]/Sep/2011" logfile

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

In my case, I experienced this error because my webapp was .NET v4, and the application pool was configured for .NET v2.

Double-clicking on the application pool brings up a popup window, where we can select the desired version of .NET Framework.

What is the best open-source java charting library? (other than jfreechart)

Good question, I was just looking for alternatives to JFreeChart myself the other day. JFreeChart is excellent and very comprehensive, I've used it on several projects. My recent problem was that it meant adding 1.6mb of libraries to a 50kb applet, so I was looking for something smaller.

The JFreeChart FAQ itself lists alternatives. Compared to JFreeChart, most of them are pretty basic, and some pretty ugly. The most promising seem to be the Java Chart Construction Kit and OpenChart2.

I also found EasyCharts, which is a commercial product but seemingly free to use in some circumstances.

In the end, I went back to the tried and trusted JFreeChart and used Proguard to butcher it into a more manageable size.

I suggest that you take another look at JFreeChart. The user guide is only available to buy, but the demo shows what is possible and it's pretty easy to work out how from the API documentation. Basically you start with the ChartFactory static methods and plug the resultant JFreeChart object into a ChartPanel to display it. If you get stuck, I'm sure you'll get some quick answers to your problems on StackOverflow.

Simple line plots using seaborn

Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style function should get you started:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()

Result:

enter image description here

async/await - when to return a Task vs void?

According to Microsoft documentation, should NEVER use async void

Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached:

  • Which is ALWAYS a bad practice in ASP.NET Core apps.

  • Accesses the HttpResponse after the HTTP request is complete.

  • Crashes the process.

Angular: How to update queryParams without changing route

Try

this.router.navigate([], { 
  queryParams: {
    query: value
  }
});

will work for same route navigation other than single quotes.

How to sort alphabetically while ignoring case sensitive?

Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

  System.out.println(Arrays.toString(myArray));

 }

}

/* Output:[A, b, B] */

PHP file_get_contents() and setting request headers

Using the php cURL libraries will probably be the right way to go, as this library has more features than the simple file_get_contents(...).

An example:

<?php
$ch = curl_init();
$headers = array('HTTP_ACCEPT: Something', 'HTTP_ACCEPT_LANGUAGE: fr, en, da, nl', 'HTTP_CONNECTION: Something');

curl_setopt($ch, CURLOPT_URL, "http://localhost"); # URL to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
$result = curl_exec( $ch ); # run!
curl_close($ch);
?>

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

Set EditText cursor color

There is a new way to change cursor color in latest Appcompact v21
Just change colorAccent in style like this:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->

    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#088FC9</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#088FC9</item>

    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <!-- THIS IS WHAT YOU'RE LOOKING FOR -->
    <item name="colorAccent">#0091BC</item> 
</style>

Then apply this style on your app theme or activities.

Update: this way only works on API 21+
Update 2: I'm not sure the minimum android version that it can work.
Tested by android version:

2.3.7 - didn't work
4.4.4 - worked
5.0 - worked
5.1 - worked

Why is jquery's .ajax() method not sending my session cookie?

Using

xhrFields: { withCredentials:true }

as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:

Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true

It was important that only one allowed "origin" was in the response header of the OPTIONS call and not "*". I achieved this by reading the origin from the request and populating it back into the response - probably circumventing the original reason for the restriction, but in my use case the security is not paramount.

I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn't! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header NB the "in practice" bit.

select dept names who have more than 2 employees whose salary is greater than 1000

select D.DeptName from [Department] D where D.DeptID in 
( 
    select E.DeptId from [Employee] E
    where E.Salary > 1000
    group by E.DeptId
    having count(*) > 2
)

Horizontal swipe slider with jQuery and touch devices support?

If I was you, I would implement my own solution based on the event specs. Basically, what swipe is - it's handling of touch down, touch move, touch up events. here is excerpt of my own lib for handling iPhone touch events:

touch_object.prototype.handle_touchstart = function(e){
    if (e.targetTouches.length != 1){
        return false;
    }
    this.obj.style.zIndex = 100;
    e.preventDefault();
    this.startX = e.targetTouches[0].pageX - this.geometry.x;
    this.startY = e.targetTouches[0].pageY - this.geometry.y;
    /* adjust for left /top */
    this.bind_handler('touchmove');
    this.bind_handler('touchend');
}
touch_object.prototype.handle_touchmove = function(e) {
    e.preventDefault();
    if (e.targetTouches.length != 1){
        return false;
    }
    var x=e.targetTouches[0].pageX - this.startX;
    var y=e.targetTouches[0].pageY - this.startY;
    this.move(x,y);

}
touch_object.prototype.handle_touchend = function(e){
    this.obj.style.zIndex = 10;
    this.unbind_handler('touchmove');
    this.unbind_handler('touchend');
}

I used that code to "move things around". But, instead of moving, you can create your own algorithm for e.g. triggering redirect to some other location, or you can use that move to "move/swipe" the element, on which the swipe is on to other location.

so, it really helps to understand basics of how things work and then create more complicated solutions. this might help as well.

I used this, to create my solution:

http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

How get all values in a column using PHP?

First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function

function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
    $databaseConnectionQuery =  mysqli_connect($serverName, $userName, $password, $databaseName);
    if($databaseConnectionQuery === false)
    {
        die("ERROR: Could not connect. " . mysqli_connect_error());
        return false;
    }

    $resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
    $fetchFields = mysqli_fetch_fields($resultQuery);
    $fetchValues = mysqli_fetch_fields($resultQuery);

    if (mysqli_num_rows($resultQuery) > 0) 
    {           

        echo "<table class='table'>";
        echo "<tr>";
        foreach ($fetchFields as $fetchedField)
         {          
            echo "<td>";
            echo "<b>" . $fetchedField->name . "<b></a>";
            echo "</td>";
        }       
        echo "</tr>";
        while($totalRows = mysqli_fetch_array($resultQuery)) 
        {           
            echo "<tr>";                                
            for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
            {           
                echo "<td>";
                echo $totalRows[$eachRecord];
                echo "</td>";               
            }
            echo "<td><a href=''><button>Edit</button></a></td>";
            echo "<td><a href=''><button>Delete</button></a></td>";
            echo "</tr>";           
        } 
        echo "</table>";        

    } 
    else
    {
      echo "No Records Found in";
    }
}

All set now Pass the arguments as For Example

$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;

Here

localhost indicates Name of the host,

root indicates the username for database

root@123 indicates the password for the database

$queryStatment for generating Query

hope it helps

Case Statement Equivalent in R

Mixing plyr::mutate and dplyr::case_when works for me and is readable.

iris %>%
plyr::mutate(coolness =
     dplyr::case_when(Species  == "setosa"     ~ "not cool",
                      Species  == "versicolor" ~ "not cool",
                      Species  == "virginica"  ~ "super awesome",
                      TRUE                     ~ "undetermined"
       )) -> testIris
head(testIris)
levels(testIris$coolness)  ## NULL
testIris$coolness <- as.factor(testIris$coolness)
levels(testIris$coolness)  ## ok now
testIris[97:103,4:6]

Bonus points if the column can come out of mutate as a factor instead of char! The last line of the case_when statement, which catches all un-matched rows is very important.

     Petal.Width    Species      coolness
 97         1.3  versicolor      not cool
 98         1.3  versicolor      not cool  
 99         1.1  versicolor      not cool
100         1.3  versicolor      not cool
101         2.5  virginica     super awesome
102         1.9  virginica     super awesome
103         2.1  virginica     super awesome

How to handle login pop up window using Selenium WebDriver?

You can use this Autoit script to handle the login popup:

WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'

Creating a list/array in excel using VBA to get a list of unique names in a column

You don't need arrays for this. Try something like:

ActiveSheet.Range("$A$1:$A$" & LastRow).RemoveDuplicates Columns:=1, Header:=xlYes

If there's no header, change accordingly.

EDIT: Here's the traditional method, which takes advantage of the fact that each item in a Collection must have a unique key:

Sub test()
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim coll As Collection
Dim cell As Excel.Range
Dim arr() As String
Dim i As Long

Set ws = ActiveSheet
With ws
    LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    Set coll = New Collection
    For Each cell In .Range("C4:C" & LastRow)
        On Error Resume Next
        coll.Add cell.Value, CStr(cell.Value)
        On Error GoTo 0
    Next cell
    ReDim arr(1 To coll.Count)
    For i = LBound(arr) To UBound(arr)
        arr(i) = coll(i)
        'to show in Immediate Window
        Debug.Print arr(i)
    Next i
End With
End Sub

How to reset / remove chrome's input highlighting / focus border?

To remove the default focus, use the following in your default .css file :

:focus {outline:none;}

You can then control the focus border color either individually by element, or in the default .css:

:focus {outline:none;border:1px solid red}

Obviously replace red with your chosen hex code.

You could also leave the border untouched and control the background color (or image) to highlight the field:

:focus {outline:none;background-color:red}

:-)

Comparing arrays in JUnit assertions, concise built-in way?

Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.

import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;

//...

assertThat(result, is(new int[] {56, 100, 2000}));

Failure Trace output:

java.lang.AssertionError: 
   Expected: is [<56>, <100>, <2000>]
   but: was [<55>, <100>, <2000>]

Why do we use arrays instead of other data structures?

Time to go back in time for a lesson. While we don't think about these things much in our fancy managed languages today, they are built on the same foundation, so let's look at how memory is managed in C.

Before I dive in, a quick explanation of what the term "pointer" means. A pointer is simply a variable that "points" to a location in memory. It doesn't contain the actual value at this area of memory, it contains the memory address to it. Think of a block of memory as a mailbox. The pointer would be the address to that mailbox.

In C, an array is simply a pointer with an offset, the offset specifies how far in memory to look. This provides O(1) access time.

  MyArray   [5]
     ^       ^
  Pointer  Offset

All other data structures either build upon this, or do not use adjacent memory for storage, resulting in poor random access look up time (Though there are other benefits to not using sequential memory).

For example, let's say we have an array with 6 numbers (6,4,2,3,1,5) in it, in memory it would look like this:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================

In an array, we know that each element is next to each other in memory. A C array (Called MyArray here) is simply a pointer to the first element:

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^
MyArray

If we wanted to look up MyArray[4], internally it would be accessed like this:

   0     1     2     3     4 
=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
                           ^
MyArray + 4 ---------------/
(Pointer + Offset)

Because we can directly access any element in the array by adding the offset to the pointer, we can look up any element in the same amount of time, regardless of the size of the array. This means that getting MyArray[1000] would take the same amount of time as getting MyArray[5].

An alternative data structure is a linked list. This is a linear list of pointers, each pointing to the next node

========    ========    ========    ========    ========
| Data |    | Data |    | Data |    | Data |    | Data |
|      | -> |      | -> |      | -> |      | -> |      | 
|  P1  |    |  P2  |    |  P3  |    |  P4  |    |  P5  |        
========    ========    ========    ========    ========

P(X) stands for Pointer to next node.

Note that I made each "node" into its own block. This is because they are not guaranteed to be (and most likely won't be) adjacent in memory.

If I want to access P3, I can't directly access it, because I don't know where it is in memory. All I know is where the root (P1) is, so instead I have to start at P1, and follow each pointer to the desired node.

This is a O(N) look up time (The look up cost increases as each element is added). It is much more expensive to get to P1000 compared to getting to P4.

Higher level data structures, such as hashtables, stacks and queues, all may use an array (or multiple arrays) internally, while Linked Lists and Binary Trees usually use nodes and pointers.

You might wonder why anyone would use a data structure that requires linear traversal to look up a value instead of just using an array, but they have their uses.

Take our array again. This time, I want to find the array element that holds the value '5'.

=====================================
|  6  |  4  |  2  |  3  |  1  |  5  |
=====================================
   ^     ^     ^     ^     ^   FOUND!

In this situation, I don't know what offset to add to the pointer to find it, so I have to start at 0, and work my way up until I find it. This means I have to perform 6 checks.

Because of this, searching for a value in an array is considered O(N). The cost of searching increases as the array gets larger.

Remember up above where I said that sometimes using a non sequential data structure can have advantages? Searching for data is one of these advantages and one of the best examples is the Binary Tree.

A Binary Tree is a data structure similar to a linked list, however instead of linking to a single node, each node can link to two children nodes.

         ==========
         |  Root  |         
         ==========
        /          \ 
  =========       =========
  | Child |       | Child |
  =========       =========
                  /       \
            =========    =========
            | Child |    | Child |
            =========    =========

 Assume that each connector is really a Pointer

When data is inserted into a binary tree, it uses several rules to decide where to place the new node. The basic concept is that if the new value is greater than the parents, it inserts it to the left, if it is lower, it inserts it to the right.

This means that the values in a binary tree could look like this:

         ==========
         |   100  |         
         ==========
        /          \ 
  =========       =========
  |  200  |       |   50  |
  =========       =========
                  /       \
            =========    =========
            |   75  |    |   25  |
            =========    =========

When searching a binary tree for the value of 75, we only need to visit 3 nodes ( O(log N) ) because of this structure:

  • Is 75 less than 100? Look at Right Node
  • Is 75 greater than 50? Look at Left Node
  • There is the 75!

Even though there are 5 nodes in our tree, we did not need to look at the remaining two, because we knew that they (and their children) could not possibly contain the value we were looking for. This gives us a search time that at worst case means we have to visit every node, but in the best case we only have to visit a small portion of the nodes.

That is where arrays get beat, they provide a linear O(N) search time, despite O(1) access time.

This is an incredibly high level overview on data structures in memory, skipping over a lot of details, but hopefully it illustrates an array's strength and weakness compared to other data structures.

I want to truncate a text or line with ellipsis using JavaScript

function truncate(string, length, delimiter) {
   delimiter = delimiter || "&hellip;";
   return string.length > length ? string.substr(0, length) + delimiter : string;
};

var long = "Very long text here and here",
    short = "Short";

truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"

How to calculate md5 hash of a file using javascript

I don't believe there is a way in javascript to access the contents of a file upload. So you therefore cannot look at the file contents to generate an MD5 sum.

You can however send the file to the server, which can then send an MD5 sum back or send the file contents back .. but that's a lot of work and probably not worthwhile for your purposes.

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

We added some WCF SOAP related things to an existing IIS site and it caused this problem, with the site refusing to honour the web.config authentication redirect.

We tried the various fixes listed without success, and invented a work around of mapping the new weird URL back to the one we've been using for years:

<urlMappings enabled="true">
<add mappedUrl="~/loginout.aspx" url="~/Account/Login"/>
</urlMappings>

That worked but it's ugly. Eventually we traced it down to a web.config entry added by Visual Studio some time earlier:

<add key="webpages:Enabled" value="true" />

As we'd been unable to work out precisely what that does, we took it out, which solved the problem for us immediately.

Add new value to an existing array in JavaScript

This has nothing to do with jQuery, just JavaScript in general.

To create an array in JavaScript:

var a = [];

Or:

var a = ['value1', 'value2', 'value3'];

To append values on the end of existing array:

a.push('value4');

To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2], but new Array(1) is not equivalent to [1]. Rather the latter is closer to [undefined], since a single integer argument to the Array constructor indicates the desired array length.
  • Array, just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45 There is another way to fix that error.

In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;

  1. Connect to MySQL as root

    mysql -u root -p
    

    then enter your MySQL root password;

  2. Select database;

    use mysql;
    
  3. Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;

  4. Create additional record for root user with Host='127.0.0.1' if it's not there;

        SET @s = CONCAT('INSERT INTO mysql.user SELECT ',
                REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME) 
                         FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
                ,"Host","'127.0.0.1'"),
                ' FROM mysql.user WHERE User="root"'); 
    
         PREPARE stmt FROM @s; 
         EXECUTE stmt;
    
  5. Additionally to that you can execute mysql_upgrade -u -p to see if everything is ok.

Opening new window in HTML for target="_blank"

To open in a new windows with dimensions and everything, you will need to call a JavaScript function, as target="_blank" won't let you adjust sizes. An example would be:

<a href="http://www.facebook.com/sharer" onclick="window.open(this.href, 'mywin',
'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); return false;" >Share this</a>

Hope this helps you.

Five equal columns in twitter bootstrap

Five columns are clearly not the part of bootstrap by design.

But with Bootstrap v4 (alpha), there are 2 things to help with a complicated grid layout

  1. Flex (http://v4-alpha.getbootstrap.com/getting-started/flexbox/), the new element type (official - https://www.w3.org/TR/css-flexbox-1/)
  2. Responsive utilities (http://v4-alpha.getbootstrap.com/layout/responsive-utilities/)

In simple term, I'm using

<style>
.flexc { display: flex; align-items: center; padding: 0; justify-content: center; }
.flexc a { display: block; flex: auto; text-align: center; flex-basis: 0; }
</style>
<div class="container flexc hidden-sm-down">
  <!-- content to show in MD and larger viewport -->
  <a href="#">Link/Col 1</a>
  <a href="#">Link/Col 2</a>
  <a href="#">Link/Col 3</a>
  <a href="#">Link/Col 4</a>
  <a href="#">Link/Col 5</a>
</div>
<div class="container hidden-md-up">
  <!-- content to show in SM and smaller viewport, I don't think 5 cols in smaller viewport are gonna be alright :) -->
</div>

Be it 5,7,9,11,13 or something odds, it'll be okay. I'm quite sure that 12-grids standard is able to serve more than 90% of use case - so let's design that way - develop more easier too!

The nice flex tutorial is here "https://css-tricks.com/snippets/css/a-guide-to-flexbox/"

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

Close Android Application

just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!

Chart won't update in Excel (2007)

I had the same problem while working through a tutorial (very frustrating when you follow the steps and don't get the expected result).

The tutorial to create a pie chart wanted me to select range A3:A10, then also select non-adjacent range E3:E10. I did so. I got the chart.

It then asked me to change a value and watch the percentage change, then to look at the pie chart and see the update.

It didn't update.

I looked at the data source for the pie chart, and the range was bizarre. It had the A3:A10 range notated properly, but the E10 cell reference repeated several times, and it had all of the E cells listed in a random order. It looked like

=SERIES(,(Revenue!$A$3:$A$10,Revenue!$E$3,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$9,Revenue!$E$8,Revenue!$E$7,Revenue!$E$6,Revenue!$E$5,Revenue!$E$4),1

I changed the data source to read:

=SERIES(,Revenue!$A$3:$A$10,Revenue!$E$3:$E$10,1)

Problem solved. Sometimes it's a matter of cleaning up your code so the calculations processor has less to sort through.

Send mail via CMD console

Unless you want to talk to an SMTP server directly via telnet you'd use commandline mailers like blat:

blat -to [email protected] -f [email protected] -s "mail subject" ^
  -server smtp.example.net -body "message text"

or bmail:

bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
  -a "mail subject" -b "message text"

You could also write your own mailer in VBScript or PowerShell.

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

In a URL, should spaces be encoded using %20 or +?

You can use either - which means most people opt for "+" as it's more human readable.

Easy way of running the same junit test over and over?

I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.

https://github.com/anderson-marques/concurrent-testing

Maven dependency:

<dependency>
    <groupId>org.lite</groupId>
    <artifactId>concurrent-testing</artifactId>
    <version>1.0.0</version>
</dependency>

Example of use:

package org.lite.concurrent.testing;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;

/**
 * Concurrent tests examples
 */
public class ExampleTest {

    /**
     * Create a new TestRule that will be applied to all tests
     */
    @Rule
    public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 20, threads = 10)
    public void testConcurrentExecutionSuccess(){
        Assert.assertTrue(true);
    }

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
    public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
    }

    @Test(expected = RuntimeException.class)
    @ConcurrentTest(requests = 3)
    public void testConcurrentExecutionFail(){
        throw new RuntimeException("Fail");
    }
}

This is a open source project. Feel free to improve.

How to get config parameters in Symfony2 Twig Templates

You can use parameter substitution in the twig globals section of the config:

Parameter config:

parameters:
    app.version: 0.1.0

Twig config:

twig:
    globals:
        version: '%app.version%'

Twig template:

{{ version }}

This method provides the benefit of allowing you to use the parameter in ContainerAware classes as well, using:

$container->getParameter('app.version');

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

For those the above answer does not work, here is another possible solution to look at.

Issue: On installing npm os-service package i was getting below error error MSB4019: The imported project "d:\M icrosoft.Cpp.Default.props" was not found. Confirm that the path in the declaration is correct

Even the installation of build tools or VS 2015 did not work for me. So I tried installing below directly via PowerShell (as admin)

https://chocolatey.org/packages/visualcpp-build-tools/14.0.25420.1 Command: choco install visualcpp-build-tools --version 14.0.25420.1

Once this was installed, set an environment variable VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140

Then installation of the package worked perfectly fine after these.

Django: save() vs update() to update the database?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.

update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.

Check if current directory is a Git repository

# check if git repo

if [ $(git rev-parse --is-inside-work-tree) = true ]; then
    echo "yes, is a git repo"
    git pull
else
    echo "no, is not a git repo"
    git clone url --depth 1
fi

how to use html2canvas and jspdf to export to pdf in a proper and simple way

This one shows how to print only selected element on the page with dpi/resolution adjustments

HTML:

<html>

  <body>
    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>
  </body>

</html>

CSS:

body {
  background: beige;
}

header {
  background: red;
}

footer {
  background: blue;
}

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
}

JS:

$('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {
    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);
      doc.save('sample-file.pdf');
    }
  });
});

jsfiddle: https://jsfiddle.net/marksalvania/dum8bfco/

Finishing current activity from a fragment

Try this. There shouldn't be any warning...

            Activity thisActivity = getActivity();
            if (thisActivity != null) {
                startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                thisActivity.finish();
            }

Angular 2 'component' is not a known element

A lot of answers/comments mention components defined in other modules, or that you have to import/declare the component (that you want to use in another component) in its/their containing module.

But in the simple case where you want to use component A from component B when both are defined in the same module, you have to declare both components in the containing module for B to see A, and not only A.

I.e. in my-module.module.ts

import { AComponent } from "./A/A.component";
import { BComponent } from "./B/B.component";

@NgModule({
  declarations: [
    AComponent,   // This is the one that we naturally think of adding ..
    BComponent,   // .. but forget this one and you get a "**'AComponent'** 
                  // is not a known element" error.
  ],
})

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

After another hour or two I can actually answer my own question.

Someone on another forum mentioned that you need to keep a mention of plain ol' localhost in the httpd-vhost.conf file, so here's what I ended up with in there:

ServerName localhost

DocumentRoot "c:/wamp/www/"

DocumentRoot "C:/wamp/www/pocket/"
ServerName pocket.clickng.com
ServerAlias pocket.clickng.com
ErrorLog "logs/pocket.clickng.com-error.log"
CustomLog "logs/pocket.clickng.com-access.log" common
<Directory "C:/wamp/www/pocket/">
    Options Indexes FollowSymLinks Includes
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Exit WAMP, restart - good to go. Hope this helps someone else :)