Programs & Examples On #Zillow

Loop inside React JSX

Using Array map function is a very common way to loop through an Array of elements and create components according to them in React, this is a great way to do a loop which is a pretty efficient and tidy way to do your loops in JSX, It's not the only way to do it, but the preferred way.

Also, don't forget having a unique Key for each iteration as required. Map function creates a unique index from 0 but it's not recommended using the produced index but if your value is unique or if there is a unique key, you can use them:

<tbody>
  {numrows.map(x=> <ObjectRow key={x.id} />)}
</tbody>

Also, few lines from MDN if you not familiar with map function on Array:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to the map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. This value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function.

map does not mutate the array on which it is called (although callback, if invoked, may do so).

UINavigationBar custom back button without title

iOS7 has new interface rules, so It's better to keep at least the back arrow when you push a UIView. It's very easy to change the "back" text programmatically. Just add this code before push the view (Or prepareForSegue if you are using StoryBoards):

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
      self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"NEW TITLE" style:UIBarButtonItemStylePlain target:nil action:nil];
}

This will change the default "Back" text, but will keep the iOS7 styled back arrow. You can also change the tint color for the back arrow before push the view:

- (void)viewDidLoad{
     //NavBar background color:
     self.navigationController.navigationBar.barTintColor=[UIColor redColor];
//NavBar tint color for elements:
     self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
}

Hope this helps you!

Android - Package Name convention

But if your Android App is only for personal purpose or created by you alone, you can use:

me.app_name.app

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

We had the same issue while trying to launch Selenium tests from Jenkins. I had selected the 'Start Xvfb before the build, and shut it down after' box and passed in the necessary screen options, but I was still getting this error.

It finally worked when we passed in the following commands in the Execute Shell box.

Xvfb :99 -ac -screen 0 1280x1024x24 & nice -n 10 x11vnc 2>&1 & ... killall Xvfb

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

How to hide iOS status bar

Try this simple method:


Objective-C:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated]
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated]
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
}

Swift:

override func viewWillAppear(animated: Bool) 
{
    super.viewWillAppear(animated)
    UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None)
}

override func viewWillDisappear(animated: Bool) 
{
    super.viewWillDisappear(animated)
    UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.None)
}

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Windows batch - concatenate multiple text files into one

We can use normal CAT command to merge files..

D:> cat *.csv > outputs.csv

Max or Default?

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select CType(y.MyCounter, Integer?)).Max

Or in C#:

var x = (from y in context.MyTable
         where y.MyField == value
         select (int?)y.MyCounter).Max();

How do you check in python whether a string contains only numbers?

Use string isdigit function:

>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False

What does @media screen and (max-width: 1024px) mean in CSS?

It means if the screen size is 1024 then only apply below CSS rules.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

Read carefully the warning message :

The POM for org.raml:jaxrs-code-generator:jar:2.0.0 is missing, no dependency information available

The problem is not the jar, but the pom.xml that is missing.
The pom.xml lists the required dependencies for this jar that Maven will pull during the build and overall the packaging of your application. So, you may really need it.

Note that this problem may of course occur for other Maven dependencies and the ideas to solve that is always the same.

The Mule website documents very well that in addition to some information related to.


How to solve ?

1) Quick workaround : looking for in the internet the pom.xml of the artifact

Googling the artifact id, the group id and its version gives generally interesting results : maven repository links to download it.
In the case of the org.raml:jaxrs-code-generator:jar:2.0.0 dependency, you can download the pom.xml from the Maven mule repository :

https://repository.mulesoft.org/nexus/content/repositories/releases/org/raml/jaxrs-code-generator/2.0.0/

2) Clean workaround for a single Maven project : adding the repository declaration in your pom.

In your case, add the Maven mule repositories :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-snapshots</id>
            <name>MuleSoft Snapshot Repository</name>
            <url>http://repository.mulesoft.org/snapshots/</url>
            <layout>default</layout>
        </repository>
    </repositories>
    ...
</project>

3) Clean workaround for any Maven projects : add the repository declaration in your settings.xml

 <profile> 
   <repositories>
    ...
    <repository>
      <id>mulesoft-releases</id>
      <name>MuleSoft Repository</name>
      <url>http://repository.mulesoft.org/releases/</url>
      <layout>default</layout>
    </repository>
    <repository>
      <id>mulesoft-snapshots</id>
      <name>MuleSoft Snapshot Repository</name>
      <url>http://repository.mulesoft.org/snapshots/</url>
      <layout>default</layout>
    </repository>
     ...
  </repositories>     
</profile>

Note that in some rare cases, the pom.xml declaring the dependencies is nowhere. So, you have to identify yourself whether the artifact requires dependencies.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Inline <style> tags vs. inline css properties

Whenever is possible is preferable to use class .myclass{} and identifier #myclass{}, so use a dedicated css file or tag <style></style> within an html. Inline style is good to change css option dynamically with javascript.

Xcode 5 and iOS 7: Architecture and Valid architectures

My understanding from Apple Docs.

  • What is Architectures (ARCHS) into Xcode build-settings?
    • Specifies architecture/s to which the binary is TARGETED. When specified more that one architecture, the generated binary may contain object code for each of the specified architecture.
  • What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?

    • Specifies architecture/s for which the binary may be BUILT.
    • During build process, this list is intersected with ARCHS and the resulting list specifies the architectures the binary can run on.
  • Example :- One iOS project has following build-settings into Xcode.

    • ARCHS = armv7 armv7s
    • VALID_ARCHS = armv7 armv7s arm64
    • In this case, binary will be built for armv7 armv7s arm64 architectures. But the same binary will run on ONLY ARCHS = armv7 armv7s.

string sanitizer for filename

preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)

Add/remove more valid characters depending on what is allowed for your system.

Alternatively you can try to create the file and then return an error if it's bad.

How to set web.config file to show full error message

This can also help you by showing full details of the error on a client's browser.

<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>

Access camera from a browser

    <style type="text/css">
        #container {
            margin: 0px auto;
            width: 500px;
            height: 375px;
            border: 10px #333 solid;
        }

        #videoElement {
          width: 500px;
          height: 375px;
          background-color: #777;
        }
    </style>    
<div id="container">
            <video autoplay="true" id="videoElement"></video>
        </div>
        <script type="text/javascript">
          var video = document.querySelector("#videoElement");
          navigator.getUserMedia = navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia;
    
          if(navigator.getUserMedia) {
            navigator.getUserMedia({video:true}, handleVideo, videoError);
          }
    
          function handleVideo(stream) {
            video.srcObject=stream;
            video.play();
          }
    
          function videoError(e) {
    
          }
        </script>

A non well formed numeric value encountered

if $_GET['start_date'] is a string then convert it in integer or double to deal numerically.

$int = (int) $_GET['start_date']; //Integer
$double = (double) $_GET['start_date']; //It takes in floating value with 2 digits

Determine the path of the executing BASH script

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Java 8 LocalDate Jackson format

The following annotation worked fine for me.

No extra dependencies needed.

    @JsonProperty("created_at")
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime createdAt;

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

Back in 2013, that was not possible. Microsoft didn't provide any executable for this.

See this link for some VBS way to do this. https://superuser.com/questions/201371/create-zip-folder-from-the-command-line-windows

From Windows 8 on, .NET Framework 4.5 is installed by default, with System.IO.Compression.ZipArchive and PowerShell available, one can write scripts to achieve this, see https://stackoverflow.com/a/26843122/71312

Debugging in Maven?

I thought I would expand on these answers for OSX and Linux folks (not that they need it):

I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.

$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found

DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.

I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)

Let's see:

$ which mvn
/usr/local/bin/mvn

There you are... you little b@stard.

Now where did you get installed to:

$ ls -l /usr/local/bin/mvn

lrwxr-xr-x  1 root  wheel  39 Oct 31 13:00 /
                  /usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn

Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...

Do you have your little buddy mvnDebug with you?

$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug 
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug

Good. Good. Very good. All going as planned.

Now move that little b@stard where I can remember him more easily.

$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
  ln: /usr/local/bin/mvnDebug: Permission denied

Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!

$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug

Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)

$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Internally mvnDebug uses this:

MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE  \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"

So you could modify it (I usually debug on port 9090).

This blog explains how to setup Eclipse remote debugging (shudder)

http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html

Ditto Netbeans

https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a

Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html

Here is some good docs on the -Xdebug command in general.

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."

"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."

-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp

Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.

React - How to get parameter value from query string?

React Router v4

Using component

<Route path="/users/:id" component={UserPage}/> 
this.props.match.params.id

The component is automatically rendered with the route props.


Using render

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
this.props.match.params.id

Route props are passed to the render function.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

background-size in shorthand background property (CSS3)

You can do as

 body{
        background:url('equote.png'),url('equote.png');
        background-size:400px 100px,50px 50px;
    }

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

How to Detect Browser Back Button event - Cross Browser

My variant:

const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )

