Programs & Examples On #Embedded language

Anything related to languages (designed to be) embedded in other applications and their implementations. DO NOT use this tag to mark questions related to embedded devices, unless it also relates to embedding a language in a bigger application.

How to use a PHP class from another file?

Use include("class.classname.php");

And class should use <?php //code ?> not <? //code ?>

IE and Edge fix for object-fit: cover;

I achieved satisfying results with:

min-height: 100%;
min-width: 100%;

this way you always maintain the aspect ratio.

The complete css for an image that will replace "object-fit: cover;":

width: auto;
height: auto;
min-width: 100%;
min-height: 100%;
position: absolute;
right: 50%;
transform: translate(50%, 0);

Changing navigation title programmatically

Swift 5.1

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "What ever you want"
}

How to call one shell script from another shell script?

If you have another file in same directory, you can either do:

bash another_script.sh

or

source another_script.sh

or

. another_script.sh

When you use bash instead of source, the script cannot alter environment of the parent script. The . command is POSIX standard while source command is a more readable bash synonym for . (I prefer source over .). If your script resides elsewhere just provide path to that script. Both relative as well as full path should work.

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

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

You simply need to upgrade your Tomcat version, to Tomcat 8.0.xx. Java8 <-> Tomcat8

This is the configuration that I have been using and it has always worked out well JDK version Tomcat versions

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

Best way to get user GPS location in background in Android

I have try to my code and got success try this

package com.mobeyosoft.latitudelongitude;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by 5943 6417 on 14-09-2016.
 */
public class LocationService extends Service
{
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 1;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Context context;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
        context=this;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }



    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }



    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }




    public class MyLocationListener implements LocationListener{

        public void onLocationChanged(final Location loc)
        {
            Log.i("**********", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());
                intent.putExtra("Provider", loc.getProvider());
                sendBroadcast(intent);

            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


        public void onStatusChanged(String provider, int status, Bundle extras)
        {

        }

    }
}

How to confirm RedHat Enterprise Linux version?

That's the RHEL release version.

You can see the kernel version by typing uname -r. It'll be 2.6.something.

How to append one DataTable to another DataTable

use loop

  for (int i = 0; i < dt1.Rows.Count; i++)
        {      
           dt2.Rows.Add(dt1.Rows[i][0], dt1.Rows[i][1], ...);//you have to insert all Columns...
        }

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

How to get english language word database?

I do not see http://wordlist.sourceforge.net/ mentioned here, but that is where I would start if I were looking for something like this (and I was, when I stumbled over this question).

If you cannot find what you want there, and what you want is a list of english words, then you should probably spend some extra time describing how to recognize what it is that you want.

How to change language of app when user selects language?

Good solutions explained pretty well here. But Here is one more.

Create your own CustomContextWrapper class extending ContextWrapper and use it to change Locale setting for the complete application. Here is a GIST with usage.

And then call the CustomContextWrapper with saved locale identifier e.g. 'hi' for Hindi language in activity lifecycle method attachBaseContext. Usage here:

@Override
protected void attachBaseContext(Context newBase) {
    // fetch from shared preference also save the same when applying. Default here is en = English
    String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
    super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}

Common Header / Footer with static HTML

There are three ways to do what you want

Server Script

This includes something like php, asp, jsp.... But you said no to that

Server Side Includes

Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.

Client Side Include

This solutions has you calling back to the server after page has already been loaded on the client.

Overriding a JavaScript function while referencing the original

I've created a small helper for a similar scenario because I often needed to override functions from several libraries. This helper accepts a "namespace" (the function container), the function name, and the overriding function. It will replace the original function in the referred namespace with the new one.

The new function accepts the original function as the first argument, and the original functions arguments as the rest. It will preserve the context everytime. It supports void and non-void functions as well.

function overrideFunction(namespace, baseFuncName, func) {
    var originalFn = namespace[baseFuncName];
    namespace[baseFuncName] = function () {
        return func.apply(this, [originalFn.bind(this)].concat(Array.prototype.slice.call(arguments, 0)));
    };
}

Usage for example with Bootstrap:

overrideFunction($.fn.popover.Constructor.prototype, 'leave', function(baseFn, obj) {
    // ... do stuff before base call
    baseFn(obj);
    // ... do stuff after base call
});

I didn't create any performance tests though. It can possibly add some unwanted overhead which can or cannot be a big deal, depending on scenarios.

Resolving a Git conflict with binary files

To resolve by keeping the version in your current branch (ignore the version from the branch you are merging in), just add and commit the file:

git commit -a

To resolve by overwriting the version in your current branch with the version from the branch you are merging in, you need to retrieve that version into your working directory first, and then add/commit it:

git checkout otherbranch theconflictedfile
git commit -a

Explained in more detail

Is there a better alternative than this to 'switch on type'?

Yes, thanks to C# 7 that can be achieved. Here's how it's done (using expression pattern):

switch (o)
{
    case A a:
        a.Hop();
        break;
    case B b:
        b.Skip();
        break;
    case C _: 
        return new ArgumentException("Type C will be supported in the next version");
    default:
        return new ArgumentException("Unexpected type: " + o.GetType());
}

Can't start Eclipse - Java was started but returned exit code=13

You have to go to the folder where eclipse is installed and then you have to change the eclipse.ini file.

You have to add

-vm

C:\Program Files\Java\jdk1.8.0_202\bin\javaw.exe

Your eclipse.ini file will look like the below screenshot

enter image description here

Get exit code for command in bash/ksh

Try

safeRunCommand() {
   "$@"

   if [ $? != 0 ]; then
      printf "Error when executing command: '$1'"
      exit $ERROR_CODE
   fi
}

Where is the .NET Framework 4.5 directory?

.NET 4.5 is an in place replacement for 4.0 - you will find the assemblies in the 4.0 directory.

See the blogs by Rick Strahl and Scott Hanselman on this topic.

You can also find the specific versions in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

java howto ArrayList push, pop, shift, and unshift

Great Answer by Jon.

I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

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

public class Main {

    public static void main(String[] args) {

        List<String> animals = new ArrayList<>();

        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add() -> push(): Add items to the end of an array
        animals.add("Elephant");
        System.out.println(animals);  // [Lion, Tiger, Cat, Dog, Elephant]

        // remove() -> pop(): Remove an item from the end of an array
        animals.remove(animals.size() - 1);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add(0,"xyz") -> unshift(): Add items to the beginning of an array
        animals.add(0, "Penguin");
        System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]

        // remove(0) -> shift(): Remove an item from the beginning of an array
        animals.remove(0);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

    }

}

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

How to disable clicking inside div

How to disable clicking another div click until first one popup div close

Image of the example

 <p class="btn1">One</p>
 <div id="box1" class="popup">
 Test Popup Box One
 <span class="close">X</span>
 </div>

 <!-- Two -->
 <p class="btn2">Two</p>
 <div id="box2" class="popup">
 Test Popup Box Two
 <span class="close">X</span>
  </div>

<style>
.disabledbutton {
 pointer-events: none;
 }

.close {
cursor: pointer;
}

</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
  $("#box1").css('display','block');
  $(".btn2,.btn3").addClass("disabledbutton");

});
$(".close").click(function(){
  $("#box1").css('display','none');
  $(".btn2,.btn3").removeClass("disabledbutton");
});
</script>

How to set the value for Radio Buttons When edit?

This is easier to read for me:

<input type="radio" name="rWF" id="rWF" value=1  <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>

How to show full height background image?

This worked for me (though it's for reactjs & tachyons used as inline CSS)

<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}> 
........
</div>

This takes in css as height: 100vh

Indentation Error in Python

You are mixing tabs and spaces.

Find the exact location with:

python -tt yourscript.py

and replace all tabs with spaces. You really want to configure your text editor to only insert spaces for tabs as well.

How can I directly view blobs in MySQL Workbench

Perform three steps:

  1. Go to "WorkBench Preferences" --> Choose "SQL Editor" Under "Query Results": check "Treat BINARY/VARBINARY as nonbinary character string"

  2. Restart MySQL WorkBench.

  3. Now select SELECT SUBSTRING(BLOB<COLUMN_NAME>,1,2500) FROM <Table_name>;

How to find out what character key is pressed?

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

How to remove button shadow (android)

Kotlin

stateListAnimator = null

Java

setStateListAnimator(null);

XML

android:stateListAnimator="@null"

How do I configure HikariCP in my Spring Boot app in my application.properties files?

I came across HikariCP and I was amazed by the benchmarks and I wanted to try it instead of my default choice C3P0 and to my surprise I struggled to get the configurations right probably because the configurations differ based on what combination of tech stack you are using.

I have setup Spring Boot project with JPA, Web, Security starters (Using Spring Initializer) to use PostgreSQL as a database with HikariCP as connection pooling.
I have used Gradle as build tool and I would like to share what worked for me for the following assumptions:

  1. Spring Boot Starter JPA (Web & Security - optional)
  2. Gradle build too
  3. PostgreSQL running and setup with a database (i.e. schema, user, db)

You need the following build.gradle if you are using Gradle or equivalent pom.xml if you are using maven

buildscript {
    ext {
        springBootVersion = '1.5.8.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'com'
version = '1.0'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')

    // Exclude the tomcat-jdbc since it's used as default for connection pooling
    // This can also be achieved by setting the spring.datasource.type to HikariCP 
    // datasource see application.properties below
    compile('org.springframework.boot:spring-boot-starter-data-jpa') {
        exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
    }
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.security:spring-security-test')

    // Download HikariCP but, exclude hibernate-core to avoid version conflicts
    compile('com.zaxxer:HikariCP:2.5.1') {
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }

    // Need this in order to get the HikariCPConnectionProvider
    compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
        exclude group: 'com.zaxxer', module: 'HikariCP'
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }
}

There are a bunch of excludes in the above build.gradle and that's because

  1. First exclude, instructs gradle that exclude the jdbc-tomcat connection pool when downloading the spring-boot-starter-data-jpa dependencies. This can be achieved by setting up the spring.datasource.type=com.zaxxer.hikari.HikariDataSource also but, I don't want an extra dependency if I don't need it
  2. Second exclude, instructs gradle to exclude hibernate-core when downloading com.zaxxer dependency and that's because hibernate-core is already downloaded by Spring Boot and we don't want to end up with different versions.
  3. Third exclude, instructs gradle to exclude hibernate-core when downloading hibernate-hikaricp module which is needed in order to make HikariCP use org.hibernate.hikaricp.internal.HikariCPConnectionProvider as connection provider instead of deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider

Once I figured out the build.gradle and what to keep and what to not, I was ready to copy/paste a datasource configuration into my application.properties and expected everything to work with flying colors but, not really and I stumbled upon the following issues

  • Spring boot failing to find out database details (i.e. url, driver) hence, not able to setup jpa and hibernate (because I didn't name the property key values right)
  • HikariCP falling back to com.zaxxer.hikari.hibernate.HikariConnectionProvider
  • After instructing Spring to use new connection-provider for when auto-configuring hibernate/jpa then HikariCP failed because it was looking for some key/value in the application.properties and was complaining about dataSource, dataSourceClassName, jdbcUrl. I had to debug into HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider and found out that HikariCP could not find the properties from application.properties because it was named differently.

Anyway, this is where I had to rely on trial and error and make sure that HikariCP is able to pick the properties (i.e. data source that's db details, as well as pooling properties) as well as Sping Boot behave as expected and I ended up with the following application.properties file.

server.contextPath=/
debug=true

# Spring data source needed for Spring boot to behave
# Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included 
# in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/somedb
spring.datasource.username=dbuser
spring.datasource.password=dbpassword

# Hikari will use the above plus the following to setup connection pooling
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000

# Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
# Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
# So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up 
# with different versions of hibernate-core 
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider

# JPA specific configs
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.default_schema=dbschema
spring.jpa.properties.hibernate.search.autoregister_listeners=false
spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=false

# Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 

As shown above the configurations are divided into categories based on following naming patterns

  • spring.datasource.x (Spring auto-configure will pick these, so will HikariCP)
  • spring.datasource.hikari.x (HikariCP picks these to setup the pool, make a note of the camelCase field names)
  • spring.jpa.hibernate.connection.provider_class (Instructs Spring to use new HibernateConnectionProvider)
  • spring.jpa.properties.hibernate.x (Used by Spring to auto-configure JPA, make a note of the field names with underscores)

It's hard to come across a tutorial or post or some resource that shows how the above properties file is used and how the properties should be named. Well, there you have it.

Throwing the above application.properties with build.gradle (or at least similar) into a Spring Boot JPA project version (1.5.8) should work like a charm and connect to your pre-configured database (i.e. in my case it's PostgreSQL that both HikariCP & Spring figure out from the spring.datasource.url on which database driver to use).

I did not see the need to create a DataSource bean and that's because Spring Boot is capable of doing everything for me just by looking into application.properties and that's neat.

The article in HikariCP's github wiki shows how to setup Spring Boot with JPA but, lacks explanation and details.

The above two file is also availble as a public gist https://gist.github.com/rhamedy/b3cb936061cc03acdfe21358b86a5bc6

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf

change

AddHandler application/x-httpd-php .js .xml .htc .css

to:

AddHandler application/x-httpd-php .js .xml .htc

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

Press TAB and then ENTER key in Selenium WebDriver

Be sure to include the Key in the imports...

const {Builder, By, logging, until, Key} = require('selenium-webdriver');

searchInput.sendKeys(Key.ENTER) worked great for me

In Python, how do I create a string of n characters in one line of code?

This might be a little off the question, but for those interested in the randomness of the generated string, my answer would be:

import os
import string

def _pwd_gen(size=16):
    chars = string.letters
    chars_len = len(chars)
    return str().join(chars[int(ord(c) / 256. * chars_len)] for c in os.urandom(size))

See these answers and random.py's source for more insight.

Display date/time in user's locale format and time offset

_x000D_
_x000D_
// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])_x000D_
var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server_x000D_
var serverDateStr = serverDate.toLocaleString("en-US", {_x000D_
  year: 'numeric',_x000D_
  month: 'numeric',_x000D_
  day: 'numeric',_x000D_
  hour: 'numeric',_x000D_
  minute: 'numeric',_x000D_
  second: 'numeric'_x000D_
})_x000D_
var userDate = new Date(serverDateStr + " UTC");_x000D_
var locale = window.navigator.userLanguage || window.navigator.language;_x000D_
_x000D_
var clientDateStr = userDate.toLocaleString(locale, {_x000D_
  year: 'numeric',_x000D_
  month: 'numeric',_x000D_
  day: 'numeric'_x000D_
});_x000D_
_x000D_
var clientDateTimeStr = userDate.toLocaleString(locale, {_x000D_
  year: 'numeric',_x000D_
  month: 'numeric',_x000D_
  day: 'numeric',_x000D_
  hour: 'numeric',_x000D_
  minute: 'numeric',_x000D_
  second: 'numeric'_x000D_
});_x000D_
_x000D_
console.log("Server UTC date: " + serverDateStr);_x000D_
console.log("User's local date: " + clientDateStr);_x000D_
console.log("User's local date&time: " + clientDateTimeStr);
_x000D_
_x000D_
_x000D_

Error: Uncaught SyntaxError: Unexpected token <

This is a browser issue rather than a javascript or JQuery issue; it's attempting to interpret the angle bracket as an HTML tag.

Try doing this when setting up your javascripts:

<script>
//<![CDATA[

    // insert teh codez

//]]>
</script>

Alternatively, move your javascript to a separate file.

Edit: Ahh.. with that link I've tracked it down. What I said was the issue wasn't the issue at all. this is the issue, stripped from the website:

<script type="text/javascript"
    $(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

Can you spot the error? It's in the first line: the <script tag isn't closed. It should be <script type="text/javascript">

My previous suggestion still stands, however: you should enclose intra-tagged scripts in a CDATA block, or move them to a separately linked file.

That wasn't the issue here, but it would have shown the real issue faster.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I resolved the issue via this command

pg_ctl -D /usr/local/var/postgres start

At times, you might get this error

pg_ctl: another server might be running; trying to start server anyway

So, try running the following command and then run the first command given above.

pg_ctl -D /usr/local/var/postgres stop

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

How to implement a Keyword Search in MySQL?

Ideally, have a keyword table containing the fields:

Keyword
Id
Count (possibly)

with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.

You'll also need a table of words to not count as keywords (if, and, so, but, ...).

In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".

"LIKE" queries will work but they won't scale as well.

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

How to get current class name including package name in Java?

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

Babel command not found

There are two problems here. First, you need a package.json file. Telling npm to install without one will throw the npm WARN enoent ENOENT: no such file or directory error. In your project directory, run npm init to generate a package.json file for the project.

Second, local binaries probably aren't found because the local ./node_modules/.bin is not in $PATH. There are some solutions in How to use package installed locally in node_modules?, but it might be easier to just wrap your babel-cli commands in npm scripts. This works because npm run adds the output of npm bin (node_modules/.bin) to the PATH provided to scripts.

Here's a stripped-down example package.json which returns the locally installed babel-cli version:

{
  "scripts": {
    "babel-version": "babel --version"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5"
  }
}

Call the script with this command: npm run babel-version.

Putting scripts in package.json is quite useful but often overlooked. Much more in the docs: How npm handles the "scripts" field

Get current language in CultureInfo

I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;} but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:

CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;

This will give you the culture your UI is (texts on windows, message boxes, etc).

'Use of Unresolved Identifier' in Swift

Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.

Keyboard shortcut to comment lines in Sublime Text 2

I'd like to add, that on my mac by default block comment toggle shortcut is cmd+alt+/

Get position/offset of element relative to a parent container?

Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):

<script type="text/javascript">
    function fGetCSSProperty(s, e) {
        try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
        catch (x) { return null; } 
    }
    function fGetOffSetParent(s) {
        var a = s.offsetParent || document.body;

        while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
            a = a.offsetParent;
        return a;
    }
    function GetPosition(s) {
        var b = fGetOffSetParent(s);

        return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
    }    
</script>

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I'm all about ROOT for these needs. Pretty heavy if you don't need all the analysis support, though.

Break a previous commit into multiple commits

Easiest thing to do without an interactive rebase is (probably) to make a new branch starting at the commit before the one you want to split, cherry-pick -n the commit, reset, stash, commit the file move, reapply the stash and commit the changes, and then either merge with the former branch or cherry-pick the commits that followed. (Then switch the former branch name to the current head.) (It's probably better to follow MBOs advice and do an interactive rebase.)

Send string to stdin

aliases can and can't process piped stdin...

Here we create 3 lines of output

$ echo -e "line 1\nline 2\nline 3"
line 1
line 2
line 3

We then pipe the output to stdin of the sed command to put them all on one line

$ echo -e "line 1\nline 2\nline 3" |  sed -e ":a;N;\$!ba ;s?\n? ?g"
line 1 line 2 line 3

If we define an alias of the same sed command

$ alias oline='sed -e ":a;N;\$!ba ;s?\n? ?g"'

We can pipe the output to the stdin of the alias and it behaves exactly the same

$ echo -e "line 1\nline 2\nline 3" |  oline
line 1 line 2 line 3

The problem arises when we try to define the alias as a function

$ alias oline='function _oline(){ sed -e ":a;N;\$!ba ;s?\n? ?g";}_oline'

Defining the alias as a funstion breaks the pipe

$ echo -e "line 1\nline 2\nline 3" |  oline
>

Update rows in one table with data from another table based on one column in each being equal

If you want to update matching rows in t1 with data from t2 then:

update t1
set (c1, c2, c3) = 
(select c1, c2, c3 from t2
 where t2.user_id = t1.user_id)
where exists
(select * from t2
 where t2.user_id = t1.user_id)

The "where exists" part it to prevent updating the t1 columns to null where no match exists.

run a python script in terminal without the python command

You use a shebang line at the start of your script:

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

and put it in a directory on your PATH (can be a symlink):

cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname

How do I parse a string with a decimal point to a double?

My two cents on this topic, trying to provide a generic, double conversion method:

private static double ParseDouble(object value)
{
    double result;

    string doubleAsString = value.ToString();
    IEnumerable<char> doubleAsCharList = doubleAsString.ToList();

    if (doubleAsCharList.Where(ch => ch == '.' || ch == ',').Count() <= 1)
    {
        double.TryParse(doubleAsString.Replace(',', '.'),
            System.Globalization.NumberStyles.Any,
            CultureInfo.InvariantCulture,
            out result);
    }
    else
    {
        if (doubleAsCharList.Where(ch => ch == '.').Count() <= 1
            && doubleAsCharList.Where(ch => ch == ',').Count() > 1)
        {
            double.TryParse(doubleAsString.Replace(",", string.Empty),
                System.Globalization.NumberStyles.Any,
                CultureInfo.InvariantCulture,
                out result);
        }
        else if (doubleAsCharList.Where(ch => ch == ',').Count() <= 1
            && doubleAsCharList.Where(ch => ch == '.').Count() > 1)
        {
            double.TryParse(doubleAsString.Replace(".", string.Empty).Replace(',', '.'),
                System.Globalization.NumberStyles.Any,
                CultureInfo.InvariantCulture,
                out result);
        }
        else
        {
            throw new ParsingException($"Error parsing {doubleAsString} as double, try removing thousand separators (if any)");
        }
    }

    return result;
}

Works as expected with:

  • 1.1
  • 1,1
  • 1,000,000,000
  • 1.000.000.000
  • 1,000,000,000.99
  • 1.000.000.000,99
  • 5,000,111.3
  • 5.000.111,3
  • 0.99,000,111,88
  • 0,99.000.111.88

No default conversion is implemented, so it would fail trying to parse 1.3,14, 1,3.14 or similar cases.

How do I create a folder in VB if it doesn't exist?

Under System.IO, there is a class called Directory. Do the following:

If Not Directory.Exists(path) Then
    Directory.CreateDirectory(path)
End If

It will ensure that the directory is there.

Android Button setOnClickListener Design

If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.

<Button 
   android:height="wrap_content"
   android:width="wrap_content"
   android:onClick="myClickHandler" />

And in the Java class, use these below lines of code:

class MyActivity extends Activity {
    public void myClickHandler(View target) {
        // Do stuff
    }
}

Simple PHP calculator

You need to assign $first and $second

$first = $_POST['first'];
$second= $_POST['second'];

Also, As Travesty3 said, you need to do your arithmetic outside of the quotes:

echo $first + $second;

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

What is better, adjacency lists or adjacency matrices for graph problems in C++?

It depends on what you're looking for.

With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very inefficient especially if your graph is sparse.

On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.

Generally though, adjacency lists are the right data structure for most applications of graphs.

jQuery/JavaScript: accessing contents of an iframe

I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

This is the simplest way for an amateur like me who is studying C++ on their own:

First Unzip the boost library to any directory of your choice. I recommend c:\directory.

  1. Open your visual C++.
  2. Create a new project.
  3. Right click on the project.
  4. Click on property.
  5. Click on C/C++.
  6. Click on general.
  7. Select additional include library.
  8. Include the library destination. e.g. c:\boost_1_57_0.
  9. Click on pre-compiler header.
  10. Click on create/use pre-compiled header.
  11. Select not using pre-compiled header.

Then go over to the link library were you experienced your problems.

  1. Go to were the extracted file was c:\boost_1_57_0.
  2. Click on booststrap.bat (don't bother to type on the command window just wait and don't close the window that is the place I had my problem that took me two weeks to solve. After a while the booststrap will run and produce the same file, but now with two different names: b2, and bjam.
  3. Click on b2 and wait it to run.
  4. Click on bjam and wait it to run. Then a folder will be produce called stage.
  5. Right click on the project.
  6. Click on property.
  7. Click on linker.
  8. Click on general.
  9. Click on include additional library directory.
  10. Select the part of the library e.g. c:\boost_1_57_0\stage\lib.

And you are good to go!

How to select min and max values of a column in a datatable?

var min = dt.AsEnumerable().Min(row => row["AccountLevel"]);
var max = dt.AsEnumerable().Max(row => row["AccountLevel"]);

Create aar file in Android Studio

To create AAR

while creating follow below steps.

File->New->New Module->Android Library and create.

To generate AAR

Go to gradle at top right pane in android studio follow below steps.

Gradle->Drop down library name -> tasks-> build-> assemble or assemble release

AAR will be generated in build/outputs/aar/

But if we want AAR to get generated in specific folder in project directory with name you want, modify your app level build.gradle like below

defaultConfig {
    minSdkVersion 26
    targetSdkVersion 28
    versionCode System.getenv("BUILD_NUMBER") as Integer ?: 1
    versionName "0.0.${versionCode}"


    libraryVariants.all { variant ->

        variant.outputs.all { output ->
            outputFileName = "/../../../../release/" + ("your_recommended_name.aar")
        }
    }
}

Now it will create folder with name "release" in project directory which will be having AAR.

To import "aar" into project,check below link.

How to manually include external aar package using new Gradle Android Build System

How to compare two tables column by column in oracle

Used full outer join -- But it will not show - if its not matched -

SQL> desc aaa - its a table Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> desc aaav -its a view Name Null? Type


A1 NUMBER B1 VARCHAR2(10)

SQL> select a.column_name,b.column_name from dba_tab_columns a full outer join dba_tab_columns b on a.column_name=b.column_name where a.TABLE_NAME='AAA' and B.table_name='AAAV';

COLUMN_NAME COLUMN_NAME


A1 A1 B1 B1

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

How to create a custom string representation for a class object?

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print C

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

Using LIKE operator with stored procedure parameters

I was working on same. Check below statement. Worked for me!!


SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'

How can I get dictionary key as variable directly in Python (not by searching from value)?

You can do this by casting the dict keys and values to list. It can also be be done for items.

Example:

f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'

list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'

How to get query string parameter from MVC Razor markup?

It was suggested to post this as an answer, because some other answers are giving errors like 'The name Context does not exist in the current context'.

Just using the following works:

Request.Query["queryparm1"]

Sample usage:

<a href="@Url.Action("Query",new {parm1=Request.Query["queryparm1"]})">GO</a>

Call Javascript onchange event by programmatically changing textbox value

You can put it in a different class and then call a function. This works when ajax refresh

$(document).on("change", ".inputQty", function(e) {

//Call a function(input,input);
});

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

GLSL Shader version based on Patapoms answer:

vec3 HSV2RGB( vec3 hsv )
{
    hsv.x = mod( 100.0 + hsv.x, 1.0 ); // Ensure [0,1[
    float   HueSlice = 6.0 * hsv.x; // In [0,6[
    float   HueSliceInteger = floor( HueSlice );
    float   HueSliceInterpolant = HueSlice - HueSliceInteger; // In [0,1[ for each hue slice
    vec3  TempRGB = vec3(   hsv.z * (1.0 - hsv.y), hsv.z * (1.0 - hsv.y * HueSliceInterpolant), hsv.z * (1.0 - hsv.y * (1.0 - HueSliceInterpolant)) );
    float   IsOddSlice = mod( HueSliceInteger, 2.0 ); // 0 if even (slices 0, 2, 4), 1 if odd (slices 1, 3, 5)
    float   ThreeSliceSelector = 0.5 * (HueSliceInteger - IsOddSlice); // (0, 1, 2) corresponding to slices (0, 2, 4) and (1, 3, 5)
    vec3  ScrollingRGBForEvenSlices = vec3( hsv.z, TempRGB.zx );           // (V, Temp Blue, Temp Red) for even slices (0, 2, 4)
    vec3  ScrollingRGBForOddSlices = vec3( TempRGB.y, hsv.z, TempRGB.x );  // (Temp Green, V, Temp Red) for odd slices (1, 3, 5)
    vec3  ScrollingRGB = mix( ScrollingRGBForEvenSlices, ScrollingRGBForOddSlices, IsOddSlice );
    float   IsNotFirstSlice = clamp( ThreeSliceSelector, 0.0,1.0 );                   // 1 if NOT the first slice (true for slices 1 and 2)
    float   IsNotSecondSlice = clamp( ThreeSliceSelector-1.0, 0.0,1. );              // 1 if NOT the first or second slice (true only for slice 2)
    return  mix( ScrollingRGB.xyz, mix( ScrollingRGB.zxy, ScrollingRGB.yzx, IsNotSecondSlice ), IsNotFirstSlice );    // Make the RGB rotate right depending on final slice index
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

The JDK does not install a JVM in the default path.

Unless you need external tools to run like ant, the non-JDK is enough for Eclipse to run. The easiest way to install such a JVM is to go to http://java.com and let it install whatever it want to install.

Then double-click the Eclipse binary again.

How to read a specific line using the specific line number from a file in Java?

You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.

Example:

File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);

lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));      

The above example reads a text file composed of 50 lines in the following format:

[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN

Disclamer: I wrote this library

Reading int values from SqlDataReader

Use the GetInt method.

reader.GetInt32(3);

For..In loops in JavaScript - key value pairs

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);
    }
}

hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

No provider for Router?

Nothing works from this tread. "forRoot" doesn't help.

Sorry. Sorted this out. I've managed to make it work by setting correct "routes" for this "forRoot" router setup routine


    import {RouterModule, Routes} from '@angular/router';    
    import {AppComponent} from './app.component';
    
    const appRoutes: Routes = [
      {path: 'UI/part1/Details', component: DetailsComponent}
    ];
    
    @NgModule({
      declarations: [
        AppComponent,
        DetailsComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes)
      ],
      providers: [DetailsService],
      bootstrap: [AppComponent]
    })

Also may be helpful (spent some time to realize this) Optional route part:

    const appRoutes: Routes = [
       {path: 'UI/part1/Details', component: DetailsComponent},
       {path: ':project/UI/part1/Details', component: DetailsComponent}
    ];

Second rule allows to open URLs like
hostname/test/UI/part1/Details?id=666
and
hostname/UI/part1/Details?id=666

Been working as a frontend developer since 2012 but never stuck in a such over-complicated thing as angular2 (I have 3 years experience with enterprise level ExtJS)

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

How do I create a comma-separated list from an array in PHP?

You want to use implode for this.

ie: $commaList = implode(', ', $fruit);


There is a way to append commas without having a trailing one. You'd want to do this if you have to do some other manipulation at the same time. For example, maybe you want to quote each fruit and then separate them all by commas:

$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
    $fruitList .= $prefix . '"' . $fruit . '"';
    $prefix = ', ';
}

Also, if you just do it the "normal" way of appending a comma after each item (like it sounds you were doing before), and you need to trim the last one off, just do $list = rtrim($list, ', '). I see a lot of people unnecessarily mucking around with substr in this situation.

What's a quick way to comment/uncomment lines in Vim?

Toggle comments

If all you need is toggle comments I'd rather go with commentary.vim by tpope.

enter image description here

