Programs & Examples On #Nexus

Nexus is a Repository Manager for Maven, NuGet and other binary artifact repositories. Repository managers serve two purposes: they act as highly configurable proxies between your organization and the public repositories and they also provide an organization with a deployment destination for your internally generated artifacts.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

Error when deploying an artifact in Nexus

Just to create a separate answer. The answer is actually found in a comment for the accepted answer.

Try changing the version of your artefact to end with -SNAPSHOT.

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Upload artifacts to Nexus, without Maven

for those who need it in Java, using apache httpcomponents 4.0:

public class PostFile {
    protected HttpPost httppost ;
    protected MultipartEntity mpEntity; 
    protected File filePath;

    public PostFile(final String fullUrl, final String filePath){
        this.httppost = new HttpPost(fullUrl);
        this.filePath = new File(filePath);        
        this.mpEntity = new MultipartEntity();
    }

    public void authenticate(String user, String password){
        String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
        httppost.setHeader("Authorization", "Basic " + encoding);
    }
    private void addParts() throws UnsupportedEncodingException{
        mpEntity.addPart("r", new StringBody("repository id"));
        mpEntity.addPart("g", new StringBody("group id"));
        mpEntity.addPart("a", new StringBody("artifact id"));
        mpEntity.addPart("v", new StringBody("version"));
        mpEntity.addPart("p", new StringBody("packaging"));
        mpEntity.addPart("e", new StringBody("extension"));

        mpEntity.addPart("file", new FileBody(this.filePath));

    }

    public String post() throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        addParts();
        httppost.setEntity(mpEntity);
        HttpResponse response = httpclient.execute(httppost);

        System.out.println("executing request " + httppost.getRequestLine());
        System.out.println(httppost.getEntity().getContentLength());

        HttpEntity resEntity = response.getEntity();

        String statusLine = response.getStatusLine().toString();
        System.out.println(statusLine);
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
            resEntity.consumeContent();
        }
        return statusLine;
    }
}

How to manually deploy artifacts in Nexus Repository Manager OSS 3

You can upload artifacts via their native publishing capabilities (e.g. maven deploy, npm publish).

You can also upload artifacts to "raw" repositories via a simple curl request, e.g.

curl --fail -u admin:admin123 --upload-file foo.jar 'http://my-nexus-server.com:8081/repository/my-raw-repo/'

Maven error: Not authorized, ReasonPhrase:Unauthorized

The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.

How to get relative path from absolute path

There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: PathRelativePathTo()

I'm not aware of any way to access this from .NET other than to P/Invoke it, though.

How to add a border just on the top side of a UIView

I made some changes to Dan's answer so that I could add borders to multiple edges with one command:

infoView.addBorder(toEdges: [.left, .bottom, .right], color: borderColor, thickness: 1)

Here's the full code:

extension UIView {
    func addBorder(toEdges edges: UIRectEdge, color: UIColor, thickness: CGFloat) {

        func addBorder(toEdge edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
            let border = CALayer()
            border.backgroundColor = color.cgColor

            switch edges {
            case .top:
                border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
            case .bottom:
                border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
            case .left:
                border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
            case .right:
                border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
            default:
                break
            }

            layer.addSublayer(border)
        }

        if edges.contains(.top) || edges.contains(.all) {
            addBorder(toEdge: .top, color: color, thickness: thickness)
        }

        if edges.contains(.bottom) || edges.contains(.all) {
            addBorder(toEdge: .bottom, color: color, thickness: thickness)
        }

        if edges.contains(.left) || edges.contains(.all) {
            addBorder(toEdge: .left, color: color, thickness: thickness)
        }

        if edges.contains(.right) || edges.contains(.all) {
            addBorder(toEdge: .right, color: color, thickness: thickness)
        }
    }
}

Best cross-browser method to capture CTRL+S with JQuery?

$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});

Key codes can differ between browsers, so you may need to check for more than just 115.

jQuery to loop through elements with the same class

$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});

Bad Request - Invalid Hostname IIS7

I got this error when I tried to call a webservice using "localhost". I fixed it by using the actual IP instead (192.168...)

how to display progress while loading a url to webview in android?

set a WebViewClient to your WebView, start your progress dialog on you onCreate() method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Main extends Activity {
    private WebView webview;
    private static final String TAG = "Main";
    private ProgressDialog progressBar;  

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);

        this.webview = (WebView)findViewById(R.id.webview);

        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");

        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "Processing webview url click...");
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "Finished loading URL: " +url);
                if (progressBar.isShowing()) {
                    progressBar.dismiss();
                }
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.e(TAG, "Error: " + description);
                Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
                alertDialog.show();
            }
        });
        webview.loadUrl("http://www.google.com");
    }
}

your main.xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <WebView android:id="@string/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
</LinearLayout>

htaccess redirect all pages to single page

This will direct everything from the old host to the root of the new host:

RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]

JQuery string contains check

If you are worrying about Case sensitive change the case and compare the string.

 if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
        {

            alert("found");
        }

How to rename a directory/folder on GitHub website?

I had an issue with github missing out on some case sensitive changes to folders. I needed to keep migration history so an example of how I changed "basicApp" folder in github to "basicapp"

$ git ls-files
$ git mv basicApp basicapp_temp
$ git add .
$ git commit -am "temporary change"
$ git push origin master
$ git mv basicapp_temp basicapp
$ git add .
$ git commit -am "change to desired name"
$ git push origin master

PS: git ls-files will show you how github sees your folder name

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

Ruby on Rails - Import Data from a CSV file

Use this gem: https://rubygems.org/gems/active_record_importer

class Moulding < ActiveRecord::Base
  acts_as_importable
end

Then you may now use:

Moulding.import!(file: File.open(PATH_TO_FILE))

Just be sure to that your headers match the column names of your table

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

It's working fine try this.Link

UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
[top presentViewController:secondView animated:YES completion: nil];

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

https://github.com/rackt/react-router/blob/e7c6f3d848e55dda11595447928e843d39bed0eb/examples/query-params/app.js#L4 Router is also one of the properties of react-router. So change your modules require code like that:

  var reactRouter = require('react-router')
  var Router = reactRouter.Router
  var Route = reactRouter.Route
  var Link = reactRouter.Link

If you want to use ES6 syntax the link use(import), use babel as helper.

BTW, to make your code works, we can add {this.props.children} in the App, like

render() {
  return (
    <div>
      <h1>App</h1>
      <ul>
        <li><Link to="/about">About</Link></li>
      </ul>
      {this.props.children}
    </div>

  )
}

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

Checkout another branch when there are uncommitted changes on the current branch

If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.

Example:

$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"

$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
     # experiment now contains changes that master doesn't have
     # any future changes to this file will keep you from changing branches
     # until the changes are stashed or committed

$ echo "and we're back" >> file.txt  # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

This goes for untracked files as well as tracked files. Here's an example for an untracked file.

Example:

$ git checkout -b experimental  # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"

$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
    file.txt
Please move or remove them before you can switch branches.
Aborting

A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...

$ echo 'experimental change' >> file.txt # change to existing tracked file
   # I want to save these, but not on master