adb uninstall failed

I had a failure when using adb shell uninstall com.package.app/

removed / (so adb shell uninstall com.package.app) and it works

Inheriting constructors

If your compiler supports C++11 standard, there is a constructor inheritance using using (pun intended). For more see Wikipedia C++11 article. You write:

class A
{
    public: 
        explicit A(int x) {}
};

class B: public A
{
     using A::A;
};

This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.

Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.

How do I format axis number format to thousands with a comma in matplotlib?

If you like it hacky and short you can also just update the labels

def update_xlabels(ax):
    xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
    ax.set_xticklabels(xlabels)

update_xlabels(ax)
update_xlabels(ax2)

NGINX - No input file specified. - php Fast/CGI

I tried all the settings above but this fixed my problem. You have to define nginx to check if the php file actually exists in that location. I found try_files $uri = 404; solving that problem.

location ~ \.php$ {
        try_files  $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock; 
        include fastcgi_params;
        fastcgi_index index.php;
}

printf %f with only 2 numbers after the decimal point?

Use this:

printf ("%.2f", 3.14159);

What is the difference between JavaScript and jQuery?

jQuery is a multi-browser (cf. cross-browser) JavaScript library designed to simplify the client-side scripting of HTML. see http://en.wikipedia.org/wiki/JQuery

Unable to find valid certification path to requested target - error even after cert imported

I had the same problem with sbt.
It tried to fetch dependencies from repo1.maven.org over ssl
but said it was "unable to find valid certification path to requested target url".
so I followed this post and still failed to verify a connection.
So I read about it and found that the root cert is not enough, as was suggested by the post,so -
the thing that worked for me was importing the intermediate CA certificates into the keystore.
I actually added all the certificates in the chain and it worked like a charm.

How do you configure HttpOnly cookies in tomcat / java webapps?

For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.

For setting a cookie on a response, rather than doing response.addCookie(cookie) you need to do cookie.saveTo(request, response).

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You need to add extra nginx directive (for ngx_http_proxy_module) in nginx.conf, e.g.:

proxy_read_timeout 300;

Basically the nginx proxy_read_timeout directive changes the proxy timeout, the FcgidIOTimeout is for scripts that are quiet too long, and FcgidBusyTimeout is for scripts that take too long to execute.

Also if you're using FastCGI application, increase these options as well:

FcgidBusyTimeout 300
FcgidIOTimeout 250

Then reload nginx and PHP5-FPM.

Plesk

In Plesk, you can add it in Web Server Settings under Additional nginx directives.

For FastCGI check in Web Server Settings under Additional directives for HTTP.

See: How to fix FastCGI timeout issues in Plesk?

how to use python2.7 pip instead of default pip

There should be a binary called "pip2.7" installed at some location included within your $PATH variable.

You can find that out by typing

which pip2.7

This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

Now, you should be all set, and

which pip2.7

should return the correct output.

How do I use a regular expression to match any string, but at least 3 characters?

If you want to match starting from the beginning of the word, use:

\b\w{3,}

\b: word boundary

\w: word character

{3,}: three or more times for the word character

How do I compare two string variables in an 'if' statement in Bash?

For string equality comparison, use:

if [[ "$s1" == "$s2" ]]

For string does NOT equal comparison, use:

if [[ "$s1" != "$s2" ]]

For the a contains b, use:

if [[ $s1 == *"$s2"* ]]

(and make sure to add spaces between the symbols):

Bad:

if [["$s1" == "$s2"]]

Good:

if [[ "$s1" == "$s2" ]]

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;

Demo

https://jsfiddle.net/simonmysun/2h61Ljbn/4/

Tested under Chrome 75 under Windows 10.

Supported platforms:

Server.Transfer Vs. Response.Redirect

Transfer is entirely server-side. Client address bar stays constant. Some complexity about the transfer of context between requests. Flushing and restarting page handlers can be expensive so do your transfer early in the pipeline e.g. in an HttpModule during BeginRequest. Read the MSDN docs carefully, and test and understand the new values of HttpContext.Request - especially in Postback scenarios. We usually use Server.Transfer for error scenarios.

Redirect terminates the request with a 302 status and client-side roundtrip response with and internally eats an exception (minor server perf hit - depends how many you do a day) Client then navigates to new address. Browser address bar & history updates etc. Client pays the cost of an extra roundtrip - cost varies depending on latency. In our business we redirect a lot we wrote our own module to avoid the exception cost.

How to return a value from __init__ in Python?

You can just set it to a class variable and read it from the main program:

class Foo:
    def __init__(self):
        #Do your stuff here
        self.returncode = 42
bar = Foo()
baz = bar.returncode

How to use localization in C#

In my case

[assembly: System.Resources.NeutralResourcesLanguage("ru-RU")]

in the AssemblyInfo.cs prevented things to work as usual.

Replacing H1 text with a logo image: best method for SEO and accessibility?

You missed title in <a> element.

<h1 id="logo">
  <a href="#" title="..."><span>Stack Overflow</span></a>
</h1>

I suggest to put title in <a> element because client would want to know what is the meaning of that image. Because you have set text-indent for the test of <h1> so, that front end user could get information of main logo while they hover on logo.

Sorting an Array of int using BubbleSort

public class Bubblesort{

  public static int arr[];

  public static void main(String args[]){

    System.out.println("Enter number of element you have in array for performing bubblesort");

    int numbofele = Integer.parseInt(args[0]);

    System.out.println("numer of element entered is"+ "\n" + numbofele);

    arr= new int[numbofele];

    System.out.println("Enter Elements of array");

    System.out.println("The given array is");


    for(int i=0,j=1;i<numbofele;i++,j++){

      arr[i]=Integer.parseInt(args[j]);

      System.out.println(arr[i]);

    }

    boolean swapped = false;

    System.out.println("The sorted array is");

    for(int k=0;k<numbofele-1;k++){


      for(int l=0;l+1<numbofele-k;l++){

        if(arr[l]>arr[l+1]){

          int temp = arr[l];
          arr[l]= arr[l+1];
          arr[l+1]=temp;
          swapped=true;

        } 

      }

         if(!swapped){

            for(int m=0;m<numbofele;m++){

       System.out.println(arr[m]);

    }

      return;

      }


    }

    for(int m=0;m<numbofele;m++){

       System.out.println(arr[m]);

    }


  }


}

Bootstrap 3 with remote Modal

If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:

// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
    var modal = $('#modal'), modalBody = $('#modal .modal-body');

    modal
        .on('show.bs.modal', function () {
            modalBody.load(e.currentTarget.href)
        })
        .modal();
    e.preventDefault();
});

Cannot bulk load. Operating system error code 5 (Access is denied.)

  1. Go to start run=>services.msc=>SQL SERVER(MSSQLSERVER) stop the service
  2. Right click on SQL SERVER(MSSQLSERVER)=> properties=>LogOn Tab=>Local System Account=>OK
  3. Restart the SQL server Management Studio.

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

Text in a flex container doesn't wrap in IE11

The easiest solution I've found is just adding max-width: 100% to the element that's going out of bounds. If you're using it on something like a carousel remember to add a class with the max-width attribute.

Convert string with comma to integer

The following is another method that will work, although as with some of the other methods it will strip decimal places.

a = 1,112
b = a.scan(/\d+/).join().to_i => 1112

Declaring variable workbook / Worksheet vba

to your surprise, you do need to declare variable for workbook and worksheet in excel 2007 or later version. Just add single line expression.

Sub kl()

    Set ws = ThisWorkbook.Sheets("name")
    ws.select
End Sub

Remove everything else and enjoy. But why to select a sheet? selection of sheets is now old fashioned for calculation and manipulation. Just add formula like this

Sub kl()

    Set ws = ThisWorkbook.Sheets("name")
    ws.range("cell reference").formula = "your formula"
'OR in case you are using copy paste formula, just use 'insert or formula method instead of ActiveSheet.paste e.g.:
   ws.range("your cell").formula
'or
   ws.colums("your col: one col e.g. "A:A").insert
'if you need to clear the previous value, just add the following above insert line
   ws.columns("your column").delete

End Sub

ASP.NET postback with JavaScript

Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference

(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)

Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):

function RefreshGrid() {
    <%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}

Check if one date is between two dates

Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.

Something like

if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime()))      alert("date contained");

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

How to use if statements in underscore.js templates?

To check for null values you could use _.isNull from official documentation

isNull_.isNull(object)

Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

curl.h no such file or directory

If after the installation curl-dev luarocks does not see the headers:

find /usr -name 'curl.h'
Example: /usr/include/x86_64-linux-gnu/curl/curl.h

luarocks install lua-cURL CURL_INCDIR=/usr/include/x86_64-linux-gnu/

How to get controls in WPF to fill available space?

Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.

The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.

The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.

How can you search Google Programmatically Java API

In the Terms of Service of google we can read:

5.3 You agree not to access (or attempt to access) any of the Services by any means other than through the interface that is provided by Google, unless you have been specifically allowed to do so in a separate agreement with Google. You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers) and shall ensure that you comply with the instructions set out in any robots.txt file present on the Services.

So I guess the answer is No. More over the SOAP API is no longer available

Not showing placeholder for input type="date" field

Found a better way to handle user basic comprehension with mouseover and opening datepicker on click :

<input type="text" onfocus="(this.type='date')" onmouseover="(this.type = 'date')" onblur="(this.value ? this.type = 'date' : this.type = 'text')" id="date_start" placeholder="Date">

Also hide webkit arrow and make it 100% wide to cover the click :

input[type="date"] {
    position: relative;
}
input[type="date"]::-webkit-calendar-picker-indicator {
  position: absolute;
  height: 100%;
  width: 100%;
  opacity: 0;
  left: 0;
  right: 0;
  top:0;
  bottom: 0;
}

Saving a Excel File into .txt format without quotes

Try this code. This does what you want.

LOGIC

  1. Save the File as a TAB delimited File in the user temp directory
  2. Read the text file in 1 go
  3. Replace "" with blanks and write to the new file at the same time.

CODE (TRIED AND TESTED)

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"

Sub Sample()
    Dim tmpFile As String
    Dim MyData As String, strData() As String
    Dim entireline As String
    Dim filesize As Integer

    '~~> Create a Temp File
    tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"

    ActiveWorkbook.SaveAs Filename:=tmpFile _
    , FileFormat:=xlText, CreateBackup:=False

    '~~> Read the entire file in 1 Go!
    Open tmpFile For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)

    '~~> Get a free file handle
    filesize = FreeFile()

    '~~> Open your file
    Open FlName For Output As #filesize

    For i = LBound(strData) To UBound(strData)
        entireline = Replace(strData(i), """", "")
        '~~> Export Text
        Print #filesize, entireline
    Next i

    Close #filesize

    MsgBox "Done"
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

SNAPSHOTS

Actual Workbook

enter image description here

After Saving

enter image description here

Regular expression for a hexadecimal number?

Just for the record I would specify the following:

/^[xX]?[0-9a-fA-F]{6}$/

Which differs in that it checks that it has to contain the six valid characters and on lowercase or uppercase x in case we have one.

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

What is href="#" and why is it used?

As far as I know it’s usually a placeholder for links that have some JavaScript attached to them. The main point of the link is served by executing the JavaScript code; browsers with JS support then ignore the real link target. If the browser does not support JS, the hash mark essentially turns the link into a no-op. See also unobtrusive JavaScript.

How do I close an open port from the terminal on the Mac?

  1. First find out the Procees id (pid) which has occupied the required port.(e.g 5434)

    ps aux | grep 5434

2.kill that process

   kill -9 <pid>

Sending JSON to PHP using ajax

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

How do I get the first n characters of a string without checking the size or going out of bounds?

If you are lucky enough to develop with Kotlin,
you can use take to achieve your goal.

val someString = "hello"

someString.take(10) // result is "hello"
someString.take(4) // result is "hell" )))

jQuery append() - return appended elements

I think you could do something like this:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.

$child is then the jquery wrapped child div that was added.

Search text in stored procedure in SQL Server

SELECT DISTINCT 
   o.name AS Object_Name,
   o.type_desc
FROM sys.sql_modules m        INNER JOIN        sys.objects o 
     ON m.object_id = o.object_id WHERE m.definition Like '%[String]%';

Practical uses for AtomicInteger

For example, I have a library that generates instances of some class. Each of these instances must have a unique integer ID, as these instances represent commands being sent to a server, and each command must have a unique ID. Since multiple threads are allowed to send commands concurrently, I use an AtomicInteger to generate those IDs. An alternative approach would be to use some sort of lock and a regular integer, but that's both slower and less elegant.

How can I get a precise time, for example in milliseconds in Objective-C?

Also, here is how to calculate a 64-bit NSNumber initialized with the Unix epoch in milliseconds, in case that is how you want to store it in CoreData. I needed this for my app which interacts with a system that stores dates this way.

  + (NSNumber*) longUnixEpoch {
      return [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970] * 1000];
  }

Easy way to test an LDAP User's Credentials

You should check out Softerra's LDAP Browser (the free version of LDAP Administrator), which can be downloaded here :

http://www.ldapbrowser.com/download.htm

I've used this application extensively for all my Active Directory, OpenLDAP, and Novell eDirectory development, and it has been absolutely invaluable.

If you just want to check and see if a username\password combination works, all you need to do is create a "Profile" for the LDAP server, and then enter the credentials during Step 3 of the creation process :

enter image description here

By clicking "Finish", you'll effectively issue a bind to the server using the credentials, auth mechanism, and password you've specified. You'll be prompted if the bind does not work.

Setting up a websocket on Apache?

I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.

First you need to enable proxy and proxy_wstunnel apache modules and the apache configuration file will look like this.

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
      ServerName www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/your_project_public_folder

      SSLEngine on
      SSLCertificateFile    /etc/ssl/certs/path_to_your_ssl_certificate
      SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key

      <Directory /var/www/your_project_public_folder>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
              php_flag display_errors On
      </Directory>
      ProxyRequests Off 
      ProxyPass /wss/  ws://example.com:port_no

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
</IfModule>

in your frontend application use the url "wss://example.com/wss/" this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.

wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important

also interesting part is the last /wss/ is same as proxypass value if you writing proxypass /ws/ then in the front end you should write /ws/ in the end of url.

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

Want custom title / image / description in facebook share link from a flash app

2016 Update

Use the Sharing Debugger to figure out what your problems are.

Make sure you're following the Facebook Sharing Best Practices.

Make sure you're using the Open Graph Markup correctly.

Original Answer

I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.

Is it possible to focus on a <div> using JavaScript focus() function?

Yes - this is possible. In order to do it, you need to assign a tabindex...

<div tabindex="0">Hello World</div>

A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.

Problems with a PHP shell script: "Could not open input file"

I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.

I faced this same error while because I was using parameters in my php file path like this:

/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234

But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:

/usr/bin/php -q /home/**/public_html/cron/job.php id=1234

Just replace the "?" with a space " ".

Why use String.Format?

I can see a number of reasons:

Readability

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs:

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

Format Specifiers (and this includes the fact you can write custom formatters)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs:

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

String Template Persistence

What if I want to store string templates in the database? With string formatting:

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs:

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

Align HTML input fields by :

http://jsfiddle.net/T6zhj/1/

Using display table-cell/row will do the job without any width needed.

The html :

 <html>
  <div>
      <div class="row"><label>Name:</label><input type="text"></div>
      <div class="row"><label>Email Address:</label><input type = "text"></div>
      <div class="row"><label>Description of the input value:</label><input type="text"></div>
  </div>
 </html>

The Css :

label{
    display: table-cell;
    text-align: right;
}
input {
  display: table-cell;
}
div.row{
    display:table-row;
}

ToList().ForEach in Linq

employees.ToList().ForEach(
     emp=>
     {
          collection.AddRange(emp.Departments);
          emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
     });

Escape text for HTML

.NET 4.0 and above:

using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);

Appending a line break to an output file in a shell script

Try:

echo "`date` User `whoami` started the script."$'\n' >> output.log

or just:

echo $'\n' >> output.log

toggle show/hide div with button?

This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.

<!DOCTYPE html>
<html>
<head>
<style>
body  {
  background-color:#777777;
  }
block1{
  display:block; background-color:black; color:white; padding:20px; margin:20px;
  }
block1.a{
  display:none; background-color:black; color:white; padding:20px; margin:20px;
  }
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.

Say you have a button and you set it to the loading state:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. Apparently, button() performs some delayed task. So you'll also have to postpone your disabling:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot.

Converting Array to List

If you are dealing with String[] instead of int[], We can use

ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));

Static method in a generic class?

I ran into this same problem. I found my answer by downloading the source code for Collections.sort in the java framework. The answer I used was to put the <T> generic in the method, not in the class definition.

So this worked:

public class QuickSortArray  {
    public static <T extends Comparable> void quickSort(T[] array, int bottom, int top){
//do it
}

}

Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:

public static void quickSort(Comparable[] array, int bottom, int top){
//do it
}

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Function to Calculate a CRC16 Checksum

There are several details you need to 'match up' with for a particular CRC implementation - even using the same polynomial there can be different results because of minor differences in how data bits are handled, using a particular initial value for the CRC (sometimes it's zero, sometimes 0xffff), and/or inverting the bits of the CRC. For example, sometimes one implementation will work from the low order bits of the data bytes up, while sometimes they'll work from the high order bits down (as yours currently does).

Also, you need to 'push out' the last bits of the CRC after you've run all the data bits through.

Keep in mind that CRC algorithms were designed to be implemented in hardware, so some of how bit ordering is handled may not make so much sense from a software point of view.

If you want to match the CRC16 with polynomial 0x8005 as shown on the lammertbies.nl CRC calculator page, you need to make the following changes to your CRC function:

  • a) run the data bits through the CRC loop starting from the least significant bit instead of from the most significant bit
  • b) push the last 16 bits of the CRC out of the CRC register after you've finished with the input data
  • c) reverse the CRC bits (I'm guessing this bit is a carry over from hardware implementations)

So, your function might look like:

#define CRC16 0x8005

uint16_t gen_crc16(const uint8_t *data, uint16_t size)
{
    uint16_t out = 0;
    int bits_read = 0, bit_flag;

    /* Sanity check: */
    if(data == NULL)
        return 0;

    while(size > 0)
    {
        bit_flag = out >> 15;

        /* Get next bit: */
        out <<= 1;
        out |= (*data >> bits_read) & 1; // item a) work from the least significant bits

        /* Increment bit counter: */
        bits_read++;
        if(bits_read > 7)
        {
            bits_read = 0;
            data++;
            size--;
        }

        /* Cycle check: */
        if(bit_flag)
            out ^= CRC16;

    }

    // item b) "push out" the last 16 bits
    int i;
    for (i = 0; i < 16; ++i) {
        bit_flag = out >> 15;
        out <<= 1;
        if(bit_flag)
            out ^= CRC16;
    }

    // item c) reverse the bits
    uint16_t crc = 0;
    i = 0x8000;
    int j = 0x0001;
    for (; i != 0; i >>=1, j <<= 1) {
        if (i & out) crc |= j;
    }

    return crc;
}

That function returns 0xbb3d for me when I pass in "123456789".

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Selecting default item from Combobox C#

This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

You can use git checkout <file> to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD to throw away any uncommitted changes for all files.

Where does SVN client store user authentication data?

I know I'm uprising a very old topic, but after a couple of hours struggling with this very problem and not finding a solution anywhere else, I think this is a good place to put an answer.

We have some Build Servers WindowsXP based and found this very problem: svn command line client is not caching auth credentials.

We finally found out that we are using Cygwin's svn client! not a "native" Windows. So... this client stores all the auth credentials in /home/<user>/.subversion/auth

This /home directory in Cygwin, in our installation is in c:\cygwin\home. AND: the problem was that the Windows user that is running svn did never ever "logged in" in Cygwin, and so there was no /home/<user> directory.

A simple "bash -ls" from a Windows command terminal created the directory, and after the first access to our SVN server with interactive prompting for access credentials, alás, they got cached.

So if you are using Cygwin's svn client, be sure to have a "home" directory created for the local Windows user.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

This cannot work because ppCombined is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol of the ppCombined collection in memory after you have retrieved the other properties from the database:

var persons = db.Favorites
    .Where(f => f.userId == userId)
    .Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
        new // anonymous object
        {
            personId = p.personId,
            addressId = p.addressId,   
            favoriteId = f.favoriteId,
        })
    .AsEnumerable() // database query ends here, the rest is a query in memory
    .Select(x =>
        new PersonDTO
        {
            personId = x.personId,
            addressId = x.addressId,   
            favoriteId = x.favoriteId,
            personProtocol = ppCombined
                .Where(p => p.personId == x.personId)
                .Select(p => new PersonProtocol
                {
                    personProtocolId = p.personProtocolId,
                    activateDt = p.activateDt,
                    personId = p.personId
                })
                .ToList()
        });

Angular2 - Focusing a textbox on component load

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

this is the best and simplest way, because code "myInput.focus()" runs after input created

WARNING: this solution is acceptable only if you have single element in the form (user will be not able to select other elements)

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

Troubleshooting "Illegal mix of collations" error in mysql

TL;DR

Either change the collation of one (or both) of the strings so that they match, or else add a COLLATE clause to your expression.


  1. What is this "collation" stuff anyway?

    As documented under Character Sets and Collations in General:

    A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

    Suppose that we have an alphabet with four letters: “A”, “B”, “a”, “b”. We give each letter a number: “A” = 0, “B” = 1, “a” = 2, “b” = 3. The letter “A” is a symbol, the number 0 is the encoding for “A”, and the combination of all four letters and their encodings is a character set.

    Suppose that we want to compare two string values, “A” and “B”. The simplest way to do this is to look at the encodings: 0 for “A” and 1 for “B”. Because 0 is less than 1, we say “A” is less than “B”. What we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): “compare the encodings.” We call this simplest of all possible collations a binary collation.

    But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters “a” and “b” as equivalent to “A” and “B”; (2) then compare the encodings. We call this a case-insensitive collation. It is a little more complex than a binary collation.

    In real life, most character sets have many characters: not just “A” and “B” but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules, not just for whether to distinguish lettercase, but also for whether to distinguish accents (an “accent” is a mark attached to a character as in German “Ö”), and for multiple-character mappings (such as the rule that “Ö” = “OE” in one of the two German collations).

    Further examples are given under Examples of the Effect of Collation.

  2. Okay, but how does MySQL decide which collation to use for a given expression?

    As documented under Collation of Expressions:

    In the great majority of statements, it is obvious what collation MySQL uses to resolve a comparison operation. For example, in the following cases, it should be clear that the collation is the collation of column charset_name:

    SELECT x FROM T ORDER BY x;
    SELECT x FROM T WHERE x = x;
    SELECT DISTINCT x FROM T;
    

    However, with multiple operands, there can be ambiguity. For example:

    SELECT x FROM T WHERE x = 'Y';
    

    Should the comparison use the collation of the column x, or of the string literal 'Y'? Both x and 'Y' have collations, so which collation takes precedence?

    Standard SQL resolves such questions using what used to be called “coercibility” rules.

    [ deletia ]

    MySQL uses coercibility values with the following rules to resolve ambiguities:

    • Use the collation with the lowest coercibility value.

    • If both sides have the same coercibility, then:

      • If both sides are Unicode, or both sides are not Unicode, it is an error.

      • If one of the sides has a Unicode character set, and another side has a non-Unicode character set, the side with Unicode character set wins, and automatic character set conversion is applied to the non-Unicode side. For example, the following statement does not return an error:

        SELECT CONCAT(utf8_column, latin1_column) FROM t1;
        

        It returns a result that has a character set of utf8 and the same collation as utf8_column. Values of latin1_column are automatically converted to utf8 before concatenating.

      • For an operation with operands from the same character set but that mix a _bin collation and a _ci or _cs collation, the _bin collation is used. This is similar to how operations that mix nonbinary and binary strings evaluate the operands as binary strings, except that it is for collations rather than data types.

  3. So what is an "illegal mix of collations"?

    An "illegal mix of collations" occurs when an expression compares two strings of different collations but of equal coercibility and the coercibility rules cannot help to resolve the conflict. It is the situation described under the third bullet-point in the above quotation.

    The particular error given in the question, Illegal mix of collations (latin1_general_cs,IMPLICIT) and (latin1_general_ci,IMPLICIT) for operation '=', tells us that there was an equality comparison between two non-Unicode strings of equal coercibility. It furthermore tells us that the collations were not given explicitly in the statement but rather were implied from the strings' sources (such as column metadata).

  4. That's all very well, but how does one resolve such errors?

    As the manual extracts quoted above suggest, this problem can be resolved in a number of ways, of which two are sensible and to be recommended:

    • Change the collation of one (or both) of the strings so that they match and there is no longer any ambiguity.

      How this can be done depends upon from where the string has come: Literal expressions take the collation specified in the collation_connection system variable; values from tables take the collation specified in their column metadata.

    • Force one string to not be coercible.

      I omitted the following quote from the above:

      MySQL assigns coercibility values as follows:

      • An explicit COLLATE clause has a coercibility of 0. (Not coercible at all.)

      • The concatenation of two strings with different collations has a coercibility of 1.

      • The collation of a column or a stored routine parameter or local variable has a coercibility of 2.

      • A “system constant” (the string returned by functions such as USER() or VERSION()) has a coercibility of 3.

      • The collation of a literal has a coercibility of 4.

      • NULL or an expression that is derived from NULL has a coercibility of 5.

      Thus simply adding a COLLATE clause to one of the strings used in the comparison will force use of that collation.

    Whilst the others would be terribly bad practice if they were deployed merely to resolve this error:

    • Force one (or both) of the strings to have some other coercibility value so that one takes precedence.

      Use of CONCAT() or CONCAT_WS() would result in a string with a coercibility of 1; and (if in a stored routine) use of parameters/local variables would result in strings with a coercibility of 2.

    • Change the encodings of one (or both) of the strings so that one is Unicode and the other is not.

      This could be done via transcoding with CONVERT(expr USING transcoding_name); or via changing the underlying character set of the data (e.g. modifying the column, changing character_set_connection for literal values, or sending them from the client in a different encoding and changing character_set_client / adding a character set introducer). Note that changing encoding will lead to other problems if some desired characters cannot be encoded in the new character set.

    • Change the encodings of one (or both) of the strings so that they are both the same and change one string to use the relevant _bin collation.

      Methods for changing encodings and collations have been detailed above. This approach would be of little use if one actually needs to apply more advanced collation rules than are offered by the _bin collation.

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

jQuery rotate/transform

Simply remove the line that rotates it one degree at a time and calls the script forever.

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Then pass the desired value into the function... in this example 45 for 45 degrees.

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
      // For webkit browsers: e.g. Chrome
           $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
           $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
        }

});

Change .css() to .animate() in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...

$(function() {

    var $elie = $("#bkgimg");
    rotate(45);

        function rotate(degree) {
            $elie.animate({
                        '-webkit-transform': 'rotate(' + degree + 'deg)',
                        '-moz-transform': 'rotate(' + degree + 'deg)',
                        '-ms-transform': 'rotate(' + degree + 'deg)',
                        '-o-transform': 'rotate(' + degree + 'deg)',
                        'transform': 'rotate(' + degree + 'deg)',
                        'zoom': 1
            }, 5000);
        }
});

EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate() does not yet support the CSS3 transforms.

This jQuery plugin is supposed to animate the rotation:

http://plugins.jquery.com/project/QTransform

Node/Express file upload

Personally multer didn't work for me after weeks trying to get this file upload thing right. Then I switch to formidable and after a few days I got it working perfectly without any error, multiple files, express and react.js even though react is optional. Here's the guide: https://www.youtube.com/watch?v=jtCfvuMRsxE&t=122s

Recursively list files in Java

Java 8 provides a nice stream to process all files in a tree.

Files.walk(Paths.get(path))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

This provides a natural way to traverse files. Since it's a stream you can do all nice stream operations on the result such as limit, grouping, mapping, exit early etc.

UPDATE: I might point out there is also Files.find which takes a BiPredicate that could be more efficient if you need to check file attributes.

Files.find(Paths.get(path),
           Integer.MAX_VALUE,
           (filePath, fileAttr) -> fileAttr.isRegularFile())
        .forEach(System.out::println);

Note that while the JavaDoc eludes that this method could be more efficient than Files.walk it is effectively identical, the difference in performance can be observed if you are also retrieving file attributes within your filter. In the end, if you need to filter on attributes use Files.find, otherwise use Files.walk, mostly because there are overloads and it's more convenient.

TESTS: As requested I've provided a performance comparison of many of the answers. Check out the Github project which contains results and a test case.

how to delete a specific row in codeigniter?

a simple way:

in view(pass the id value):

<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>

in controller(receive the id):

$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);

in model(get the passed args):

function row_delete($id){}

Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Debug/run standard java in Visual Studio Code IDE and OS X?

Code Runner Extension will only let you "run" java files.

To truly debug 'Java' files follow the quick one-time setup:

  • Install Java Debugger Extension in VS Code and reload.
  • open an empty folder/project in VS code.
  • create your java file (s).
  • create a folder .vscode in the same folder.
  • create 2 files inside .vscode folder: tasks.json and launch.json
  • copy paste below config in tasks.json:
{
    "version": "2.0.0",
    "type": "shell",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "isBackground": true,
    "tasks": [
        {
            "taskName": "build",
            "args": ["-g", "${file}"],
            "command": "javac"
        }
    ]
}
  • copy paste below config in launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Java",
            "type": "java",
            "request": "launch",
            "externalConsole": true,                //user input dosen't work if set it to false :(
            "stopOnEntry": true,
            "preLaunchTask": "build",                 // Runs the task created above before running this configuration
            "jdkPath": "${env:JAVA_HOME}/bin",        // You need to set JAVA_HOME enviroment variable
            "cwd": "${workspaceRoot}",
            "startupClass": "${workspaceRoot}${file}",
            "sourcePath": ["${workspaceRoot}"],   // Indicates where your source (.java) files are
            "classpath": ["${workspaceRoot}"],    // Indicates the location of your .class files
            "options": [],                             // Additional options to pass to the java executable
            "args": []                                // Command line arguments to pass to the startup class
        }

    ],
    "compounds": []
}

You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).


Tip: *To hide .class files in the side explorer of VS code, open settings of VS code and paste the below config:

"files.exclude": {
        "*.class": true
    }

enter image description here

MySQL Cannot Add Foreign Key Constraint

For me it was - you can't omit prefixing the current DB table if you create a FK for a non-current DB referencing the current DB:

USE currrent_db;
ALTER TABLE other_db.tasks ADD CONSTRAINT tasks_fk FOREIGN KEY (user_id) REFERENCES currrent_db.users (id);

If I omit "currrent_db." for users table, I get the FK error. Interesting that SHOW ENGINE INNODB STATUS; shows nothing in this case.

Is there Unicode glyph Symbol to represent "Search"

Displayed correct at Chrome OS - screenshots from this system.

tibetan astrological sign sgra gcan -char rtags U+0F17 ? U+0F17

telephone recorder (U+2315) ? U+2315

lepcha letter gla (U+1C04) ? U+1C04

What's the difference between ASCII and Unicode?

ASCII has 128 code points, 0 through 127. It can fit in a single 8-bit byte, the values 128 through 255 tended to be used for other characters. With incompatible choices, causing the code page disaster. Text encoded in one code page cannot be read correctly by a program that assumes or guessed at another code page.

Unicode came about to solve this disaster. Version 1 started out with 65536 code points, commonly encoded in 16 bits. Later extended in version 2 to 1.1 million code points. The current version is 6.3, using 110,187 of the available 1.1 million code points. That doesn't fit in 16 bits anymore.

Encoding in 16-bits was common when v2 came around, used by Microsoft and Apple operating systems for example. And language runtimes like Java. The v2 spec came up with a way to map those 1.1 million code points into 16-bits. An encoding called UTF-16, a variable length encoding where one code point can take either 2 or 4 bytes. The original v1 code points take 2 bytes, added ones take 4.

Another variable length encoding that's very common, used in *nix operating systems and tools is UTF-8, a code point can take between 1 and 4 bytes, the original ASCII codes take 1 byte the rest take more. The only non-variable length encoding is UTF-32, takes 4 bytes for a code point. Not often used since it is pretty wasteful. There are other ones, like UTF-1 and UTF-7, widely ignored.

An issue with the UTF-16/32 encodings is that the order of the bytes will depend on the endian-ness of the machine that created the text stream. So add to the mix UTF-16BE, UTF-16LE, UTF-32BE and UTF-32LE.

Having these different encoding choices brings back the code page disaster to some degree, along with heated debates among programmers which UTF choice is "best". Their association with operating system defaults pretty much draws the lines. One counter-measure is the definition of a BOM, the Byte Order Mark, a special codepoint (U+FEFF, zero width space) at the beginning of a text stream that indicates how the rest of the stream is encoded. It indicates both the UTF encoding and the endianess and is neutral to a text rendering engine. Unfortunately it is optional and many programmers claim their right to omit it so accidents are still pretty common.

wamp server does not start: Windows 7, 64Bit

For me it got resolved using following link: http://viralpatel.net/blogs/wamp-server-not-getting-started-problem/

where i was using skype and Wamp both installed and running

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

How to connect to my http://localhost web server from Android Emulator

10.0.2.2 is alis made for base machine localhost.

port number same : 1521 no need to change

abs works fine for me ..

What's the right way to pass form element state to sibling/parent elements?

Having used React to build an app now, I'd like to share some thoughts to this question I asked half a year ago.

I recommend you to read

The first post is extremely helpful to understanding how you should structure your React app.

Flux answers the question why should you structure your React app this way (as opposed to how to structure it). React is only 50% of the system, and with Flux you get to see the whole picture and see how they constitute a coherent system.

Back to the question.

As for my first solution, it is totally OK to let the handler go the reverse direction, as the data is still going single-direction.

However, whether letting a handler trigger a setState in P can be right or wrong depending on your situation.

If the app is a simple Markdown converter, C1 being the raw input and C2 being the HTML output, it's OK to let C1 trigger a setState in P, but some might argue this is not the recommended way to do it.

However, if the app is a todo list, C1 being the input for creating a new todo, C2 the todo list in HTML, you probably want to handler to go two level up than P -- to the dispatcher, which let the store update the data store, which then send the data to P and populate the views. See that Flux article. Here is an example: Flux - TodoMVC

Generally, I prefer the way described in the todo list example. The less state you have in your app the better.

button image as form input submit button?

This might be helpful

<form action="myform.cgi"> 
 <input type="file" name="fileupload" value="fileupload" id="fileupload">
 <label for="fileupload"> Select a file to upload</label> 
 <br>
 <input type="image" src="/wp-content/uploads/sendform.png" alt="Submit" width="100"> </form>

Read more: https://html.com/input-type-image/#ixzz5KD3sJxSp

In Git, what is the difference between origin/master vs origin master?

origin/master is an entity (since it is not a physical branch) representing the state of the master branch on the remote origin.

origin master is the branch master on the remote origin.

So we have these:

  • origin/master ( A representation or a pointer to the remote branch)
  • master - (actual branch)
  • <Your_local_branch> (actual branch)
  • <Your_local_branch4> (actual branch)
  • <Your_local_branch4> (actual branch)

Example (in local branch master):

git fetch # get current state of remote repository
git merge origin/master # merge state of remote master branch into local branch
git push origin master # push local branch master to remote branch master

Select count(*) from multiple tables

SELECT  (
        SELECT COUNT(*)
        FROM   tab1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   tab2
        ) AS count2
FROM    dual

Modify the legend of pandas bar plot

If you need to call plot multiply times, you can also use the "label" argument:

ax = df1.plot(label='df1', y='y_var')
ax = df2.plot(label='df2', y='y_var')

While this is not the case in the OP question, this can be helpful if the DataFrame is in long format and you use groupby before plotting.

IIS Manager in Windows 10

@user1664035 & @Attila Mika's suggestion worked. You have to navigate to Control Panel -> Programs And Features -> Turn Windows Features On or Off. And refer to the screenshot. You should check IIS Management console.

Screenshot

Why would a JavaScript variable start with a dollar sign?

As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element

_x000D_
_x000D_
Ex:_x000D_
var name = 'jQuery';_x000D_
var lib = {name:'jQuery',version:1.6};_x000D_
_x000D_
var $dataDiv = $('#myDataDiv');
_x000D_
_x000D_
_x000D_

in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().

Hope it may helped. so finally want to say that it will be a good practice to follow this but not mandatory.

Python error "ImportError: No module named"

Does

(local directory)/site-packages/toolkit

have a __init__.py?

To make import walk through your directories every directory must have a __init__.py file.

How do the major C# DI/IoC frameworks compare?

See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.

I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.

From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.

What does $1 mean in Perl?

The number variables are the matches from the last successful match or substitution operator you applied:

my $string = 'abcdefghi';

if ($string =~ /(abc)def(ghi)/) {
    print "I found $1 and $2\n";
}

Always test that the match or substitution was successful before using $1 and so on. Otherwise, you might pick up the leftovers from another operation.

Perl regular expressions are documented in perlre.

Ignore Typescript Errors "property does not exist on value of type"

The quick and dirty solution is to explicitly cast to any

(y as any).x

The "advantage" is that, the cast being explicit, this will compile even with the noImplicitAny flag set.

The proper solution is to update the typings definition file.

Please note that, when you cast a variable to any, you opt out of type checking for that variable.


Since I am in disclaimer mode, double casting via any combined with a new interface, can be useful in situations where you

  • do not want to update a broken typings file
  • are monkey patching

yet, you still want some form of typing.

Say you want to patch the definition of an instance of y of type OrginalDef with a new property x of type number:

const y: OriginalDef = ...

interface DefWithNewProperties extends OriginalDef {
    x: number
}

const patched = y as any as DefWithNewProperties

patched.x = ....   //will compile

Load and execution sequence of a web page?

Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.

Clearing state es6 React

This is how I handle it:

class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this._initState = {
        a: 1,
        b: 2
      }
    this.state = this._initState;
  }

  _resetState(){
     this.setState(this._initState);
   }
}

Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.

How to verify CuDNN installation?

I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h, so

cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2

did the trick.

Convert DataTable to CSV stream

Update 1

I have modified it to use StreamWriter instead, add an option to check if you need column headers in your output.

public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
    if (dtSource == null || writer == null) return false;

    if (includeHeader)
    {
        string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", columnNames));
        writer.Flush();
    }

    foreach (DataRow row in dtSource.Rows)
    {
        string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", fields));
        writer.Flush();
    }

    return true;
}

As you can see, you can choose the output by initial StreamWriter, if you use StreamWriter(Stream BaseStream), you can write csv into MemeryStream, FileStream, etc.

Origin

I have an easy datatable to csv function, it serves me well:

    public static void DataTableToCsv(DataTable dt, string csvFile)
    {
        StringBuilder sb = new StringBuilder();

        var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in dt.Rows)
        {
            var fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray();
            sb.AppendLine(string.Join(",", fields));
        }

        File.WriteAllText(csvFile, sb.ToString(), Encoding.Default);
    }

TimePicker Dialog from clicking EditText

public void onClick1(View v) {
  DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
  dialog.show();
}

public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
  e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

how to set start value as "0" in chartjs?

If you need use it as a default configuration, just place min: 0 inside the node defaults.scale.ticks, as follows:

defaults: {
  global: {...},
  scale: {
    ...
    ticks: { min: 0 },
  }
},

Reference: https://www.chartjs.org/docs/latest/axes/

Cannot start session without errors in phpMyAdmin

For Xampp, Deleting temp flies from the 'root' folder works for me.

TH

Trust Anchor not found for Android SSL Connection

I had the same problem what i found was that the certificate .crt file i provided missing an intermediate certificate. So I asked all .crt files from my server admin, then concatinated them in reverse order.

Ex. 1. Root.crt 2. Inter.crt 3. myCrt.crt

in windows i executed copy Inter.crt + Root.crt newCertificate.crt

(Here i ignored myCrt.crt)

Then i provided newCertificate.crt file into code via inputstream. Work done.

What's the idiomatic syntax for prepending to a short python list?

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

I got a very simple answer , 100% sure it works:

boolean Touched=false; // this a a global variable

public void changetouchvalue()
{
   Touched=true;
}

// this code is written just before onItemSelectedListener

 spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            System.out.println("Real touch felt.");
            changetouchvalue();
            return false;
        }
    });

//inside your spinner.SetonItemSelectedListener , you have a function named OnItemSelected iside that function write the following code

if(Touched)
{
 // the code u want to do in touch event
}

How to get names of enum entries?

If you only search for the names and iterate later use:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];

Show week number with Javascript?

Martin Schillinger's version seems to be the strictly correct one.

Since I knew I only needed it to work correctly on business week days, I went with this simpler form, based on something I found online, don't remember where:

ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );

It fails in early January on days that belong to the previous year's last week (it produces CW = 0 in those cases) but is correct for everything else.

How to hide/show more text within a certain length (like youtube)

For those who just want a simple Bootstrap solution.

    <style>
     .collapse.in { display: inline !important; }
    </style>

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the
    <span class="collapse" id="more">
      1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    </span>
    <span><a href="#more" data-toggle="collapse">... <i class="fa fa-caret-down"></i></span>

Here's a CodePen example.

Remember to include jquery and bootstrap.min.js in your header.

If you aren't using fontawesome icons, change <i class="fa fa-caret-down"></i> to any icon of your choice.

List directory in Go

We can get a list of files inside a folder on the file system using various golang standard library functions.

  1. filepath.Walk
  2. ioutil.ReadDir
  3. os.File.Readdir

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
)

func main() {
    var (
        root  string
        files []string
        err   error
    )

    root := "/home/manigandan/golang/samples"
    // filepath.Walk
    files, err = FilePathWalkDir(root)
    if err != nil {
        panic(err)
    }
    // ioutil.ReadDir
    files, err = IOReadDir(root)
    if err != nil {
        panic(err)
    }
    //os.File.Readdir
    files, err = OSReadDir(root)
    if err != nil {
        panic(err)
    }

    for _, file := range files {
        fmt.Println(file)
    }
}
  1. Using filepath.Walk

The path/filepath package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.

func FilePathWalkDir(root string) ([]string, error) {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if !info.IsDir() {
            files = append(files, path)
        }
        return nil
    })
    return files, err
}
  1. Using ioutil.ReadDir

ioutil.ReadDir reads the directory named by dirname and returns a list of directory entries sorted by filename.

func IOReadDir(root string) ([]string, error) {
    var files []string
    fileInfo, err := ioutil.ReadDir(root)
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}
  1. Using os.File.Readdir

Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

func OSReadDir(root string) ([]string, error) {
    var files []string
    f, err := os.Open(root)
    if err != nil {
        return files, err
    }
    fileInfo, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}

Benchmark results.

benchmark score

Get more details on this Blog Post

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The addition of a string literal with an std::string yields another std::string. system expects a const char*. You can use std::string::c_str() for that:

string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

Beginner Python: AttributeError: 'list' object has no attribute

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

How do you compare structs for equality in C?

This compliant example uses the #pragma pack compiler extension from Microsoft Visual Studio to ensure the structure members are packed as tightly as possible:

#include <string.h>

#pragma pack(push, 1)
struct s {
  char c;
  int i;
  char buffer[13];
};
#pragma pack(pop)

void compare(const struct s *left, const struct s *right) { 
  if (0 == memcmp(left, right, sizeof(struct s))) {
    /* ... */
  }
}

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How can I get a web site's favicon?

The first thing to look for is /favicon.ico in the site root; something like WebClient.DownloadFile() should do fine. However, you can also set the icon in metadata - for SO this is:

<link rel="shortcut icon"
   href="http://sstatic.net/stackoverflow/img/favicon.ico">

and note that alternative icons might be available; the "touch" one tends to be bigger and higher res, for example:

<link rel="apple-touch-icon"
   href="http://sstatic.net/stackoverflow/img/apple-touch-icon.png">

so you would parse that in either the HTML Agility Pack or XmlDocument (if xhtml) and use WebClient.DownloadFile()

Here's some code I've used to obtain this via the agility pack:

var favicon = "/favicon.ico";
var el=root.SelectSingleNode("/html/head/link[@rel='shortcut icon' and @href]");
if (el != null) favicon = el.Attributes["href"].Value;

Note the icon is theirs, not yours.

Zoom to fit all markers in Mapbox or Leaflet

The 'Answer' didn't work for me some reasons. So here is what I ended up doing:

////var group = new L.featureGroup(markerArray);//getting 'getBounds() not a function error.
////map.fitBounds(group.getBounds());
var bounds = L.latLngBounds(markerArray);
map.fitBounds(bounds);//works!

Pass a javascript variable value into input type hidden value

Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:

http://api.jquery.com/val/

Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:

on some event; assign or set the value of the input:

$('#inputid').val($('#idB').text());

where:

<input id = "inputid" type = "hidden" />

<div id = "idB">This text will be passed to the input</div>

Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.

Beware the differences betwen .html() and .text() when dealing with html forms.

How to check for an empty struct?

Just a quick addition, because I tackled the same issue today:

With Go 1.13 it is possible to use the new isZero() method:

if reflect.ValueOf(session).IsZero() {
     // do stuff...
}

I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual().

Is there a regular expression to detect a valid regular expression?

You can submit the regex to preg_match which will return false if the regex is not valid. Don't forget to use the @ to suppress error messages:

@preg_match($regexToTest, '');
  • Will return 1 if the regex is //.
  • Will return 0 if the regex is okay.
  • Will return false otherwise.

Why does cURL return error "(23) Failed writing body"?

This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.

In curl "url" | grep -qs foo, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.

A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.

E.g.

curl "url" | tac | tac | grep -qs foo

tac is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.

JUnit Eclipse Plugin?

Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

CSS Circle with border

You forgot to set the width of the border! Change border: red; to border:1px solid red;

Here the full code to get the circle:

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

how to store Image as blob in Sqlite & how to retrieve it?

In insert()

public void insert(String tableImg, Object object,
        ContentValues dataToInsert) {

   db.insert(tablename, null, dataToInsert);
}

Hope it helps you.

Slicing a dictionary

set intersection and dict comprehension can be used here

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}

Java Switch Statement - Is "or"/"and" possible?

You can use switch-case fall through by omitting the break; statement.

char c = /* whatever */;

switch(c) {
    case 'a':
    case 'A':
        //get the 'A' image;
        break;
    case 'b':
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'z':
    case 'Z':
        //get the 'Z' image;
        break;
}

...or you could just normalize to lower case or upper case before switching.

char c = Character.toUpperCase(/* whatever */);

switch(c) {
    case 'A':
        //get the 'A' image;
        break;
    case 'B':
        //get the 'B' image;
        break;
    // (...)
    case 'Z':
        //get the 'Z' image;
        break;
}

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Test if a string contains a word in PHP?

if (strpos($string, $word) === FALSE) {
   ... not found ...
}

Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.

Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.

How do I activate a Spring Boot profile when running from IntelliJ?

A probable cause could be that you do not pass the command line parameters into the applications main method. I made the same mistake some weeks ago.

public static final void main(String... args) {
    SpringApplication.run(Application.class, args);
}

How to run travis-ci locally

I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.

If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.

Since Dec 2014 Travis CI offers an Enterprise on-premises version.

http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/

The pricing is part of the article as well:

The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.

Tools for creating Class Diagrams

I use StarUML. It works quite good.

Dealing with float precision in Javascript

> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02

Quick solution:

var _cf = (function() {
  function _shift(x) {
    var parts = x.toString().split('.');
    return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
  }
  return function() { 
    return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
  };
})();

Math.a = function () {
  var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
  function cb(x, y, i, o) { return x + f * y; }
  return Array.prototype.reduce.call(arguments, cb, 0) / f;
};

Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };

Math.m = function () {
  var f = _cf.apply(null, arguments);
  function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
  return Array.prototype.reduce.call(arguments, cb, 1);
};

Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };

> Math.m(0.1, 0.2)
0.02

You can check the full explanation here.

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

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

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

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

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

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

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

What is perm space?

  • JVM has an internal representation of Java objects and those internal representations are stored in the heap (in the young generation or the tenured generation).
  • JVM also has an internal representation of the Java classes and those are stored in the permanent generation

enter image description here

Unit testing with Spring Security

General

In the meantime (since version 3.2, in the year 2013, thanks to SEC-2298) the authentication can be injected into MVC methods using the annotation @AuthenticationPrincipal:

@Controller
class Controller {
  @RequestMapping("/somewhere")
  public void doStuff(@AuthenticationPrincipal UserDetails myUser) {
  }
}

Tests

In your unit test you can obviously call this Method directly. In integration tests using org.springframework.test.web.servlet.MockMvc you can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user() to inject the user like this:

mockMvc.perform(get("/somewhere").with(user(myUserDetails)));

This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:

mockMvc.perform(get("/somewhere").with(sessionUser(myUserDetails)));
/* ... */
private static RequestPostProcessor sessionUser(final UserDetails userDetails) {
    return new RequestPostProcessor() {
        @Override
        public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {
            final SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
            );
            request.getSession().setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext
            );
            return request;
        }
    };
}

Why do Twitter Bootstrap tables always have 100% width?

I've tried to add style="width: auto !important" and works great for me!

How to pass the -D System properties while testing on Eclipse?

You can use java System.properties, for using them from eclipse you could:

  1. Add -Dlabel="label_value" in the VM arguments of the test Run Configuration like this:

eclipse_vm_config

  1. Then run the test:

    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    
    public class Main {
        @Test
        public void test(){
            System.out.println(System.getProperty("label"));
            assertEquals("label_value", System.getProperty("label"));
        }
    }
    
  2. Finally it should pass the test and output this in the console:

    label_value
    

Search for a string in Enum and return the Enum

You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>

The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse - instead you end up writing something like this in your code:

MyColours colour = Enum<MyColours>.Parse(stringValue); 

Or check out some of the comments in the same post which talk about using an extension method to achieve similar.

How to import multiple .csv files at once?

With many files and many cores, fread xargs cat (described below) is about 50x faster than the fastest solution in the top 3 answers.

rbindlist lapply read.delim  500s <- 1st place & accepted answer
rbindlist lapply fread       250s <- 2nd & 3rd place answers
rbindlist mclapply fread      10s
fread xargs cat                5s

Time to read 121401 csvs into a single data.table. Each time is an average of three runs then rounded. Each csv has 3 columns, one header row, and, on average, 4.510 rows. Machine is a GCP VM with 96 cores.

The top three answers by @A5C1D2H2I1M1N2O1R2T1, @leerssej, and @marbel and are all essentially the same: apply fread (or read.delim) to each file, then rbind/rbindlist the resulting data.tables. I usually use the rbindlist(lapply(list.files("*.csv"),fread)) form.

This is better than other R-internal alternatives, and fine for a small number of large csvs, but not the best for a large number of small csvs when speed matters. In that case, it can be much faster to first use cat, as @Spacedman suggests in the 4th-ranked answer. I'll add some detail on how to do this from within R:

x = fread(cmd='cat *.csv', header=F)

However, what if each csv has a header?

x = fread(cmd="awk 'NR==1||FNR!=1' *.csv", header=T)

And what if you have so many files that the *.csv shell glob fails?

x = fread(cmd='find . -name "*.csv" | xargs cat', header=F)

And what if all files have a header AND there are too many files?

header = fread(cmd='find . -name "*.csv" | head -n1 | xargs head -n1', header=T)
x = fread(cmd='find . -name "*.csv" | xargs tail -q -n+2', header=F)
names(x) = names(header)

And what if the resulting concatenated csv is too big for system memory?

system('find . -name "*.csv" | xargs cat > combined.csv')
x = fread('combined.csv', header=F)

With headers?

system('find . -name "*.csv" | head -n1 | xargs head -n1 > combined.csv')
system('find . -name "*.csv" | xargs tail -q -n+2 >> combined.csv')
x = fread('combined.csv', header=T)

Finally, what if you don't want all .csv in a directory, but rather a specific set of files? (Also, they all have headers.) (This is my use case.)

fread(text=paste0(system("xargs cat|awk 'NR==1||$1!=\"<column one name>\"'",input=paths,intern=T),collapse="\n"),header=T,sep="\t")

and this is about the same speed as plain fread xargs cat :)

Note: for data.table pre-v1.11.6 (19 Sep 2018), omit the cmd= from fread(cmd=.

Addendum: using the parallel library's mclapply in place of serial lapply, e.g., rbindlist(lapply(list.files("*.csv"),fread)) is also much faster than rbindlist lapply fread.

To sum up, if you're interested in speed, and have many files and many cores, fread xargs cat is about 50x faster than the fastest solution in the top 3 answers.

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

AdBlockers usually have some rules, i.e. they match the URIs against some type of expression (sometimes they also match the DOM against expressions, not that this matters in this case).

Having rules and expressions that just operate on a tiny bit of text (the URI) is prone to create some false-positives...

Besides instructing your users to disable their extensions (at least on your site) you can also get the extension and test which of the rules/expressions blocked your stuff, provided the extension provides enough details about that. Once you identified the culprit, you can either try to avoid triggering the rule by using different URIs, report the rule as incorrect or overly-broad to the team that created it, or both. Check the docs for a particular add-on on how to do that.

For example, AdBlock Plus has a Blockable items view that shows all blocked items on a page and the rules that triggered the block. And those items also including XHR requests.

Blockable items

Convert an image to grayscale in HTML/CSS

be An alternative for older browser could be to use mask produced by pseudo-elements or inline tags.

Absolute positionning hover an img (or text area wich needs no click nor selection) can closely mimic effects of color scale , via rgba() or translucide png .

It will not give one single color scale, but will shades color out of range.

test on code pen with 10 different colors via pseudo-element, last is gray . http://codepen.io/gcyrillus/pen/nqpDd (reload to switch to another image)

Up, Down, Left and Right arrow keys do not trigger KeyDown event

    protected override bool IsInputKey(Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Right:
            case Keys.Left:
            case Keys.Up:
            case Keys.Down:
                return true;
            case Keys.Shift | Keys.Right:
            case Keys.Shift | Keys.Left:
            case Keys.Shift | Keys.Up:
            case Keys.Shift | Keys.Down:
                return true;
        }
        return base.IsInputKey(keyData);
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        switch (e.KeyCode)
        {
            case Keys.Left:
            case Keys.Right:
            case Keys.Up:
            case Keys.Down:
                if (e.Shift)
                {

                }
                else
                {
                }
                break;                
        }
    }

Get the current file name in gulp.src()

Here is another simple way.

var es, log, logFile;

es = require('event-stream');

log = require('gulp-util').log;

logFile = function(es) {
  return es.map(function(file, cb) {
    log(file.path);
    return cb();
  });
};

gulp.task("do", function() {
 return gulp.src('./examples/*.html')
   .pipe(logFile(es))
   .pipe(gulp.dest('./build'));
});

What's the difference between git clone --mirror and git clone --bare

A clone copies the refs from the remote and stuffs them into a subdirectory named 'these are the refs that the remote has'.

A mirror copies the refs from the remote and puts them into its own top level - it replaces its own refs with those of the remote.

This means that when someone pulls from your mirror and stuffs the mirror's refs into thier subdirectory, they will get the same refs as were on the original. The result of fetching from an up-to-date mirror is the same as fetching directly from the initial repo.

Keytool is not recognized as an internal or external command

You are getting that error because the keytool executable is under the bin directory, not the lib directory in your example. And you will need to add the location of your keystore as well in the command line. There is a pretty good reference to all of this here - Jrun Help / Import certificates | Certificate stores | ColdFusion

The default truststore is the JRE's cacerts file. This file is typically located in the following places:

  • Server Configuration:

    cf_root/runtime/jre/lib/security/cacerts

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/lib/security/cacerts

  • Sun JDK installation:

    jdk_root/jre/lib/security/cacerts

  • Consult documentation for other J2EE application servers and JVMs


The keytool is part of the Java SDK and can be found in the following places:

  • Server Configuration:

    cf_root/runtime/bin/keytool

  • Multiserver/J2EE on JRun 4 Configuration:

    jrun_root/jre/bin/keytool

  • Sun JDK installation:

    jdk_root/bin/keytool

  • Consult documentation for other J2EE application servers and JVMs

So if you navigate to the directory where the keytool executable is located your command line would look something like this:

keytool -list -v -keystore JAVA_HOME\jre\lib\security\cacert -storepass changeit

You will need to supply pathing information depending on where you run the keytool command from and where your certificate file resides.

Also, be sure you are updating the correct cacerts file that ColdFusion is using. In case you have more than one JRE installed on that server. You can verify the JRE ColdFusion is using from the administrator under the 'System Information'. Look for the Java Home line.

What Language is Used To Develop Using Unity

One can use any one of the following three scripting languages:

  1. JavaScript
  2. C#
  3. Boo

But my personal choice is C# because I find it faster in comparison to other two.

Android: How to turn screen on and off programmatically?

Are you sure you requested the proper permission in your Manifest file?

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

You can use the AlarmManager1 class to fire off an intent that starts your activity and acquires the wake lock. This will turn on the screen and keep it on. Releasing the wakelock will allow the device to go to sleep on its own.

You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)

How do I make a text input non-editable?

You can add the attribute readonly to the input:

<input type="text" value="3"
       class="field left" readonly="readonly">

More info: http://www.w3schools.com/tags/att_input_readonly.asp

Align printf output in Java

You can refer to this blog for printing formatted coloured text on console

https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");

//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";

System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases           |Passed   |Failed   |Skipped  |%n");
System.out.format("+----------------------+---------+---------+---------+%n");

String formattedMessage = "TEST_01".trim();

leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}

How can I get the iOS 7 default blue color programmatically?

iOS 7 default blue color is R:0.0 G:122.0 B:255.0

UIColor *ios7BlueColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];

Why is using "for...in" for array iteration a bad idea?

In addition to the reasons given in other answers, you may not want to use the "for...in" structure if you need to do math with the counter variable because the loop iterates through the names of the object's properties and so the variable is a string.

For example,

for (var i=0; i<a.length; i++) {
    document.write(i + ', ' + typeof i + ', ' + i+1);
}

will write

0, number, 1
1, number, 2
...

whereas,

for (var ii in a) {
    document.write(i + ', ' + typeof i + ', ' + i+1);
}

will write

0, string, 01
1, string, 11
...

Of course, this can easily be overcome by including

ii = parseInt(ii);

in the loop, but the first structure is more direct.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

This is absolutely doable with some flexbox magic. Have a look at this pen.

You need css like this:

aside {
  background-color: cyan;
  position: fixed;
  max-height: 100vh;
  width: 25%;
  display: flex;
  flex-direction: column;
}

ul {
  overflow-y: scroll;
}

section {
  width: 75%;
  float: right;
  background: orange;
}

This will work in IE10+

How to create a hex dump of file containing only the hex characters without spaces in bash?

The other answers are preferable, but for a pure Bash solution, I've modified the script in my answer here to be able to output a continuous stream of hex characters representing the contents of a file. (Its normal mode is to emulate hexdump -C.)

Grouping into interval of 5 minutes within a time range

I found out that with MySQL probably the correct query is the following:

SELECT SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,  
                                 '%Y-%m-%d %H:%i:%S' ) , 1, 19 ) AS ts_CEILING,
SUM(value)
FROM group_interval
GROUP BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,  
                                   '%Y-%m-%d %H:%i:%S' ) , 1, 19 )
ORDER BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,  
                                   '%Y-%m-%d %H:%i:%S' ) , 1, 19 ) DESC

Let me know what you think.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

You have just add FormsModule and import the FormsModule in your app.module.ts file.

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

imports: [
    BrowserModule, FormsModule 
],

Just add the above two lines in your app.module.ts. It's working fine.

How to delete an SMS from the inbox in Android programmatically?

Use this function to delete specific message thread or modify according your needs:

public void delete_thread(String thread) 
{ 
  Cursor c = getApplicationContext().getContentResolver().query(
  Uri.parse("content://sms/"),new String[] { 
  "_id", "thread_id", "address", "person", "date","body" }, null, null, null);

 try {
  while (c.moveToNext()) 
      {
    int id = c.getInt(0);
    String address = c.getString(2);
    if (address.equals(thread)) 
        {
     getApplicationContext().getContentResolver().delete(
     Uri.parse("content://sms/" + id), null, null);
    }

       }
} catch (Exception e) {

  }
}

Call this function simply below:

delete_thread("54263726");//you can pass any number or thread id here

Don't forget to add android mainfest permission below:

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

Find duplicate lines in a file and count how many time each line was duplicated?

In windows using "Windows PowerShell" I used the command mentioned below to achieve this

Get-Content .\file.txt | Group-Object | Select Name, Count

Also we can use the where-object Cmdlet to filter the result

Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count

How to call a parent method from child class in javascript?

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do: ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments: ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.

Browser detection in JavaScript?

This little library may help you. But be aware that browser detection is not always the solution.

How to exit an if clause

The only thing that would apply this without additional methods is elif as the following example

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 

(Built-in) way in JavaScript to check if a string is a valid number

parseInt(), but be aware that this function is a bit different in the sense that it for example returns 100 for parseInt("100px").