Installation

Pathogen:

cd ~/.vim/bundle
git clone git://github.com/tpope/vim-commentary.git

vim-plug:

Plug 'tpope/vim-commentary'

Vundle:

Plugin 'tpope/vim-commentary'

Further customization

Add this to your .vimrc file: noremap <leader>/ :Commentary<cr>

You can now toggle comments by pressing Leader+/, just like Sublime and Atom.

How to convert / cast long to String?

String logStringVal= date+"";

Can convert the long into string object, cool shortcut for converting into string...but use of String.valueOf(date); is advisable

Get selected value from combo box in C# WPF

To get the value of the ComboBox's selected index in C# use:

Combobox.SelectedValue

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

How do I disable fail_on_empty_beans in Jackson?

If you use org.codehaus.jackson.map.ObjectMapper, then pls. use the following lines

mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

csv.Error: iterator should return strings, not bytes

The reason it is throwing that exception is because you have the argument rb, which opens the file in binary mode. Change that to r, which will by default open the file in text mode.

Your code:

import csv
ifile  = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
    print (row) 

New code:

import csv
ifile  = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
    print (row)

Laravel 5 Class 'form' not found

You can also try running the following commands in Terminal or Command:

  1. composer dump-auto or composer dump-auto -o
  2. php artisan cache:clear
  3. php artisan config:clear

The above worked for me.

How to check whether an array is empty using PHP?

Why has no one said this answer:

$array = [];

if($array == []) {
    // array is empty
}

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

Java Read Large Text File With 70million line of text