$ git checkout -b experiment
M       file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"

Double border with different color

I use outline a css 2 property that simply works. Check this out, is simple and even easy to animate:

_x000D_
_x000D_
.double-border {_x000D_
  display: block;_x000D_
  clear: both;_x000D_
  background: red;_x000D_
  border: 5px solid yellow;_x000D_
  outline: 5px solid blue;_x000D_
  transition: 0.7s all ease-in;_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
}_x000D_
.double-border:hover {_x000D_
  background: yellow;_x000D_
  outline-color: red;_x000D_
  border-color: blue;_x000D_
}
_x000D_
<div class="double-border"></div>
_x000D_
_x000D_
_x000D_

How do you get the list of targets in a makefile?

This help target will only print targets which have ## followed by a description. This allows for documenting both public and private targets. Using the .DEFAULT_GOAL makes the help more discoverable.

Only sed, xargs and printf used which are pretty common.

Using the < $(MAKEFILE_LIST) allows for the makefile to be called something other than Makefile for instance Makefile.github

You can customize the output to suit your preference in the printf. This example is set up to match the OP's request for rake style output

When cutting and pasting the below make file, don't forget to change the 4 spaces indentation to tabs.

# vim:ft=make
# Makefile

.DEFAULT_GOAL := help
.PHONY: test help

help:  ## these help instructions
    @sed -rn 's/^([a-zA-Z_-]+):.*?## (.*)$$/"\1" "\2"/p' < $(MAKEFILE_LIST) | xargs printf "make %-20s# %s\n"

lint: ## style, bug and quality checker
    pylint src test

private: # for internal usage only
    @true

test: private ## run pytest with coverage
    pytest --cov test


Here is the output from the Makefile above. Notice the private target doesn't get output because it only has a single # for it's comment.

$ make
make help                # these help instructions
make lint                # style, bug and quality checker
make test                # run pytest with coverage

CSS background-image not working

<span class="btn-pTool">
         <a class="btn-pToolName" href="#"></a>
     </span>

Try to add display:block to .btn-pTool, and give it a width and height.

Also in your code both tbn-pTool and btn-pToolName have no text content, so that may result in them not being displayed at all.

You can try to force come content in them this way

.btn-pTool, .btn-pToolName {
    content: " ";
}

Center a DIV horizontally and vertically

I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.

My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.

So, with this HTML:

<div class="parentElement">  
  <div class="childElement">  
    ...Some Contents...  
  </div>  
</div>  

This CSS:

.parentElement {  
  position:relative;
  width:960px;
}
.childElement {
  position:absolute;
  top:50%;
  left:50%;
}

This jQuery might be useful:

$('.childElement').each(function(){
  // determine the real dimensions of the element: http://api.jquery.com/outerWidth/
  var x = $(this).outerWidth();
  var y = $(this).outerHeight();
  // adjust parent dimensions to fit child
  if($(this).parent().height() < y) {
    $(this).parent().css({height: y + 'px'});
  }
  // offset the child element using negative margins to "center" in both axes
  $(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});

Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...).

Error Code: 1005. Can't create table '...' (errno: 150)

I had the very same error message. Finally I figured out I misspelled the name of the table in the command:

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);

versus

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);

I wonder why on earth MySQL cannot tell such a table does not exist...

Java - creating a new thread

A simpler way can be :

new Thread(YourSampleClass).start();    

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

if you are using httpd/apache, you can add a file something like ws.conf and add this code to it. Also, this solution can proxy something like this "http://localhost:6001/socket.io" to just this "http://localhost/socket.io"

<VirtualHost *:80>
    RewriteEngine on

    #redirect WebSocket
    RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyPass        /socket.io http://localhost:6001/socket.io
    ProxyPassReverse /socket.io http://localhost:6001/socket.io
</VirtualHost>

Is it possible to send a variable number of arguments to a JavaScript function?

Yes you can pass variable no. of arguments to a function. You can use apply to achieve this.

E.g.:

var arr = ["Hi","How","are","you"];

function applyTest(){
    var arg = arguments.length;
    console.log(arg);
}

applyTest.apply(null,arr);

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

Here is a minor improvement to CMS's solution:

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

"Hello World!".startsWith("He"); // true

 var data = "Hello world";
 var input = 'He';
 data.startsWith(input); // true

Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.

Using ! is slightly faster and more concise than === 0 though not as readable.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

ng: command not found while creating new project using angular-cli

if you find this error when you are installing angular-cli, -bash: ng: command not found try this it works,

After removing Node from your system

install NVM from here https://github.com/creationix/nvm
Install Node via NVM: nvm install stable
run npm install -g angular-cli

Mark error in form using Bootstrap

Can use CSS to show error message only on error.

.form-group.has-error .help-block {
    display: block;
}

.form-group .help-block {
    display: none;
}


<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

Best way to parse RSS/Atom feeds with PHP

The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.

String isNullOrEmpty in Java?

from Apache commons-lang.

The difference between empty and blank is : a string consisted of whitespaces only is blank but isn't empty.

I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.

How to clear basic authentication details in chrome

Shortest way: Click lock icon in address bar. Then click Site settings, then click Reset permissions

enter image description here enter image description here

Running multiple AsyncTasks at the same time -- not possible?

Making @sulai suggestion more generic :

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}   

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

C++ style cast from unsigned char * to const char *

You would need to use a reinterpret_cast<> as the two types you are casting between are unrelated to each other.

How to get file name when user select a file via <input type="file" />?

just tested doing this and it seems to work in firefox & IE

<html>
    <head>
        <script type="text/javascript">
            function alertFilename()
            {
                var thefile = document.getElementById('thefile');
                alert(thefile.value);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="file" id="thefile" onchange="alertFilename()" />
            <input type="button" onclick="alertFilename()" value="alert" />
        </form>
    </body>
</html>

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

conda will only keep track of the packages it installed. And pip will give you the packages that were either installed using the pip installer itself or they used setuptools in their setup.py so conda build generated the egg information. So you have basically three options.

  1. You can take the union of the conda list and pip freeze and manage packages that were installed using conda (that show in the conda list) with the conda package manager and the ones that are installed with pip (that show in pip freeze but not in conda list) with pip.

  2. Install in your environment only the python, pip and distribute packages and manage everything with pip. (This is not that trivial if you're on Windows...)

  3. Build your own conda packages, and manage everything with conda.

I would personally recommend the third option since it's very easy to build conda packages. There is a git repository of example recipes on the continuum's github account. But it usually boils down to:

 conda skeleton pypi PACKAGE
 conda build PACKAGE

or just:

conda pipbuild PACKAGE

Also when you have built them once, you can upload them to https://binstar.org/ and just install from there.

Then you'll have everything managed using conda.

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Something happened in Java 8 Update 91 that broke existing JSP code. That seems pretty clear. Here is a sample of similar questions and bug reports:

All these are about problems with Java 8 Update 91 (or later) that are not present when using earlier JRE/JDK versions.


The following OpenJDK changeset from 22 January 2016 appears to be related: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/32f64c19b5fb (commit message "8144430: Improve JMX connections"). The changeset seems to be related to this vulnerability, https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-3427, which is mentioned in a comment to this Red Hat bug report, https://bugzilla.redhat.com/show_bug.cgi?id=1336481.

The Update 91 release notes document mentions JDK-8144430 (non-public ticket): http://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html.

In "Oracle Critical Patch Update Advisory - April 2016", the CVE-2016-3427 vulnerability is mentioned: http://www.oracle.com/technetwork/security-advisory/cpuapr2016v3-2985753.html.

How to modify PATH for Homebrew?

To avoid unnecessary duplication, I added the following to my ~/.bash_profile

case ":$PATH:" in
  *:/usr/local/bin:*) ;;     # do nothing if $PATH already contains /usr/local/bin
  *) PATH=/usr/local/bin:$PATH ;;  # in every other case, add it to the front