enter image description hereI actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system. I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ReadComplexDelimitedFile {
    private static long total = 0;
    private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");

    @SuppressWarnings("unused")
    private void readFileUsingScanner() {

        String s;
        try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
            while (stdin.hasNextLine()) {
                s = stdin.nextLine();
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total = total + fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }

    //Winner
    private void readFileUsingCustomBufferedReader() {

        try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    private void readFileUsingBufferedReader() {

        try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingLineReader() {

        try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingStreams() {

        try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
            total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    private void readFileUsingBufferedReaderFileChannel() {
        try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
            try (FileChannel inputChannel = fis.getChannel()) {
                try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
                    String s;
                    while ((s = stdin.readLine()) != null) {
                        String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                        total = total + fields.length;
                    }
                }
            } catch (Exception e) {
                System.err.println("Error");
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    public static void main(String args[]) {
        //JVM wamrup
        for (int i = 0; i < 100000; i++) {
            total += i;
        }
        // We know scanner is slow-Still warming up
        ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
        List<Long> longList = new ArrayList<>(50);
        for (int i = 0; i < 50; i++) {
            total = 0;
            long startTime = System.nanoTime();
            //readComplexDelimitedFile.readFileUsingScanner();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingScanner");
        longList.forEach(System.out::println);
        // Actual performance test starts here

        longList = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingStreams();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingStreams");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingCustomBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingCustomBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingLineReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingLineReader");
        longList.forEach(System.out::println);

    }
}

I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)

import com.sun.istack.internal.NotNull;

import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * Reads text from a character-input stream, buffering characters so as to
 * provide for the efficient reading of characters, arrays, and lines.
 * <p>
 * <p> The buffer size may be specified, or the default size may be used.  The
 * default is large enough for most purposes.
 * <p>
 * <p> In general, each read request made of a Reader causes a corresponding
 * read request to be made of the underlying character or byte stream.  It is
 * therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
 * operations may be costly, such as FileReaders and InputStreamReaders.  For
 * example,
 * <p>
 * <pre>
 * CustomBufferedReader in
 *   = new CustomBufferedReader(new FileReader("foo.in"));
 * </pre>
 * <p>
 * will buffer the input from the specified file.  Without buffering, each
 * invocation of read() or readLine() could cause bytes to be read from the
 * file, converted into characters, and then returned, which can be very
 * inefficient.
 * <p>
 * <p> Programs that use DataInputStreams for textual input can be localized by
 * replacing each DataInputStream with an appropriate CustomBufferedReader.
 *
 * @author Mark Reinhold
 * @see FileReader
 * @see InputStreamReader
 * @see java.nio.file.Files#newBufferedReader
 * @since JDK1.1
 */

public class CustomBufferedReader extends Reader {

    private final Reader in;

    private char cb[];
    private int nChars, nextChar;

    private static final int INVALIDATED = -2;
    private static final int UNMARKED = -1;
    private int markedChar = UNMARKED;
    private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

    /**
     * If the next character is a line feed, skip it
     */
    private boolean skipLF = false;

    /**
     * The skipLF flag when the mark was set
     */
    private boolean markedSkipLF = false;

    private static int defaultCharBufferSize = 8192;
    private static int defaultExpectedLineLength = 80;
    private ReadWriteLock rwlock;


    /**
     * Creates a buffering character-input stream that uses an input buffer of
     * the specified size.
     *
     * @param in A Reader
     * @param sz Input-buffer size
     * @throws IllegalArgumentException If {@code sz <= 0}
     */
    public CustomBufferedReader(@NotNull final Reader in, int sz) {
        super(in);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.in = in;
        cb = new char[sz];
        nextChar = nChars = 0;
        rwlock = new ReentrantReadWriteLock();
    }

    /**
     * Creates a buffering character-input stream that uses a default-sized
     * input buffer.
     *
     * @param in A Reader
     */
    public CustomBufferedReader(@NotNull final Reader in) {
        this(in, defaultCharBufferSize);
    }


    /**
     * Fills the input buffer, taking the mark into account if it is valid.
     */
    private void fill() throws IOException {
        int dst;
        if (markedChar <= UNMARKED) {
            /* No mark */
            dst = 0;
        } else {
            /* Marked */
            int delta = nextChar - markedChar;
            if (delta >= readAheadLimit) {
                /* Gone past read-ahead limit: Invalidate mark */
                markedChar = INVALIDATED;
                readAheadLimit = 0;
                dst = 0;
            } else {
                if (readAheadLimit <= cb.length) {
                    /* Shuffle in the current buffer */
                    System.arraycopy(cb, markedChar, cb, 0, delta);
                    markedChar = 0;
                    dst = delta;
                } else {
                    /* Reallocate buffer to accommodate read-ahead limit */
                    char ncb[] = new char[readAheadLimit];
                    System.arraycopy(cb, markedChar, ncb, 0, delta);
                    cb = ncb;
                    markedChar = 0;
                    dst = delta;
                }
                nextChar = nChars = delta;
            }
        }

        int n;
        do {
            n = in.read(cb, dst, cb.length - dst);
        } while (n == 0);
        if (n > 0) {
            nChars = dst + n;
            nextChar = dst;
        }
    }

    /**
     * Reads a single character.
     *
     * @return The character read, as an integer in the range
     * 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
     * end of the stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public char readChar() throws IOException {
        for (; ; ) {
            if (nextChar >= nChars) {
                fill();
                if (nextChar >= nChars)
                    return (char) -1;
            }
            return cb[nextChar++];
        }
    }

    /**
     * Reads characters into a portion of an array, reading from the underlying
     * stream if necessary.
     */
    private int read1(char[] cbuf, int off, int len) throws IOException {
        if (nextChar >= nChars) {
            /* If the requested length is at least as large as the buffer, and
               if there is no mark/reset activity, and if line feeds are not
               being skipped, do not bother to copy the characters into the
               local buffer.  In this way buffered streams will cascade
               harmlessly. */
            if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
                return in.read(cbuf, off, len);
            }
            fill();
        }
        if (nextChar >= nChars) return -1;
        int n = Math.min(len, nChars - nextChar);
        System.arraycopy(cb, nextChar, cbuf, off, n);
        nextChar += n;
        return n;
    }

    /**
     * Reads characters into a portion of an array.
     * <p>
     * <p> This method implements the general contract of the corresponding
     * <code>{@link Reader#read(char[], int, int) read}</code> method of the
     * <code>{@link Reader}</code> class.  As an additional convenience, it
     * attempts to read as many characters as possible by repeatedly invoking
     * the <code>read</code> method of the underlying stream.  This iterated
     * <code>read</code> continues until one of the following conditions becomes
     * true: <ul>
     * <p>
     * <li> The specified number of characters have been read,
     * <p>
     * <li> The <code>read</code> method of the underlying stream returns
     * <code>-1</code>, indicating end-of-file, or
     * <p>
     * <li> The <code>ready</code> method of the underlying stream
     * returns <code>false</code>, indicating that further input requests
     * would block.
     * <p>
     * </ul> If the first <code>read</code> on the underlying stream returns
     * <code>-1</code> to indicate end-of-file then this method returns
     * <code>-1</code>.  Otherwise this method returns the number of characters
     * actually read.
     * <p>
     * <p> Subclasses of this class are encouraged, but not required, to
     * attempt to read as many characters as possible in the same fashion.
     * <p>
     * <p> Ordinarily this method takes characters from this stream's character
     * buffer, filling it from the underlying stream as necessary.  If,
     * however, the buffer is empty, the mark is not valid, and the requested
     * length is at least as large as the buffer, then this method will read
     * characters directly from the underlying stream into the given array.
     * Thus redundant <code>CustomBufferedReader</code>s will not copy data
     * unnecessarily.
     *
     * @param cbuf Destination buffer
     * @param off  Offset at which to start storing characters
     * @param len  Maximum number of characters to read
     * @return The number of characters read, or -1 if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public int read(char cbuf[], int off, int len) throws IOException {
        int n = read1(cbuf, off, len);
        if (n <= 0) return n;
        while ((n < len) && in.ready()) {
            int n1 = read1(cbuf, off + n, len - n);
            if (n1 <= 0) break;
            n += n1;
        }
        return n;
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @param ignoreLF If true, the next '\n' will be skipped
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.io.LineNumberReader#readLine()
     */
    String readLine(boolean ignoreLF) throws IOException {
        StringBuilder s = null;
        int startChar;



        bufferLoop:
        for (; ; ) {

            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars) { /* EOF */
                if (s != null && s.length() > 0)
                    return s.toString();
                else
                    return null;
            }
            boolean eol = false;
            char c = 0;
            int i;

            /* Skip a leftover '\n', if necessary */



            charLoop:
            for (i = nextChar; i < nChars; i++) {
                c = cb[i];
                if ((c == '\n')) {
                    eol = true;
                    break charLoop;
                }
            }

            startChar = nextChar;
            nextChar = i;

            if (eol) {
                String str;
                if (s == null) {
                    str = new String(cb, startChar, i - startChar);
                } else {
                    s.append(cb, startChar, i - startChar);
                    str = s.toString();
                }
                nextChar++;
                return str;
            }

            if (s == null)
                s = new StringBuilder(defaultExpectedLineLength);
            s.append(cb, startChar, i - startChar);
        }
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false);
    }

    /**
     * Skips characters.
     *
     * @param n The number of characters to skip
     * @return The number of characters actually skipped
     * @throws IllegalArgumentException If <code>n</code> is negative.
     * @throws IOException              If an I/O error occurs
     */
    public long skip(long n) throws IOException {
        if (n < 0L) {
            throw new IllegalArgumentException("skip value is negative");
        }
        rwlock.readLock().lock();
            long r = n;
            try{
            while (r > 0) {
                if (nextChar >= nChars)
                    fill();
                if (nextChar >= nChars) /* EOF */
                    break;
                if (skipLF) {
                    skipLF = false;
                    if (cb[nextChar] == '\n') {
                        nextChar++;
                    }
                }
                long d = nChars - nextChar;
                if (r <= d) {
                    nextChar += r;
                    r = 0;
                    break;
                } else {
                    r -= d;
                    nextChar = nChars;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return n - r;
    }

    /**
     * Tells whether this stream is ready to be read.  A buffered character
     * stream is ready if the buffer is not empty, or if the underlying
     * character stream is ready.
     *
     * @throws IOException If an I/O error occurs
     */
    public boolean ready() throws IOException {
        rwlock.readLock().lock();
        try {
            /*
             * If newline needs to be skipped and the next char to be read
             * is a newline character, then just skip it right away.
             */
            if (skipLF) {
                /* Note that in.ready() will return true if and only if the next
                 * read on the stream will not block.
                 */
                if (nextChar >= nChars && in.ready()) {
                    fill();
                }
                if (nextChar < nChars) {
                    if (cb[nextChar] == '\n')
                        nextChar++;
                    skipLF = false;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return (nextChar < nChars) || in.ready();

    }

    /**
     * Tells whether this stream supports the mark() operation, which it does.
     */
    public boolean markSupported() {
        return true;
    }

    /**
     * Marks the present position in the stream.  Subsequent calls to reset()
     * will attempt to reposition the stream to this point.
     *
     * @param readAheadLimit Limit on the number of characters that may be
     *                       read while still preserving the mark. An attempt
     *                       to reset the stream after reading characters
     *                       up to this limit or beyond may fail.
     *                       A limit value larger than the size of the input
     *                       buffer will cause a new buffer to be allocated
     *                       whose size is no smaller than limit.
     *                       Therefore large values should be used with care.
     * @throws IllegalArgumentException If {@code readAheadLimit < 0}
     * @throws IOException              If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
        if (readAheadLimit < 0) {
            throw new IllegalArgumentException("Read-ahead limit < 0");
        }
        rwlock.readLock().lock();
        try {
            this.readAheadLimit = readAheadLimit;
            markedChar = nextChar;
            markedSkipLF = skipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    /**
     * Resets the stream to the most recent mark.
     *
     * @throws IOException If the stream has never been marked,
     *                     or if the mark has been invalidated
     */
    public void reset() throws IOException {
        rwlock.readLock().lock();
        try {
            if (markedChar < 0)
                throw new IOException((markedChar == INVALIDATED)
                        ? "Mark invalid"
                        : "Stream not marked");
            nextChar = markedChar;
            skipLF = markedSkipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    public void close() throws IOException {
        rwlock.readLock().lock();
        try {
            in.close();
        } finally {
            cb = null;
            rwlock.readLock().unlock();
        }

    }

    public Stream<String> lines() {
        Iterator<String> iter = new Iterator<String>() {
            String nextLine = null;

            @Override
            public boolean hasNext() {
                if (nextLine != null) {
                    return true;
                } else {
                    try {
                        nextLine = readLine();
                        return (nextLine != null);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            }

            @Override
            public String next() {
                if (nextLine != null || hasNext()) {
                    String line = nextLine;
                    nextLine = null;
                    return line;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
    }
}

And now the results:

Time taken for readFileUsingBufferedReaderFileChannel 2902690903 1845190694 1894071377 1815161868 1861056735 1867693540 1857521371 1794176251 1768008762 1853089582

Time taken for readFileUsingBufferedReader 2022837353 1925901163 1802266711 1842689572 1899984555 1843101306 1998642345 1821242301 1820168806 1830375108

Time taken for readFileUsingStreams 1992855461 1930827034 1850876033 1843402533 1800378283 1863581324 1810857226 1798497108 1809531144 1796345853

Time taken for readFileUsingCustomBufferedReader 1759732702 1765987214 1776997357 1772999486 1768559162 1755248431 1744434555 1750349867 1740582606 1751390934

Time taken for readFileUsingLineReader 1845307174 1830950256 1829847321 1828125293 1827936280 1836947487 1832186310 1820276327 1830157935 1829171481

Process finished with exit code 0

Inference: The test was run on a 200 MB file. The test was repeated several times. The data looked like this

Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011

Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.

Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second

Can I install Python 3.x and 2.x on the same Windows computer?

Here's my setup:

  1. Install both Python 2.7 and 3.4 with the windows installers.
  2. Go to C:\Python34 (the default install path) and change python.exe to python3.exe
  3. Edit your environment variables to include C:\Python27\;C:\Python27\Scripts\;C:\Python34\;C:\Python34\Scripts\;

Now in command line you can use python for 2.7 and python3 for 3.4.

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

PHP stores error logs in /var/log/apache2 if PHP is an apache2 module. Shared hosts are often storing log files in your root directory /log subfolder. But...if you have access to a php.ini file you can do this:

error_log = /var/log/php-scripts.log

According to rinogo's comment: If you're using cPanel, the master log file you're probably looking for is stored (by default) at

/usr/local/apache/logs/error_log

If all else fails you can check the location of the log file using

<?php phpinfo(); ?>

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

Wait .5 seconds before continuing code VB.net

Make a timer, that activates whatever code you want to when it ticks. Make sure the first line in the timer's code is:

timer.enabled = false

Replace timer with whatever you named your timer.

Then use this in your code:

   WebBrowser1.Document.Window.DomWindow.execscript("checkPasswordConfirm();","JavaScript")
timer.enabled = true
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
    If webpageelement.InnerText = "Sign Up" Then
        webpageelement.InvokeMember("click")
    End If
Next

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

IntelliJ sometimes gets confused all by itself, even without the external changes Korgen described (though that is a good way to consistently reproduce it).

Click File -> Synchronize, and IntelliJ should see that everything is okay again.

If that doesn't work, IntelliJ's caches might be corrupt (this used to happen a lot more often than it does now); in that case, regenerate them by

Clicking File -> Invalidate Caches and restarting the IDE

(though loading the project will take a while while the caches are recreated).

LINUX: Link all files from one to another directory

GNU cp has an option to create symlinks instead of copying.

cp -rs /mnt/usr/lib /usr/

Note this is a GNU extension not found in POSIX cp.

How do I get the current location of an iframe?

HTA works like a normal windows application.
You write HTML code, and save it as an .hta file.

However, there are, at least, one drawback: The browser can't open an .hta file; it's handled as a normal .exe program. So, if you place a link to an .hta onto your web page, it will open a download dialog, asking of you want to open or save the HTA file. If its not a problem for you, you can click "Open" and it will open a new window (that have no toolbars, so no Back button, neither address bar, neither menubar).

I needed to do something very similar to what you want, but instead of iframes, I used a real frameset.
The main page need to be a .hta file; the other should be a normal .htm page (or .php or whatever).

Here's an example of a HTA page with 2 frames, where the top one have a button and a text field, that contains the second frame URL; the button updates the field:

frameset.hta

<html>
    <head>
        <title>HTA Example</title>
        <HTA:APPLICATION id="frames" border="thin" caption="yes" icon="http://www.google.com/favicon.ico" showintaskbar="yes" singleinstance="no" sysmenu="yes" navigable="yes" contextmenu="no" innerborder="no" scroll="auto" scrollflat="yes" selection="yes" windowstate="normal"></HTA:APPLICATION>
    </head>
    <frameset rows="60px, *">
        <frame src="topo.htm" name="topo" id="topo" application="yes" />
        <frame src="http://www.google.com" name="conteudo" id="conteudo" application="yes" />
    </frameset>
</html>
  • There's an HTA:APPLICATION tag that sets some properties to the file; it's good to have, but it isn't a must.
  • You NEED to place an application="yes" at the frames' tags. It says they belongs to the program too and should have access to all data (if you don't, the frames will still show the error you had before).

topo.htm

<html>
    <head>
        <title>Topo</title>
        <script type="text/javascript">
            function copia_url() {
                campo.value = parent.conteudo.location;
            }
        </script>
    </head>
    <body style="background: lightBlue;" onload="copia_url()">
        <input type="button" value="Copiar URL" onclick="copia_url()" />
        <input type="text" size="120" id="campo" />
    </body>
</html>
  • You should notice that I didn't used any getElement function to fetch the field; on HTA file, all elements that have an ID becomes instantly an object

I hope this help you, and others that get to this question. It solved my problem, that looks like to be the same as you have.

You can found more information here: http://www.irt.org/articles/js191/index.htm

Enjoy =]

How to round up a number to nearest 10?

My first impulse was to google for "php math" and I discovered that there's a core math library function called "round()" that likely is what you want.

Can I fade in a background image (CSS: background-image) with jQuery?

jquery:

 $("div").fadeTo(1000 , 1);

css

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

html

<div></div>

What's the difference between a 302 and a 307 redirect?

307 came about because user agents adopted as a de facto behaviour to take POST requests that receive a 302 response and send a GET request to the Location response header.

That is the incorrect behaviour — only a 303 should cause a POST to turn into a GET. User agents should (but don't) stick with the POST method when requesting the new URL if the original POST request returned a 302.

307 was introduced to allow servers to make it clear to the user agent that a method change should not be made by the client when following the Location response header.

Breaking out of a nested loop

Use a suitable guard in the outer loop. Set the guard in the inner loop before you break.

bool exitedInner = false;

for (int i = 0; i < N && !exitedInner; ++i) {

    .... some outer loop stuff

    for (int j = 0; j < M; ++j) {

        if (sometest) {
            exitedInner = true;
            break;
        }
    }
    if (!exitedInner) {
       ... more outer loop stuff
    }
}

Or better yet, abstract the inner loop into a method and exit the outer loop when it returns false.

for (int i = 0; i < N; ++i) {

    .... some outer loop stuff

    if (!doInner(i, N, M)) {
       break;
    }

    ... more outer loop stuff
}

How to make a view with rounded corners?

Use shape in xml with rectangle.set the property of bottom or upper radius as want.then apply that xml as background to ur view....or...use gradients to do it from code.

Rotate label text in seaborn factorplot

For a seaborn.heatmap, you can rotate these using (based on @Aman's answer)

pandas_frame = pd.DataFrame(data, index=names, columns=names)
heatmap = seaborn.heatmap(pandas_frame)
loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=45)
heatmap.set_yticklabels(labels[::-1], rotation=45) # reversed order for y

How to downgrade tensorflow, multiple versions possible?

I discovered the joy of anaconda: https://www.continuum.io/downloads

C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1) 
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl

voila, a virtual environment is created.

How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following steps:

  1. Install Tomcat7
  2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and paste it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
  3. Setup paths in your Environment Variables as shown below:

C:>echo %path%

C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;

C:>echo %classpath%

C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;

C:>echo %CATALINA_HOME%

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;

C:>echo %JAVA_HOME%

C:\Program Files (x86)\Java\jdk1.6.0_27;

Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:

C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

Now start Tomcat service by double clicking on 'Tomcat7.exe' under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin'.

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

How do I check if a string is a number (float)?

def is_float(s):
    if s is None:
        return False

    if len(s) == 0:
        return False

    digits_count = 0
    dots_count = 0
    signs_count = 0

    for c in s:
        if '0' <= c <= '9':
            digits_count += 1
        elif c == '.':
            dots_count += 1
        elif c == '-' or c == '+':
            signs_count += 1
        else:
            return False

    if digits_count == 0:
        return False

    if dots_count > 1:
        return False

    if signs_count > 1:
        return False

    return True

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

Check that a input to UITextField is numeric only

In Swift 4:

let formatString = "12345"
if let number = Decimal(string:formatString){

    print("String contains only number")
}
else{
    print("String doesn't contains only number")
}

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h"
#include "Ball.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

if your pods are empty

  1. remove copy pods resources and check pods manifest.
  2. lock from build phases settings of your project

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

Can HTTP POST be limitless?

HTTP may not have an upper limit, but webservers may have one. In ASP.NET there is a default accept-limit of 4 MB, but you (the developer/webmaster) can change that to be higher or lower.

How to get the list of all printers in computer

You can also use the LocalPrintServer class. See: System.Printing.LocalPrintServer

    public List<string>  InstalledPrinters
    {
        get
        {
            return (from PrintQueue printer in new LocalPrintServer().GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local,
                EnumeratedPrintQueueTypes.Connections }).ToList()
                    select printer.Name).ToList(); 
        } 
    }

As stated in the docs: Classes within the System.Printing namespace are not supported for use within a Windows service or ASP.NET application or service.

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.

<HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

      <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            //xml code
      </ScrollView>
</HorizontalScrollView>

How to convert a string of bytes into an int?

import array
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]

Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.

How to stop "setInterval"

You have to store the timer id of the interval when you start it, you will use this value later to stop it, using the clearInterval function:

$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    timerId = setInterval(function () {
      // interval function body
    }, 1000);
  });

  $('textarea').blur(function () {
    clearInterval(timerId);
  });

});

Populating a data frame in R in a loop

It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:

  1. Preallocate your data.frame. This is not recommended because indexing is slow for data.frames.
  2. Use another data structure in the loop and transform into a data.frame afterwards. A list is very useful here.

Example to illustrate the general approach:

mylist <- list() #create an empty list

for (i in 1:5) {
  vec <- numeric(5) #preallocate a numeric vector
  for (j in 1:5) { #fill the vector
    vec[j] <- i^j 
  }
  mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix

In this example it is not necessary to use a list, you could preallocate a matrix. However, if you do not know how many iterations your loop will need, you should use a list.

Finally here is a vectorized alternative to the example loop:

outer(1:5,1:5,function(i,j) i^j)

As you see it's simpler and also more efficient.

How Do I Upload Eclipse Projects to GitHub?

Jokab's answer helped me a lot but in my case I could not push to github until I logged in my github account to my git bash so i ran the following commands

git config credential.helper store

then

git push http://github.com/[user name]/[repo name].git

After the second command a GUI window appeared, I provided my login credentials and it worked for me.

What is the difference between include and require in Ruby?

'Load'- inserts a file's contents.(Parse file every time the file is being called)

'Require'- inserts a file parsed content.(File parsed once and stored in memory)

'Include'- includes the module into the class and can use methods inside the module as class's instance method

'Extend'- includes the module into the class and can use methods inside the module as class method

What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Array vs ArrayList in performance

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

Swift Error: Editor placeholder in source file

After Command + Shift + B, the project works fine.

How to compile a 64-bit application using Visual C++ 2010 Express?

Download the Windows SDK and then go to View->Properties->Configuration Manager->Active Solution Platform->New->x64.

C# DLL config file

Since the assembly resides in a temporary cache, you should combine the path to get the dll's config:

var appConfig = ConfigurationManager.OpenExeConfiguration(
    Path.Combine(Environment.CurrentDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name));

Calculate distance between two latitude-longitude points? (Haversine formula)

In the other answers an implementation in is missing.

Calculating the distance between two point is quite straightforward with the distm function from the geosphere package:

distm(p1, p2, fun = distHaversine)

where:

p1 = longitude/latitude for point(s)
p2 = longitude/latitude for point(s)
# type of distance calculation
fun = distCosine / distHaversine / distVincentySphere / distVincentyEllipsoid 

As the earth is not perfectly spherical, the Vincenty formula for ellipsoids is probably the best way to calculate distances. Thus in the geosphere package you use then:

distm(p1, p2, fun = distVincentyEllipsoid)

Off course you don't necessarily have to use geosphere package, you can also calculate the distance in base R with a function:

hav.dist <- function(long1, lat1, long2, lat2) {
  R <- 6371
  diff.long <- (long2 - long1)
  diff.lat <- (lat2 - lat1)
  a <- sin(diff.lat/2)^2 + cos(lat1) * cos(lat2) * sin(diff.long/2)^2
  b <- 2 * asin(pmin(1, sqrt(a))) 
  d = R * b
  return(d)
}

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

Safe navigation operator (?.) or (!.) and null property paths

A new library called ts-optchain provides this functionality, and unlike lodash' solution, it also keeps your types safe, here is a sample of how it is used (taken from the readme):

import { oc } from 'ts-optchain';

interface I {
  a?: string;
  b?: {
    d?: string;
  };
  c?: Array<{
    u?: {
      v?: number;
    };
  }>;
  e?: {
    f?: string;
    g?: () => string;
  };
}

const x: I = {
  a: 'hello',
  b: {
    d: 'world',
  },
  c: [{ u: { v: -100 } }, { u: { v: 200 } }, {}, { u: { v: -300 } }],
};

// Here are a few examples of deep object traversal using (a) optional chaining vs
// (b) logic expressions. Each of the following pairs are equivalent in
// result. Note how the benefits of optional chaining accrue with
// the depth and complexity of the traversal.

oc(x).a(); // 'hello'
x.a;

oc(x).b.d(); // 'world'
x.b && x.b.d;

oc(x).c[0].u.v(); // -100
x.c && x.c[0] && x.c[0].u && x.c[0].u.v;

oc(x).c[100].u.v(); // undefined
x.c && x.c[100] && x.c[100].u && x.c[100].u.v;

oc(x).c[100].u.v(1234); // 1234
(x.c && x.c[100] && x.c[100].u && x.c[100].u.v) || 1234;

oc(x).e.f(); // undefined
x.e && x.e.f;

oc(x).e.f('optional default value'); // 'optional default value'
(x.e && x.e.f) || 'optional default value';

// NOTE: working with function value types can be risky. Additional run-time
// checks to verify that object types are functions before invocation are advised!
oc(x).e.g(() => 'Yo Yo')(); // 'Yo Yo'
((x.e && x.e.g) || (() => 'Yo Yo'))();

How can I get customer details from an order in WooCommerce?

I was looking for something like this. It works well.

So get the mobile number in WooCommerce plugin like this -

$customer_id = get_current_user_id();
print get_user_meta($customer_id, 'billing_phone', true);

Joining three tables using MySQL

SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

jquery $.each() for objects

You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead. Change the code to as below:

<script>     
    $(document).ready(function() {         
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
        $.each(data.programs, function(key,val) {             
            alert(key+val);         
        });     
    }); 
</script> 

How do I wait until Task is finished in C#?

It waits for client.GetAsync("aaaaa");, but doesn't wait for result = Print(x)

Try responseTask.ContinueWith(x => result = Print(x)).Wait()

--EDIT--

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
responseTask.Wait();
Console.WriteLine("End");

Above code doesn't guarantee the output:

In task
In ContinueWith
End

But this does (see the newTask)

Task responseTask = Task.Run(() => { 
    Thread.Sleep(1000); 
    Console.WriteLine("In task"); 
});
Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
newTask.Wait();
Console.WriteLine("End");

Specify a Root Path of your HTML directory for script links?

I recommend using the HTML <base> element:

<head>
    <base href="http://www.example.com/default/">
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</head>

In this example, the stylesheet is located in http://www.example.com/default/style.css, the script in http://www.example.com/default/script.js. The advantage of <base> over / is that it is more flexible. Your whole website can be located in a subdirectory of a domain, and you can easily alter the default directory of your website.

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Applying the recursive function on numpy arrays will be faster than the current answer.

df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
    new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new

Output

      A  B  D    C
   0  1  1  1    1
   1  2  2  2    4
   2  3  3  3   15
   3  4  4  4   64
   4  5  5  5  325

"Too many values to unpack" Exception

That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

But this raises your error

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

raises

Traceback (most recent call last):
  File "c.py", line 3, in ?
    a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack

Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.

Oracle error : ORA-00905: Missing keyword

Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN) can cause the same error.

Example:

SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID

Or if its in the query itself as a field name

 SELECT ..., ...., IN, ..., .... FROM SOMETABLE

That would also throw that error. I hope this helps someone.

Converting bool to text in C++

I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):

#include <stdio.h>
#include <stdarg.h>

#define BOOL_STR(b) (b?"true":"false")

int main (int argc, char const *argv[]) {
    bool alpha = true;
    printf( BOOL_STR(alpha) );
    return 0;
}

Generating a PDF file from React Components

You can use ReactPDF

Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

How to change the style of alert box?

I use sweetalert2 library. It's really simple, a lot of customization, modern, animated windows, eye-catching, and also nice design.

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href>Why do I have this issue?</a>'
})

Check this link

When use getOne and findOne methods Spring Data JPA

I really find very difficult from the above answers. From debugging perspective i almost spent 8 hours to know the silly mistake.

I have testing spring+hibernate+dozer+Mysql project. To be clear.

I have User entity, Book Entity. You do the calculations of mapping.

Were the Multiple books tied to One user. But in UserServiceImpl i was trying to find it by getOne(userId);

public UserDTO getById(int userId) throws Exception {

    final User user = userDao.getOne(userId);

    if (user == null) {
        throw new ServiceException("User not found", HttpStatus.NOT_FOUND);
    }
    userDto = mapEntityToDto.transformBO(user, UserDTO.class);

    return userDto;
}

The Rest result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 1,
        "name": "TEST_ME",
        "bookList": null
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

The above code did not fetch the books which is read by the user let say.

The bookList was always null because of getOne(ID). After changing to findOne(ID). The result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 0,
        "name": "Annama",
        "bookList": [
            {
                "id": 2,
                "book_no": "The karma of searching",
            }
        ]
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

.gitignore all the .DS_Store files in every folder and subfolder

Your .gitignore file should look like this:

# Ignore Mac DS_Store files
.DS_Store

As long as you don't include a slash, it is matched against the file name in all directories. (from here)

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Generate table relationship diagram from existing schema (SQL Server)

SchemaCrawler for SQL Server can generate database diagrams, with the help of GraphViz. Foreign key relationships are displayed (and can even be inferred, using naming conventions), and tables and columns can be excluded using regular expressions.

link with target="_blank" does not open in new tab in Chrome

Because JavaScript is handling the click event. When you click, the following code is called:

el.addEvent('click', function(e){
    if(obj.options.onOpen){
        new Event(e).stop();
        if(obj.options.open == i){
            obj.options.open = null;
            obj.options.onClose(this.href, i);
        }else{
            obj.options.open = i;
            obj.options.onOpen(this.href, i);
        }   
    }       
})

The onOpen manually changes the location.

Edit: Regarding your comment... If you can modify ImageMenu.js, you could update the script which calls onClose to pass the a element object (this, rather than this.href)

obj.options.onClose(this, i);

Then update your ImageMenu instance, with the following onOpen change:

window.addEvent('domready', function(){
    var myMenu = new ImageMenu($$('#imageMenu a'), {
        openWidth: 310,
        border: 2,
        onOpen: function(e, i) {
            if (e.target === '_blank') {
                window.open(e.href);    
            } else {
                location = e.href;
            }
        }
    });
});

This would check for the target property of the element to see if it's _blank, and then call window.open, if found.

If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen handler. Say something like:

<a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a>

Then, update your onOpen call to:

onOpen: function(e, i) {
    if (e.indexOf('_b=1') > -1) {
        window.open(e);   
    } else {
        location = e;
    }
}

The only downside to this is the user sees the hash on hover.

Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like:

var linksThatOpenInANewWindow = {
    'http://www.foracure.org.au': 1
};

onOpen: function(e, i) {
    if (linksThatOpenInANewWindow[e] === 1) {
        window.open(e);   
    } else {
        location = e
    }
}

The only downside is maintenance, depending on the number of links.

Others have suggested modifying the link (using # or javascript:) and adding an inline event handler (onclick) - I don't recommend that at all as it breaks links when JS is disabled/not supported.

Posting array from form

Why are you sending it through a post if you already have it on the server (PHP) side?

Why not just save the array to the $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.

It will depend upon how you really want to do.

How to escape a JSON string containing newline characters using JavaScript?

this is an old post. but it may still be helpful for those using angular.fromJson, and JSON.stringify. escape() is deprecated. use this instead,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

How can I change or remove HTML5 form validation default error messages?

This is a very good link I found about checking various attributes of html5 validations.

https://dzone.com/articles/custom-validation-messages

Hope it helps someone.

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

How to build PDF file from binary string returned from a web-service using javascript

I saw another question on just this topic recently (streaming pdf into iframe using dataurl only works in chrome).

I've constructed pdfs in the ast and streamed them to the browser. I was creating them first with fdf, then with a pdf class I wrote myself - in each case the pdf was created from data retrieved from a COM object based on a couple of of GET params passed in via the url.

From looking at your data sent recieved in the ajax call, it looks like you're nearly there. I haven't played with the code for a couple of years now and didn't document it as well as I'd have cared to, but - I think all you need to do is set the target of an iframe to be the url you get the pdf from. Though this may not work - the file that oututs the pdf may also have to outut a html response header first.

In a nutshell, this is the output code I used:

//We send to a browser
header('Content-Type: application/pdf');
if(headers_sent())
    $this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->buffer));
header('Content-Disposition: inline; filename="'.$name.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo $this->buffer;

So, without seeing the full response text fro the ajax call I can't really be certain what it is, though I'm inclined to think that the code that outputs the pdf you're requesting may only be doig the equivalent of the last line in the above code. If it's code you have control over, I'd try setting the headers - then this way the browser can just deal with the response text - you don't have to bother doing a thing to it.

I simply constructed a url for the pdf I wanted (a timetable) then created a string that represented the html for an iframe of the desired sie, id etc that used the constructed url as it's src. As soon as I set the inner html of a div to the constructed html string, the browser asked for the pdf and then displayed it when it was received.

function  showPdfTt(studentId)
{
    var url, tgt;
    title = byId("popupTitle");
    title.innerHTML = "Timetable for " + studentId;
    tgt = byId("popupContent");
    url = "pdftimetable.php?";
    url += "id="+studentId;
    url += "&type=Student";
    tgt.innerHTML = "<iframe onload=\"centerElem(byId('box'))\" src='"+url+"' width=\"700px\" height=\"500px\"></iframe>";
}

EDIT: forgot to mention - you can send binary pdf's in this manner. The streams they contain don't need to be ascii85 or hex encoded. I used flate on all the streams in the pdf and it worked fine.

HTTPS connections over proxy servers

The short answer is: It is possible, and can be done with either a special HTTP proxy or a SOCKS proxy.

First and foremost, HTTPS uses SSL/TLS which by design ensures end-to-end security by establishing a secure communication channel over an insecure one. If the HTTP proxy is able to see the contents, then it's a man-in-the-middle eavesdropper and this defeats the goal of SSL/TLS. So there must be some tricks being played if we want to proxy through a plain HTTP proxy.

The trick is, we turn an HTTP proxy into a TCP proxy with a special command named CONNECT. Not all HTTP proxies support this feature but many do now. The TCP proxy cannot see the HTTP content being transferred in clear text, but that doesn't affect its ability to forward packets back and forth. In this way, client and server can communicate with each other with help of the proxy. This is the secure way of proxying HTTPS data.

There is also an insecure way of doing so, in which the HTTP proxy becomes a man-in-the-middle. It receives the client-initiated connection, and then initiate another connection to the real server. In a well implemented SSL/TLS, the client will be notified that the proxy is not the real server. So the client has to trust the proxy by ignoring the warning for things to work. After that, the proxy simply decrypts data from one connection, reencrypts and feeds it into the other.

Finally, we can certainly proxy HTTPS through a SOCKS proxy, because the SOCKS proxy works at a lower level. You may think a SOCKS proxy as both a TCP and a UDP proxy.

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

How to update an "array of objects" with Firestore?

You can use a transaction (https://firebase.google.com/docs/firestore/manage-data/transactions) to get the array, push onto it and then update the document:

    const booking = { some: "data" };
    const userRef = this.db.collection("users").doc(userId);

    this.db.runTransaction(transaction => {
        // This code may get re-run multiple times if there are conflicts.
        return transaction.get(userRef).then(doc => {
            if (!doc.data().bookings) {
                transaction.set({
                    bookings: [booking]
                });
            } else {
                const bookings = doc.data().bookings;
                bookings.push(booking);
                transaction.update(userRef, { bookings: bookings });
            }
        });
    }).then(function () {
        console.log("Transaction successfully committed!");
    }).catch(function (error) {
        console.log("Transaction failed: ", error);
    });

How to get Javascript Select box's selected text

Just use

$('#SelectBoxId option:selected').text(); For Getting text as listed

$('#SelectBoxId').val(); For Getting selected Index value

The proxy server received an invalid response from an upstream server

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

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

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

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

EDIT

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

How to create a function in a cshtml template?

If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I made a basic Demo and reproduced this problem. It seems that WinRT component failed to find the correct assembly of Newton.Json. Temporarily the workaround is to manually add the Newtonsoft.json.dll file. You can achieve this by following steps:

  1. Right click References-> Add Reference->Browse...-> Find C:\Users\.nuget\packages\Newtonsoft.Json\9.0.1\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.json.dll->Click Add button.

  2. Rebuild your Runtime Component project and run. This error should be gone.

HTML input - name vs. id

IDs must be unique

...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by

  • Javascript scripts loaded in the page
  • CSS styles defined on the page

Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seems that it works.

Names are quite often unique but can be shared

...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's value gets posted back to server even though there are several related radio button controls with the same name.

Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.

When names can be duplicated

It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like Asp.net MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.

Now suppose you have this scenario:

  • you have a view with a list of items of the same type
  • user usually works with one item at a time, so they will only enter data with one item alone and send it to server

So your view's model (since it displays a list) is of type IEnumerable<SomeType> but your server side only accepts one single item of type SomeType.

How about name sharing then?

Each item is wrapped within its own FORM element and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.

This particular scenario can be seen on my Creative stories mini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.

Error: Cannot pull with rebase: You have unstaged changes

When the unstaged change is because git is attempting to fix eol conventions on a file (as is always my case), no amount of stashing or checking-out or resetting will make it go away.

However, if the intent is really to rebase and ignore unstaged changed, then what I do is delete the branch locally then check it out again.

git checkout -f anyotherbranchthanthisone
git branch -D thebranchineedtorebase
git checkout thebranchineedtorebase

Voila! It hasn't failed me yet.

Java: get greatest common divisor

/*
import scanner and instantiate scanner class;
declare your method with two parameters
declare a third variable;
set condition;
swap the parameter values if condition is met;
set second conditon based on result of first condition;
divide and assign remainder to the third variable;
swap the result;
in the main method, allow for user input;
Call the method;

*/
public class gcf {
    public static void main (String[]args){//start of main method
        Scanner input = new Scanner (System.in);//allow for user input
        System.out.println("Please enter the first integer: ");//prompt
        int a = input.nextInt();//initial user input
        System.out.println("Please enter a second interger: ");//prompt
        int b = input.nextInt();//second user input


       Divide(a,b);//call method
    }
   public static void Divide(int a, int b) {//start of your method

    int temp;
    // making a greater than b
    if (b > a) {
         temp = a;
         a = b;
         b = temp;
    }

    while (b !=0) {
        // gcd of b and a%b
        temp = a%b;
        // always make a greater than b
        a =b;
        b =temp;

    }
    System.out.println(a);//print to console
  }
}

How do I automatically resize an image for a mobile site?

if you use bootstrap 3 , just add img-responsive class in your img tag

<img class="img-responsive"  src="...">

if you use bootstrap 4, add img-fluid class in your img tag

<img class="img-fluid"  src="...">

which does the staff: max-width: 100%, height: auto, and display:block to the image

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Another idea is to do myVar.split(',')[1];

For simple case, not using a regexp is a good idea...

Nested Recycler view height doesn't wrap its content

This answer is based on the solution given by Denis Nek. It solves the problem of not taking decorations like dividers into account.

public class WrappingRecyclerViewLayoutManager extends LinearLayoutManager {

public WrappingRecyclerViewLayoutManager(Context context)    {
    super(context, VERTICAL, false);
}

public WrappingRecyclerViewLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);
        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        Rect outRect = new Rect();
        calculateItemDecorationsForChild(view, outRect);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin + outRect.bottom + outRect.top;
        recycler.recycleView(view);
    }
}

}

Non-Static method cannot be referenced from a static context with methods and variables

You can either

1) Declare printMenu(), getUserchoice() and input as static