esac

Credit: https://superuser.com/a/580611

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

111 - the one you are using is Japan yy/mm/dd.

I guess the one you are looking for is 103, that is dd/mm/yyyy.

So you should try:

 SELECT convert(datetime, '23/07/2009', 103)

In a bootstrap responsive page how to center a div

Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
    <div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
        <div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Javascript How to define multiple variables on a single line?

Why not doing it in two lines?

var a, b, c, d;    // All in the same scope
a = b = c = d = 1; // Set value to all.

The reason why, is to preserve the local scope on variable declarations, as this:

var a = b = c = d = 1;

will lead to the implicit declarations of b, c and d on the window scope.

Adding a tooltip to an input box

I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:

<input title="This is the text of the tooltip" value="44"/>

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.

Your module should be :

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ContactComponent
  ]
})
export class ContactModule {}

Can I have a video with transparent background using HTML5 video tag?

Update: Webm with an alpha channel is now supported in Chrome and Firefox.

For other browers, there are workarounds, but they involve re-rendering the video using Canvas and it is kind of a hack. seeThru is one example. It works pretty well on HTML5 desktop browsers (even IE9) but it doesn't seem to work very well on mobile. I couldn't get it to work at all on Chrome for Android. It did work on Firefox for Android but with a pretty lousy framerate. I think you might be out of luck for mobile, although I'd love to be proven wrong.

Add Text on Image using PIL

To add text on an image file, just copy/paste the code below

<?php
$source = "images/cer.jpg";
$image = imagecreatefromjpeg($source);
$output = "images/certificate".rand(1,200).".jpg";
$white = imagecolorallocate($image,255,255,255);
$black = imagecolorallocate($image,7,94,94);
$font_size = 30;
$rotation = 0;
$origin_x = 250;
$origin_y = 450;
$font = __DIR__ ."/font/Roboto-Italic.ttf";
$text = "Dummy";
$text1 = imagettftext($image,$font_size,$rotation,$origin_x,$origin_y,$black,$font,$text);
     imagejpeg($image,$output,99);
?> <img src="<?php echo $output; ?>"> <a href="<?php echo $output;    ?>" download="<?php echo $output; ?>">Download Certificate</a>

Reset ID autoincrement ? phpmyadmin

You can also do this in phpMyAdmin without writing SQL.

  • Click on a database name in the left column.
  • Click on a table name in the left column.
  • Click the "Operations" tab at the top.
  • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
  • Input desired value and click the "Go" button below.

Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

What's the fastest way to loop through an array in JavaScript?

This looks to be the fastest way by far...

var el;
while (el = arr.shift()) {
  el *= 2;
}

Take into account that this will consume the array, eating it, and leaving nothing left...

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

ImportError: No module named 'MySQL'

Try that out bud

sudo wget http://cdn.mysql.com//Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz

gunzip mysql-connector-python-2.1.3.tar.gz

tar xf mysql-connector-python-2.1.3.tar

cd mysql-connector-python-2.1.3

sudo python3 setup.py install

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

How do I make a redirect in PHP?

Use:

<?php
    header('Location: redirectpage.php');
    header('Location: redirectpage.php');
    exit();
    echo "<script>location.href='redirectpage.php';</script>";
?>

This is a regular and normal PHP redirect, but you can make a redirecting page with a few seconds wait by the below code:

<?php
    header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>

What's the best way to send a signal to all members of a process group?

If you know the pid of the thing you want to kill, you can usually go from the session id, and everything in the same session. I'd double check, but I used this for scripts starting rsyncs in loops that I want to die, and not start another (because of the loop) as it would if I'd just killall'd rsync.

kill $(ps -o pid= -s $(ps -o sess --no-heading --pid 21709))

If you don't know the pid you can still nest more

kill $(ps -o pid= -s $(ps -o sess --no-heading --pid $(pgrep rsync )))

Get the content of a sharepoint folder with Excel VBA

The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.

Add references to the following ActiveX libraries in VBA:

  • Windows Script Host Object Model (wshom.ocx) - for WshNetwork
  • Microsoft Scripting Runtime (scrrun.dll) - for FileSystemObject

Create a new class module, call it DriveMapper and add the following code:

Option Explicit

Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork

Private Sub Class_Terminate()
  UnmapDrive
End Sub

Public Function MapDrive(NetworkPath As String) As Scripting.Folder
  Dim DriveLetter As String, i As Integer

  UnmapDrive

  For i = Asc("Z") To Asc("A") Step -1
    DriveLetter = Chr(i)
    If Not oFSO.DriveExists(DriveLetter) Then
      oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
      Set oMappedDrive = oFSO.GetDrive(DriveLetter)
      Set MapDrive = oMappedDrive.RootFolder
      Exit For
    End If
  Next i
End Function

Private Sub UnmapDrive()
  If Not oMappedDrive Is Nothing Then
    If oMappedDrive.IsReady Then
      oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
    End If
    Set oMappedDrive = Nothing
  End If
End Sub

Then you can implement it in your code:

Sub test()
  Dim dm As New DriveMapper
  Dim sharepointFolder As Scripting.Folder

  Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")

  Debug.Print sharepointFolder.Path
End Sub

socket.emit() vs. socket.send()

socket.send is implemented for compatibility with vanilla WebSocket interface. socket.emit is feature of Socket.IO only. They both do the same, but socket.emit is a bit more convenient in handling messages.

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

Month name as a string

The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech

private String getMonthName(Calendar calendar, boolean short) {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
    if (short) {
        flags |= DateUtils.FORMAT_ABBREV_MONTH;
    }
    return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}

Tested on API 15-25

Output for May is ??? but not ???

Deleting rows from parent and child tables

Here's a complete example of how it can be done. However you need flashback query privileges on the child table.

Here's the setup.

create table parent_tab
  (parent_id number primary key,
  val varchar2(20));

create table child_tab
    (child_id number primary key,
    parent_id number,
    child_val number,
     constraint child_par_fk foreign key (parent_id) references parent_tab);

insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');

insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);

commit;

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).

delete from child_tab where child_val = 100;

Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab

delete from parent_tab
where parent_id in
  (select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
  minus
  select parent_id from child_tab);

'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

select * from parent_tab;

It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

How do I get monitor resolution in Python?

In Windows, you can also use ctypes with GetSystemMetrics():

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