OR

2) If you want to design it better, move the logic from your main into a separate instance method. And then from the main create a new instance of your class and call your instance method(s)

How to solve a pair of nonlinear equations using Python?

from scipy.optimize import fsolve

def double_solve(f1,f2,x0,y0):
    func = lambda x: [f1(x[0], x[1]), f2(x[0], x[1])]
    return fsolve(func,[x0,y0])

def n_solve(functions,variables):
    func = lambda x: [ f(*x) for f in functions]
    return fsolve(func, variables)

f1 = lambda x,y : x**2+y**2-1
f2 = lambda x,y : x-y

res = double_solve(f1,f2,1,0)
res = n_solve([f1,f2],[1.0,0.0])

Changing button text onclick

var count=0;
document.getElementById("play").onclick = function(){


if(count%2 =="1"){

                document.getElementById("video").pause();
                document.getElementById("play").innerHTML ="Pause";
            }else {

            document.getElementById("video").play();
            document.getElementById("play").innerHTML ="Play";

            }
            ++count;

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

It may be usefull.

All values in array represent what you want to be (null, undefined or another things) and you search what you want in it.

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1

How to use log levels in java

Those are the levels. You'd consider the severity of the message you're logging, and use the appropriate levels.

It's basically a watermark; the higher the level, the more likely you want to retain the information in the log entry. FINEST would be for messages that are of very little importance, so you'd use it for things you usually don't care about but might want to see in some rare circumstance.

How to convert a String to CharSequence?

Since String IS-A CharSequence, you can pass a String wherever you need a CharSequence, or assign a String to a CharSequence:

CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"

public void foo(CharSequence cs) { 
  System.out.println(cs);
}

If you want to convert a CharSequence to a String, just use the toString method that must be implemented by every concrete implementation of CharSequence.

Hope it helps.

Import mysql DB with XAMPP in command LINE

You may also need to specify the host. From your statement, it looks like you run on Windows. Try this:

mysql -h localhost -u #myusername -p #mypasswd MYBASE
      < c:/user/folderss/myscript.sql

Or

mysql -h localhost -u #myusername -p #mypasswd MYBASE
       < "c:\user\folderss\myscript.sql"

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

Python dictionary : TypeError: unhashable type: 'list'

You can also use defaultdict to address this situation. It goes something like this:

from collections import defaultdict

#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)

for aKey in aSourceDictionary:
    aTargetDictionary[aKey].append(aSourceDictionary[aKey])

PHP $_POST not working?

There is nothing wrong with your code. The problem is not visible form here.

  1. Check if after the submit, the script is called at all.

  2. Have a look at what is submitted: var_dump($_REQUEST)

CSS class for pointer cursor

There is no classes for that. But you can add inline style for your div or other elements like,

<div class="" style="cursor: pointer;">

Is there a pretty print for PHP?

I use this function for debugging:

function pre($pre=true) {
    if($pre) {
        echo "<pre>";
    }
    foreach(func_get_args as $arg) {
        print_r($arg);
        # or, if it pleases you more:
        # var_dump(arg); 
    }
    if($pre) {
        echo "<pre>";
    }

}

This way you don't have to

pre($arrayOne);
pre($arrayTwo);

But in one go:

pre($arrayOne, $arrayTwo); 

Or as many arguments you give it.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

How do you test to see if a double is equal to NaN?

You can check for NaN by using var != var. NaN does not equal NaN.

EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

How do I see which version of Swift I'm using?

By just entering swift command in the terminal, it will show the version, while logging to Swift console.(something like below)

System-IOSs-MacBook-Air:~ system$ swift
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.

Total Number of Row Resultset getRow Method

The getRow() method retrieves the current row number, not the number of rows. So before starting to iterate over the ResultSet, getRow() returns 0.

To get the actual number of rows returned after executing your query, there is no free method: you are supposed to iterate over it.

Yet, if you really need to retrieve the total number of rows before processing them, you can:

  1. ResultSet.last()
  2. ResultSet.getRow() to get the total number of rows
  3. ResultSet.beforeFirst()
  4. Process the ResultSet normally

Open soft keyboard programmatically

perfectly working code to show and hide softkeyboard for edittextbox.....

// code to hide soft keyboard
public void hideSoftKeyBoard(EditText editBox) {
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
     imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);  
}