so that you don't need to install the pywin32 package; it doesn't need anything that doesn't come with Python itself.

For multi-monitor setups, you can retrieve the combined width and height of the virtual monitor:

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)

How do I get the project basepath in CodeIgniter

Change your default controller which is in config file.

i.e : config/routes.php

$route['default_controller'] = "Your controller name";

Hope this will help.

Getting cursor position in Python

win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

How do I add button on each row in datatable?

take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

Operation Not Permitted when on root - El Capitan (rootless disabled)

Correct solution is to copy or install to /usr/local/bin not /usr/bin.This is due to System Integrity Protection (SIP). SIP makes /usr/bin read-only but leaves /usr/local as read-write.

SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.

As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.

 constructor(private dataService:DataService ) {
    console.log("constructor called");
  }

I missed the below import code.

import { DataService } from '../../services/data.service';

What is the most efficient way to store tags in a database?

If space is going to be an issue, have a 3rd table Tags(Tag_Id, Title) to store the text for the tag and then change your Tags table to be (Tag_Id, Item_Id). Those two values should provide a unique composite primary key as well.

Video file formats supported in iPhone

Short answer: H.264 MPEG (MP4)

Long answer from Apple.com:

Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,

Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

http://www.apple.com/iphone/specs.html

How to add a button to UINavigationBar?

In Swift 2, you would do:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

(Not a major change) In Swift 4/5, it will be:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

Unable to load script from assets index.android.bundle on windows

This is a general error message, you may have encountered during the react native application development. So In this tutorial we are going to provide solution to this issue.

Issue Description : Unable to load script from assets index.android.bundle on windows Unable to load script from assets index.android.bundle on windows

Follow the below steps to solve above issue :

Step-1 : Create "assets" folder inside your project directory Now create assets folder inside the project directory that is "MobileApp\android\app\src\main". You can manually create assets folder :

< OR >

you can create folder by using command as well. Command : mkdir android/app/src/main/assets

Step-2 : Running your React Native application Lets run the below command to run the react native application in emulator or physical device.

Switch to project directory. cd MobileApp

Run the below command that helps to bundle you android application project.

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Run the Final step to run react native application in emulator or physical device. react-native run-android

< OR >

Also you can combine last two command in one, In this case case you have to execute command only once.

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android

< OR >

You can automate the above steps by placing them in scripts part of package.json like this:

"android-android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

React - changing an uncontrolled input

Simple solution to resolve this problem is to set an empty value by default :

<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />

What is causing this error - "Fatal error: Unable to find local grunt"

Being new to grunt and setting it up, I am running (perhaps foolishly) my grunt project/folder from a Google Drive so I can access the same code/builds from either my laptop or workstation.

There is a fair bit of synchronisation of the nodes_modules folders back to Google Drive and there seemed to be a conflict at some point, and the /nodes_modules/grunt folder was renamed to /nodes_modules/grunt (1)

Renaming it back by removing the (1) seemed to fix it for me.

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

An other way of CASE:

SELECT *  
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL     THEN 1 
               WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1 
               WHEN @myParm = value3                          THEN 1 
          END

How to show two figures using matplotlib?

I had this same problem.


Did:

f1 = plt.figure(1)

# code for figure 1

# don't write 'plt.show()' here


f2 = plt.figure(2)

# code for figure 2

plt.show()


Write 'plt.show()' only once, after the last figure. Worked for me.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

Uncaught SyntaxError: Unexpected token < On Chrome

header("Location: route_to_main_page");

I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.

Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".

Objective-C and Swift URL encoding

Here's what I use. Note you have to use the @autoreleasepool feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.

This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.

Here's the test string that I used: This is my 123+ test & test2. Got it?!

These are my Objective C++ class methods:

static NSString * urlDecode(NSString *stringToDecode) {
    NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

static NSString * urlEncode(NSString *stringToEncode) {
    @autoreleasepool {
        NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                NULL,
                (CFStringRef)stringToEncode,
                NULL,
                (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                kCFStringEncodingUTF8
            ));
        result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
        return result;
    }
}

How to split an integer into an array of digits?

return array as string

>>> list(str(12345))
['1', '2', '3', '4', '5']

return array as integer

>>> map(int,str(12345))
[1, 2, 3, 4, 5]

How can I access iframe elements with Javascript?

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

how to remove key+value from hash in javascript

You're looking for delete:

delete myhash['key2']

See the Core Javascript Guide

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

How to toggle boolean state of react component?

I found this the most simple when toggling boolean values. Simply put if the value is already true then it sets it to false and vice versa. Beware of undefined errors, make sure your property was defined before executing

this.setState({
   propertyName: this.propertyName = !this.propertyName
});

YouTube iframe embed - full screen

jut add allowfullscreen="true" to iframe

  <iframe src="URL here" allowfullscreen="true"> </iframe>

How to show full column content in a Spark Dataframe?

results.show(false) will show you the full column content.

Show method by default limit to 20, and adding a number before false will show more rows.

Transitions on the CSS display property

display is not one of the properties that transition works upon.

See Animatable CSS properties for the list of CSS properties that can have transitions applied to them. See CSS Values and Units Module Level 4, Combining Values: Interpolation, Addition, and Accumulation for how they are interpolated.

Up to CSS 3 was listed in 9.1. Properties from CSS (just close the warning popup)

I've also tried using height, but that just failed miserably.

Last time I had to do this, I used max-height instead, which is an animatable property (although it was a bit of a hack, it did work), but beware that it may be very janky for complex pages or users with low-end mobile devices.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)

keyword not supported data source

I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.

Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this

        public static string MyEntityFrameworkConnection
    {
        get
        {
             return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
        }

    }

call MyEntityFrameworkConnection whenever connection need to be established.

private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;

note: the connection in web.config file will be generated automatically when adding Entity model to the solution.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

It's mentioned as SSL_ERROR_SYSCALL, errno 10054.

To resolve this SSL issue I went to .gitconfig file (which is located in c drive in my desktop) I changed sslverify to false and added my username and email id.

sslVerify = `false` //make sslVerify as false    
[user]
    name = `***<Enter your name>**`
    email = `**<Email Id>**`

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

How to write one new line in Bitbucket markdown?

Feb 3rd 2020:

  • Atlassian Bitbucket v5.8.3 local installation.
  • I wanted to add a new line around an horizontal line. --- did produce the line, but I could not get new lines to work with suggestions above.
  • note: I did not want to use the [space][space] suggestion, since my editor removes trailing spaces on save, and I like this feature on.

I ended up doing this:

TEXT...
<br><hr><br>
TEXT...

Resulting in:

TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...

Laravel blank white screen

Sometimes it's because laravel 5.1 require PHP >= 5.5.9. Update php will solve the problem.

Embedding Windows Media Player for all browsers

December 2020 :

  • We have now Firefox 83.0 and Chrome 87.0
  • Internet Explorer is dead, it has been replaced by the new Chromium-based Edge 87.0
  • Silverlight is dead
  • Windows XP is dead
  • WMV is not a standard : https://www.w3schools.com/html/html_media.asp

To answer the question :

  • You have to convert your WMV file to another format : MP4, WebM or Ogg video.
  • Then embed it in your page with the HTML 5 <video> element.

I think this question should be closed.

Converting NSData to NSString in Objective c

Use below code.

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I had this problem, and turns out the problem was that I had used

new SimpleJdbcCall(jdbcTemplate)
    .withProcedureName("foo")

instead of

new SimpleJdbcCall(jdbcTemplate)
    .withFunctionName("foo")

Python method for reading keypress?

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

JSON forEach get Key and Value

Assuming that obj is a pre-constructed object (and not a JSON string), you can achieve this with the following:

Object.keys(obj).forEach(function(key){
   console.log(key + '=' + obj[key]);
});

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Node.js Best Practice Exception Handling

I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.

You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).

Difference between JOIN and INNER JOIN

They are functionally equivalent, but INNER JOIN can be a bit clearer to read, especially if the query has other join types (i.e. LEFT or RIGHT or CROSS) included in it.

Is Xamarin free in Visual Studio 2015?

Updated March 31st, 2016:

We have announced that Visual Studio now includes Xamarin at no extra cost, including Community Edition, which is free for individual developers, open source projects, academic research, education, and small professional teams. There is no size restriction on the Community Edition and offers the same features as the Pro & Enterprise editions. Read more about the update here: https://blog.xamarin.com/xamarin-for-all/

Be sure to browse the store on how to download and get started: https://visualstudio.microsoft.com/vs/pricing/ and there is a nice FAQ section: https://visualstudio.microsoft.com/vs/support/

How do you find out the type of an object (in Swift)?

For Swift 3.0

String(describing: <Class-Name>.self)

For Swift 2.0 - 2.3

String(<Class-Name>)

Replace spaces with dashes and make all letters lower-case

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

How to extract the substring between two markers?

Using PyParsing

import pyparsing as pp

word = pp.Word(pp.alphanums)

s = 'gfgfdAAA1234ZZZuijjk'
rule = pp.nestedExpr('AAA', 'ZZZ')
for match in rule.searchString(s):
    print(match)

which yields:

[['1234']]

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

wait until all threads finish their work in java

try this, will work.

  Thread[] threads = new Thread[10];

  List<Thread> allThreads = new ArrayList<Thread>();

  for(Thread thread : threads){

        if(null != thread){

              if(thread.isAlive()){

                    allThreads.add(thread);

              }

        }

  }

  while(!allThreads.isEmpty()){

        Iterator<Thread> ite = allThreads.iterator();

        while(ite.hasNext()){

              Thread thread = ite.next();

              if(!thread.isAlive()){

                   ite.remove();
              }

        }

   }

Run an exe from C# code

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("C:\\");
    }
}

If your application needs cmd arguments, use something like this:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}

C# Pass Lambda Expression as Method Parameter

If I understand you need following code. (passing expression lambda by parameter) The Method

public static void Method(Expression<Func<int, bool>> predicate) { 
    int[] number={1,2,3,4,5,6,7,8,9,10};
    var newList = from x in number
                  .Where(predicate.Compile()) //here compile your clausuly
                  select x;
                newList.ToList();//return a new list
    }

Calling method

Method(v => v.Equals(1));

You can do the same in their class, see this is example.

public string Name {get;set;}

public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
    {
        List<Class> c = new List<Class>();
        c.Add(new Class("name1"));
        c.Add(new Class("name2"));

        var f = from g in c.
                Where (predicate.Compile())
                select g;
        f.ToList();

       return f;
    }

Calling method

Class.GetList(c=>c.Name=="yourname");

I hope this is useful

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

How do I configure different environments in Angular.js?

Have you seen this question and its answer?

You can set a globally valid value for you app like this:

app.value('key', 'value');

and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.

Timestamp Difference In Hours for PostgreSQL

You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval) returns 183600 (which you then divide by 3600 to convert seconds to hours).

So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs:

SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)

`col-xs-*` not working in Bootstrap 4

If you want to apply an extra small class in Bootstrap 4,you need to use col-. important thing to know is that col-xs- is dropped in Bootstrap4

Return only string message from Spring MVC 3 Controller

Although, @Tomasz is absolutely right there is another way:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);

iOS: Multi-line UILabel in Auto Layout

Source: http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html

Intrinsic Content Size of Multi-Line Text

The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.

Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.

- (void)layoutSubviews
{
    [super layoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [super layoutSubviews];
}

The first call to [super layoutSubviews] is necessary for the label to get its frame set, while the second call is necessary to update the layout after the change. If we omit the second call we get a NSInternalInconsistencyException error, because we’ve made changes in the layout pass which require updating the constraints, but we didn’t trigger layout again.

We can also do this in a label subclass itself:

@implementation MyLabel
- (void)layoutSubviews
{
    self.preferredMaxLayoutWidth = self.frame.size.width;
    [super layoutSubviews];
}
@end

In this case, we don’t need to call [super layoutSubviews] first, because when layoutSubviews gets called, we already have a frame on the label itself.

To make this adjustment from the view controller level, we hook into viewDidLayoutSubviews. At this point the frames of the first Auto Layout pass are already set and we can use them to set the preferred maximum width.

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [self.view layoutIfNeeded];
}

Lastly, make sure that you don’t have an explicit height constraint on the label that has a higher priority than the label’s content compression resistance priority. Otherwise it will trump the calculated height of the content. Make sure to check all the constraints that can affect label's height.

What is getattr() exactly and how do I use it?

getattr(object, 'x') is completely equivalent to object.x.

There are only two cases where getattr can be useful.

  • you can't write object.x, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
  • you want to provide a default value. object.y will raise an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.

How to set a JavaScript breakpoint from code in Chrome?

On the "Scripts" tab, go to where your code is. At the left of the line number, click. This will set a breakpoint.

Screenshot:

screenshot of breakpoint in chrome

You will then be able to track your breakpoints within the right tab (as shown in the screenshot).

Why is vertical-align:text-top; not working in CSS

You could apply position: relative; to the div and then position: absolute; top: 0; to a paragraph or span inside of it containing the text.

What is the best way to uninstall gems from a rails3 project?

This will uninstall a gem installed by bundler:

bundle exec gem uninstall GEM_NAME

Note that this throws

ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>

but the gem is actually removed. Next time you run bundle install the gem will be reinstalled.

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

Replace Line Breaks in a String C#

Best way to replace linebreaks safely is

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.

Convert data.frame columns from factors to characters

To replace only factors:

i <- sapply(bob, is.factor)
bob[i] <- lapply(bob[i], as.character)

In package dplyr in version 0.5.0 new function mutate_if was introduced:

library(dplyr)
bob %>% mutate_if(is.factor, as.character) -> bob

...and in version 1.0.0 was replaced by across:

library(dplyr)
bob %>% mutate(across(where(is.factor), as.character)) -> bob

Package purrr from RStudio gives another alternative:

library(purrr)
bob %>% modify_if(is.factor, as.character) -> bob

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Reading from memory stream to string

string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

Number of times a particular character appears in a string

BEST

DECLARE @yourSpecialMark = '/';
select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))

It will count, how many times occours the special mark '/'