// code to show soft keyboard
private void showSoftKeyBoard(EditText editBox){
     InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
     editBox.requestFocus();
     inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

how to use javascript Object.defineProperty

Summary:

Object.defineProperty(player, "health", {
    get: function () {
        return 10 + ( player.level * 15 );
    }
});

Object.defineProperty is used in order to make a new property on the player object. Object.defineProperty is a function which is natively present in the JS runtime environemnt and takes the following arguments:

Object.defineProperty(obj, prop, descriptor)

  1. The object on which we want to define a new property
  2. The name of the new property we want to define
  3. descriptor object

The descriptor object is the interesting part. In here we can define the following things:

  1. configurable <boolean>: If true the property descriptor may be changed and the property may be deleted from the object. If configurable is false the descriptor properties which are passed in Object.defineProperty cannot be changed.
  2. Writable <boolean>: If true the property may be overwritten using the assignment operator.
  3. Enumerable <boolean>: If true the property can be iterated over in a for...in loop. Also when using the Object.keys function the key will be present. If the property is false they will not be iterated over using a for..in loop and not show up when using Object.keys.
  4. get <function> : A function which is called whenever is the property is required. Instead of giving the direct value this function is called and the returned value is given as the value of the property
  5. set <function> : A function which is called whenever is the property is assigned. Instead of setting the direct value this function is called and the returned value is used to set the value of the property.

Example:

_x000D_
_x000D_
const player = {_x000D_
  level: 10_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
  configurable: true,_x000D_
  enumerable: false,_x000D_
  get: function() {_x000D_
    console.log('Inside the get function');_x000D_
    return 10 + (player.level * 15);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(player.health);_x000D_
// the get function is called and the return value is returned as a value_x000D_
_x000D_
for (let prop in player) {_x000D_
  console.log(prop);_x000D_
  // only prop is logged here, health is not logged because is not an iterable property._x000D_
  // This is because we set the enumerable to false when defining the property_x000D_
}
_x000D_
_x000D_
_x000D_

How to set tbody height with overflow scroll

In my case I wanted to have responsive table height instead of fixed height in pixels as the other answers are showing. To do that I used percentage of visible height property and overflow on div containing the table:

&__table-container {
  height: 70vh;
  overflow: scroll;
}

This way the table will expand along with the window being resized.

Length of string in bash

Using your example provided

#KISS (Keep it simple stupid)
size=${#myvar}
echo $size

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

First, you should know what an Optional value is. You can step to The Swift Programming Language for detail.

Second, you should know the optional value has two statuses. One is the full value, and the other is a nil value. So before you implement an optional value, you should check which state it is.

You can use if let ... or guard let ... else and so on.

One other way, if you don't want to check the variable state before your implementation, you can also use var buildingName = buildingName ?? "buildingName" instead.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

How can I disable HREF if onclick is executed?

<a href="http://www.google.com" class="ignore-click">Test</a>

with jQuery:

<script>
    $(".ignore-click").click(function(){
        return false;
    })
</script>

with JavaScript

<script>
        for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
            document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
                event.preventDefault();
                return false;
            });
        }
</script>

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored

How can I programmatically get the MAC address of an iphone

It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.

As Apple stated:

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)

Regex in JavaScript for validating decimal numbers

Does this work?

[0-9]{2}.[0-9]{2}

PostgreSQL how to see which queries have run

PostgreSql is very advanced when related to logging techniques

Logs are stored in Installationfolder/data/pg_log folder. While log settings are placed in postgresql.conf file.

Log format is usually set as stderr. But CSV log format is recommended. In order to enable CSV format change in

log_destination = 'stderr,csvlog'   
logging_collector = on

In order to log all queries, very usefull for new installations, set min. execution time for a query

log_min_duration_statement = 0

In order to view active Queries on your database, use

SELECT * FROM pg_stat_activity

To log specific queries set query type

log_statement = 'all'           # none, ddl, mod, all

For more information on Logging queries see PostgreSql Log.