Listing information about all database files in SQL Server

I've created this query:

SELECT 
    db.name AS                                   [Database Name], 
    mf.name AS                                   [Logical Name], 
    mf.type_desc AS                              [File Type], 
    mf.physical_name AS                          [Path], 
    CAST(
        (mf.Size * 8
        ) / 1024.0 AS DECIMAL(18, 1)) AS         [Initial Size (MB)], 
    'By '+IIF(
            mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
        (mf.growth * 8
        ) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth], 
    IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
        (
                CAST(mf.max_size AS BIGINT) * 8
        ) / 1024 AS VARCHAR(30))+' MB')) AS      [MaximumSize]
FROM 
     sys.master_files AS mf
     INNER JOIN sys.databases AS db ON
            db.database_id = mf.database_id

Regex Match all characters between two strings

Sublime Text 3x

In sublime text, you simply write the two word you are interested in keeping for example in your case it is

"This is" and "sentence"

and you write .* in between

i.e. This is .* sentence

and this should do you well

How do I create an array of strings in C?

hello you can try this bellow :

 char arr[nb_of_string][max_string_length]; 
 strcpy(arr[0], "word");

a nice example of using, array of strings in c if you want it

#include <stdio.h>
#include <string.h>


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

int i, j, k;

// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];

char temp[100];
char word[100];

for (i = 0; i < 3; i++){
    printf("type word %d : ",i+1);
    scanf("%s", word);
    strcpy(array[i], word);
}

for (k=0; k<3-1; k++){
    for (i=0; i<3-1; i++)
    {
        for (j=0; j<strlen(array[i]); j++)
        {
            // if a letter ascii code is bigger we swap values
            if (array[i][j] > array[i+1][j])
            {
                strcpy(temp, array[i+1]);
                strcpy(array[i+1], array[i]);
                strcpy(array[i], temp);

                j = 999;
            }

            // if a letter ascii code is smaller we stop
            if (array[i][j] < array[i+1][j])
            {
                    j = 999;
            }

        }
    }
}

for (i=0; i<3; i++)
{
    printf("%s\n",array[i]);
}

return 0;
}

Fixed position but relative to container

The answer is yes, as long as you don't set left: 0 or right: 0 after you set the div position to fixed.

http://jsfiddle.net/T2PL5/85/

Checkout the sidebar div. It is fixed, but related to the parent, not to the window view point.

_x000D_
_x000D_
body {
  background: #ccc;
}

.wrapper {
  margin: 0 auto;
  height: 1400px;
  width: 650px;
  background: green;
}

.sidebar {
  background-color: #ddd;
  float: left;
  width: 300px;
  height: 100px;
  position: fixed;
}

.main {
  float: right;
  background-color: yellow;
  width: 300px;
  height: 1400px;
}
_x000D_
<div class="wrapper">wrapper
  <div class="sidebar">sidebar</div>
  <div class="main">main</div>
</div>
_x000D_
_x000D_
_x000D_

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

AGE is defined as "42" so the line:

str += "Do you feel " + AGE + " years old?";

is converted to:

str += "Do you feel " + "42" + " years old?";

Which isn't valid since "Do you feel " and "42" are both const char[]. To solve this, you can make one a std::string, or just remove the +:

// 1.
str += std::string("Do you feel ") + AGE + " years old?";

// 2.
str += "Do you feel " AGE " years old?";

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

What's a "static method" in C#?

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the membe

How to create a laravel hashed password

Laravel 5 uses bcrypt. So, you can do this as well.

$hashedpassword = bcrypt('plaintextpassword');

output of which you can save to your database table's password field.

Fn Ref: bcrypt

Changing the current working directory in Java?

If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I know this is an old question, but browsers have been changing over time. Although some of the answers to this question mentioned here like: creating a temporary text box above the password field and hiding it may have worked in the past, currently the easiest way to prevent the browser from popping up the password manager is to have at least three separate additional hidden password inputs, each with different dummy values, like so:

<form method="post" autocomplete="off" action="">
    <ul class="field-set">
    <li>
        <label>Username:</label>
        <input type="text" name="acct" id="username" maxlength="100" size="20">
    </li>
    <li>
        <label>Password:</label>
        <input type="password" name="pswd" id="password" maxlength="16" size="20" >
        <input type="password" style="display: none;" value="dummyinput1"/>
        <input type="password" style="display: none;" value="dummyinput2"/>
        <input type="password" style="display: none;" value="dummyinput3"/>
    </li>
    <li>
        <input type="submit" class="button" value="Login" id="Login" name="Login">
    </li>
    </ul>
</form>

Convert txt to csv python script

I suposse this is the output you need:

title,intro,tagline

2.9,Gardena,CA

It can be done with this changes to your code:

import csv
import itertools

with open('log.txt', 'r') as in_file:
    lines = in_file.read().splitlines()
    stripped = [line.replace(","," ").split() for line in lines]
    grouped = itertools.izip(*[stripped]*1)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        for group in grouped:
            writer.writerows(group)

Scheduling recurring task in Android

Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:

A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.

So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.

Angular Material: mat-select not selecting default

My solution is little tricky and simpler.

<div>
    <mat-select
        [placeholder]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

I just made use of the placeholder. The default color of material placeholder is light gray. To make it look like the option is selected, I just manipulated the CSS as follows:

::ng-deep .mat-select-placeholder {
    color: black;
}

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

MySQL date formats - difficulty Inserting a date

The date format for mysql insert query is YYYY-MM-DD

example:

INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');

How to convert a string to integer in C?

Robust C89 strtol-based solution

With:

  • no undefined behavior (as could be had with the atoi family)
  • a stricter definition of integer than strtol (e.g. no leading whitespace nor trailing trash chars)
  • classification of the error case (e.g. to give useful error messages to users)
  • a "testsuite"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

/* Convert string s to int out.
 *
 * @param[out] out The converted int. Cannot be NULL.
 *
 * @param[in] s Input string to be converted.
 *
 *     The format is the same as strtol,
 *     except that the following are inconvertible:
 *
 *     - empty string
 *     - leading whitespace
 *     - any trailing characters that are not part of the number
 *
 *     Cannot be NULL.
 *
 * @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
 *
 * @return Indicates if the operation succeeded, or why it failed.
 */
str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace(s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}

int main(void) {
    int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);

    /* Different base. */
    assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
    assert(i == 17);

    /* 0 */
    assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
    assert(i == 0);

    /* INT_MAX. */
    sprintf(s, "%d", INT_MAX);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MAX);

    /* INT_MIN. */
    sprintf(s, "%d", INT_MIN);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MIN);

    /* Leading and trailing space. */
    assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);

    /* Trash characters. */
    assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);

    /* int overflow.
     *
     * `if` needed to avoid undefined behaviour
     * on `INT_MAX + 1` if INT_MAX == LONG_MAX.
     */
    if (INT_MAX < LONG_MAX) {
        sprintf(s, "%ld", (long int)INT_MAX + 1L);
        assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
    }

    /* int underflow */
    if (LONG_MIN < INT_MIN) {
        sprintf(s, "%ld", (long int)INT_MIN - 1L);
        assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
    }

    /* long overflow */
    sprintf(s, "%ld0", LONG_MAX);
    assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);

    /* long underflow */
    sprintf(s, "%ld0", LONG_MIN);
    assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);

    return EXIT_SUCCESS;
}

GitHub upstream.

Based on: https://stackoverflow.com/a/6154614/895245

Convert a Unicode string to a string in Python (containing extra symbols)

See unicodedata.normalize

title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'

Handling exceptions from Java ExecutorService tasks

If you want to monitor the execution of task, you could spin 1 or 2 threads (maybe more depending on the load) and use them to take tasks from an ExecutionCompletionService wrapper.

How the single threaded non blocking IO model works in Node.js

if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."

about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.

in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.

Read XLSX file in Java

This one maybe work for you, it can read/write Excel 2007 xlsx file. SmartXLS

What is the difference between Promises and Observables?

Promise vs Observable similarity first

  1. Both used to handle async code.
  2. Please look for promise example. Promise constructor passes a resolve reference function which will get called when it gets called with some value upon completion of some async task.

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("Hello from a Promise!");
  }, 2000);
});

promise.then(value => console.log(value));

  1. Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.

  2. So both handles async tasks. Now let's see the difference.


const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

observable.subscribe(value => console.log(value));

Promise vs Observable difference

Promise

  1. It resolves or reject a single value and can handle a single value async task at a time.
  2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
  3. Not cancellable
  4. No rxjs support for operators.

Observable

  1. ability to emit multiple asynchronous values.
  2. Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
  3. Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
  4. Can be cancelled using unsubscribe method anytime.
  5. One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combineLatest etc. to transform observable data before subscribing.

enter image description here


Function to calculate distance between two coordinates

I try to make the code a little bit understandable by naming the variables, I hope this can help

function getDistanceFromLatLonInKm(point1, point2) {

  const [lat1, lon1] = point1;
  const [lat2, lon2] = point2;
  const earthRadius = 6371;
  const dLat = convertDegToRad(lat2 - lat1);
  const dLon = convertDegToRad(lon2 - lon1);
  const squarehalfChordLength =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);

  const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
  const distance = earthRadius * angularDistance;
  return distance;

}

Number format in excel: Showing % value without multiplying with 100

You just have to change to a Custom format - right click and select format and at the bottom of the list is custom.

 0.00##\%;[Red](0.00##\%)

The first part of custom format is your defined format you posted. Everything after the semicolon is for negative numbers. [RED] tells Excel to make the negative numbers red and the () make sure that negative number is in parentheses.

Regex for not empty and not whitespace

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

How do I change the font size of a UILabel in Swift?

label.font = UIFont.systemFontOfSize(20)

Redis - Connect to Remote Server

  • if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with the above suggestions, make sure your start redis with the config like so: ./src/redis-server redis.conf

    • also side note i am including a screenshot of virtual box setting to connect to redis, if you are on windows and connecting to a virtualbox vm.

enter image description here

How to define an enum with string value?

It works for me..

   public class ShapeTypes
    {
        private ShapeTypes() { }
        public static string OVAL
        {
            get
            {
                return "ov";
            }
            private set { }
        }

        public static string SQUARE
        {
            get
            {
                return "sq";
            }
            private set { }
        }

        public static string RECTANGLE
        {
            get
            {
                return "rec";
            }
            private set { }
        }
    }

Java parsing XML document gives "Content not allowed in prolog." error

I think this is also a solution of this problem.

Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'

I got resolved my problem by doing same changes.

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

IOError: [Errno 32] Broken pipe: Python

The top answer (if e.errno == errno.EPIPE:) here didn't really work for me. I got:

AttributeError: 'BrokenPipeError' object has no attribute 'EPIPE'

However, this ought to work if all you care about is ignoring broken pipes on specific writes. I think it's safer than trapping SIGPIPE:

try:
    # writing, flushing, whatever goes here
except BrokenPipeError:
    exit( 0 )

You obviously have to make a decision as to whether your code is really, truly done if you hit the broken pipe, but for most purposes I think that's usually going to be true. (Don't forget to close file handles, etc.)

How to bind inverse boolean properties in WPF?

I wanted my XAML to remain as elegant as possible so I created a class to wrap the bool which resides in one of my shared libraries, the implicit operators allow the class to be used as a bool in code-behind seamlessly

public class InvertableBool
{
    private bool value = false;

    public bool Value { get { return value; } }
    public bool Invert { get { return !value; } }

    public InvertableBool(bool b)
    {
        value = b;
    }

    public static implicit operator InvertableBool(bool b)
    {
        return new InvertableBool(b);
    }

    public static implicit operator bool(InvertableBool b)
    {
        return b.value;
    }

}

The only changes needed to your project are to make the property you want to invert return this instead of bool

    public InvertableBool IsActive 
    { 
        get 
        { 
            return true; 
        } 
    }

And in the XAML postfix the binding with either Value or Invert

IsEnabled="{Binding IsActive.Value}"

IsEnabled="{Binding IsActive.Invert}"

Setting up redirect in web.config file

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   class Program
{
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
            return 1;
        }

        if (args.Length == 3)
        {
            if (args[0].ToLower() == "-insert-redirect")
            {
                var path = args[1];
                var value = args[2];

                if (InsertRedirect(path, value))
                    Console.WriteLine("Redirect added.");
                return 0;
            }
        }

        Console.WriteLine("Wrong parameters.");
        return 1;

    }

    static bool InsertRedirect(string path, string value)
    {
        try
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            // This should find the appSettings node (should be only one):
            XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");

            var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
            if (existNode != null)
                return false;

            // Create new <add> node
            XmlNode nodeNewKey = doc.CreateElement("httpRedirect");

            XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
            XmlAttribute attributeDestination = doc.CreateAttribute("destination");
            //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");

            // Assign values to both - the key and the value attributes:

            attributeEnable.Value = "true";
            attributeDestination.Value = value;
            //attributeResponseStatus.Value = "Permanent";

            // Add both attributes to the newly created node:
            nodeNewKey.Attributes.Append(attributeEnable);
            nodeNewKey.Attributes.Append(attributeDestination);
            //nodeNewKey.Attributes.Append(attributeResponseStatus);

            // Add the node under the 
            nodeAppSettings.AppendChild(nodeNewKey);
            doc.Save(path);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception adding redirect: {e.Message}");
            return false;
        }
    }
}

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

This is a known issue. The problem is that a div tag has the style "overflow: auto" which apparently is not implemented well with WebKit which is used by Safari and Chrome (see Emanuele Greco's answer). I did not know how to take advantage of Emanuele's suggestion to use the RS:ReportViewerHost element, but I solved it using JavaScript.

Problem

enter image description here

Solution

Since "overflow: auto" is specified in the style attribute of the div element with id "ctl31_ctl10", we can't override it in a stylesheet file so I resorted to JavaScript. I appended the following code to "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js"

function FixSafari()
{    
    var element = document.getElementById("ctl31_ctl10");
    if (element) 
    {
        element.style.overflow = "visible";  //default overflow value
    }
}

// Code from http://stackoverflow.com/questions/9434/how-do-i-add-an-additional-window-onload-event-in-javascript
if (window.addEventListener) // W3C standard
{
    window.addEventListener('load', FixSafari, false); // NB **not** 'onload'
} 
else if (window.attachEvent) // Microsoft
{
    window.attachEvent('onload', FixSafari);
}

Note

There appears to be a solution for SSRS 2005 that I have not tried but I don't think it is applicable to SSRS 2008 because I can't find the "DocMapAndReportFrame" class.

Regular expression field validation in jQuery

I'm using jQuery and JavaScript and it works fine for me:

var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Difference between Method and Function?

In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

How to install Visual Studio 2015 on a different drive

Run installer in command line (Admin) with argument:

vs_community_ENU.exe /uninstall /force

Then:

vs_community_ENU /CustomInstallPath E:\VisualStudio2015

Cleanest way to write retry logic?

I would add the following code to the accepted answer

public static class Retry<TException> where TException : Exception //ability to pass the exception type
    {
        //same code as the accepted answer ....

        public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
        {
            var exceptions = new List<Exception>();

            for (int retry = 0; retry < retryCount; retry++)
            {
                try
                {
                    return action();
                }
                catch (TException ex) //Usage of the exception type
                {
                    exceptions.Add(ex);
                    Thread.Sleep(retryInterval);
                }
            }

            throw new AggregateException(String.Format("Failed to excecute after {0} attempt(s)", retryCount), exceptions);
        }
    }

Basically the above code is making the Retry class generic so you can pass the type of the exception you want to catch for retry.

Now use it almost in the same way but specifying the exception type

Retry<EndpointNotFoundException>.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

Unique on a dataframe with only selected columns

Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:

dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]

Checking for a null object in C++

You can use a special designated object as the null object in case of references as follows:

class SomeClass
{
    public:

        int operator==(SomeClass &object)
        {
            if(this == &object) 
            {
                    return true;
            }

            return false;
        }


    static SomeClass NullObject;
};

SomeClass SomeClass::NullObject;

void print(SomeClass &val)
{
    if(val == SomeClass::NullObject)
    {
        printf("\nNULL");
    }
    else
    {
        printf("\nNOT NULL");
    }
}

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

How do I use a Boolean in Python?

Unlike Java where you would declare boolean flag = True, in Python you can just declare myFlag = True

Python would interpret this as a boolean variable

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

How to get value of a div using javascript

First of all

<div id="demo" align="center"  value="1"></div>

that is not valid HTML. Read up on custom data attributes or use the following instead:

<div id="demo" align="center" data-value="1"></div>

Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.

var cookieValue = document.getElementById("demo").getAttribute("data-value"); 

RegEx for valid international mobile phone number

^\+[1-9]{1}[0-9]{7,11}$ 

The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$ fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.

The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.

Get difference between 2 dates in JavaScript?

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

[nodemon] Internal watch failed: watch /home/Document/nmmExpressServer/bin ENOSPC
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nodemon ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.

This is the error I got when running nodemon ./bin/www.

The solution was closing an Atom window that had a entire directory of folders open in the project window.

I don't know why, but I'm assuming Atom and nodemon use similar processes to watch files/folders.

How to compile and run C in sublime text 3?

Instruction is base on the "icemelon" post. Link to the post:

how-do-i-compile-and-run-a-c-program-in-sublime-text-2

Use the link below to find out how to setup enviroment variable on your OS:

c_environment_setup

The instruction below was tested on the Windows 8.1 system and Sublime Text 3 - build 3065.

1) Install MinGW. 2) Add path to the "MinGW\bin" in the "PATH environment variable".

"System Properties -> Advanced -> Environment" variables and there update "PATH' variable.

3) Then check your PATH environment variable by the command below in the "Command Prompt":

echo %path%

4) Add new Build System to the Sublime Text.

My version of the code below ("C.sublime-build").

link to the code:

C.sublime-build

// Put this file here:
// "C:\Users\[User Name]\AppData\Roaming\Sublime Text 3\Packages\User"
// Use "Ctrl+B" to Build and "Crtl+Shift+B" to Run the project.
// OR use "Tools -> Build System -> New Build System..." and put the code there.

{
    "cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],

    // Doesn't work, sublime text 3, Windows 8.1    
    // "cmd" : ["gcc $file_name -o ${file_base_name}"],

    "selector" : "source.c",
    "shell": true,
    "working_dir" : "$file_path",

    // You could add path to your gcc compiler this and don't add path to your "PATH environment variable"
    // "path" : "C:\\MinGW\\bin"

    "variants" : [

        { "name": "Run",
          "cmd" : ["${file_base_name}.exe"]
        }
    ]
}

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Sum of values in an array using jQuery

If you want it to be a jquery method, you can do it like this :

$.sum = function(arr) {
    var r = 0;
    $.each(arr, function(i, v) {
        r += +v;
    });
    return r;
}

and call it like this :

var sum = $.sum(["20", "40", "80", "400"]);

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.

UPDATE

In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

How can I embed a YouTube video on GitHub wiki pages?

If you like HTML tags more than markdown + center alignment:

_x000D_
_x000D_
<div align="center">_x000D_
  <a href="https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE"><img src="https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="IMAGE ALT TEXT"></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert byte array to string

To convert the byte[] to string[], simply use the below line.

byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
                 fileData, 
                 0, 
                 fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
                                             StringSplitOptions.None);

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

$scope.popoverPostion = function(event){
    $scope.pos = '';

       if(event.x <= 207 && event.x >= 140){
           $scope.pos = 'top';
           event.x = '';
       }
       else if(event.x < 140){
           $scope.pos = 'top-left';
           event.x = '';
       }
       else if(event.x > 207){
           $scope.pos = 'top-right';
           event.x = '';
       }

};

Ternary operation in CoffeeScript

a = if true then 5 else 10
a = if false then 5 else 10 

See documentation.

test if event handler is bound to an element in jQuery

Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.

I therefore use die() or unbind() like this:

$("#someid").die("click").live("click",function(){...

or

$("#someid").unbind("click").bind("click",function(){...

or in recent jQuery versions:

$("#someid").off("click").on("click",function(){...

Get Value From Select Option in Angular 4

    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`

How to use z-index in svg elements?

Using D3:

If you want to add the element in the reverse order to the data use:

.insert('g', ":first-child")

Instead of .append

Adding an element to top of a group element

Javascript logical "!==" operator?

It's != without type coercion. See the MDN documentation for comparison operators.

Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with == and !=. (null == undefined, false == "0", etc.)

Short answer: always use === and !== unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)

How to check if a process is running via a batch script

Here's how I've worked it out:

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log

The above will open Notepad if it is not already running.

Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.

Where does one get the "sys/socket.h" header/source file?

Given that Windows has no sys/socket.h, you might consider just doing something like this:

#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif

I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a

#ifdef __WIN32__
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   WSAStartup(versionWanted, &wsaData);
#endif

at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.

fopen deprecated warning

If you code is intended for a different OS (like Mac OS X, Linux) you may use following:

#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif