Programs & Examples On #Slf4j

Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction layer for various logging frameworks. Please also include a tag for the actual logging framework you're using if you are attempting to configure logging for your application.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12 artifact id.
Include this in your pom file

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.6</version>
</dependency>

Let me know if error is still not resolved
I also recomend you to see this link

Configuring Log4j Loggers Programmatically

It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).

If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.

public class YourLoggingWrapper {
    private static boolean loggingIsInitialized = false;

    public YourLoggingWrapper() {
        // ...blah
    }

    public static void debug(String debugMsg) {
        log(LogLevel.Debug, debugMsg);
    }

    // Same for all other log levels your want to handle.
    // You mentioned TRACE and ERROR.

    private static void log(LogLevel level, String logMsg) {
        if(!loggingIsInitialized)
            initLogging();

        org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");

        switch(level) {
        case: Debug:
            logger.debug(logMsg);
            break;
        default:
            // whatever
        }
    }

    // log4j logging is lazily constructed; it gets initialized
    // the first time the invoking app calls a log method
    private static void initLogging() {
        loggingIsInitialized = true;

        org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");

        // Now all the same configuration code that @oers suggested applies...
        // configure the logger, configure and add its appenders, etc.
        debugLogger.addAppender(someConfiguredFileAppender);
    }

With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!

Setting log level of message at runtime in slf4j

Based on the answer of massimo virgilio, I've also managed to do it with slf4j-log4j using introspection. HTH.

Logger LOG = LoggerFactory.getLogger(MyOwnClass.class);

org.apache.logging.slf4j.Log4jLogger LOGGER = (org.apache.logging.slf4j.Log4jLogger) LOG;

try {
    Class loggerIntrospected = LOGGER.getClass();
    Field fields[] = loggerIntrospected.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        String fieldName = fields[i].getName();
        if (fieldName.equals("logger")) {
            fields[i].setAccessible(true);
            org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) fields[i].get(LOGGER);
            loggerImpl.setLevel(Level.DEBUG);
        }
    }
} catch (Exception e) {
    System.out.println("ERROR :" + e.getMessage());
}

Mocking Logger and LoggerFactory with PowerMock and Mockito

In answer to your first question, it should be as simple as replacing:

   when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);

with

   when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);

Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,

private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);

is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.

You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

This won't have been OP's problem, but for anyone else who tries everything with no success:

I had similar symptoms. Whenever I built after a mvn clean, it wouldn't find log, or getXYZ(), or builder(), or anything.

[ERROR]   symbol:   variable log
[ERROR]   location: class com.example.MyClass
[ERROR] /Path/To/Some/Java/src/main/com/example/MyClass.java:[30,38] cannot find symbol
[ERROR]   symbol:   method builder()
[ERROR]   location: class com.example.MyClass

After reading every answer I could find about QueryDSL/JPA/Hibernate/Lombok/IntelliJ/Maven issues to no avail, I worked out that the culprit was a single static import of a @Getter method that was annotated on a static field.

Spring 1.15.14.RELEASE, Intellij 2019.1.1

@SpringBootApplication
public class BarApplication implements ApplicationContextAware {
  @Getter
  private static ApplicationContext applicationContext;

  // ... start Spring application, and grab hold of ApplicationContext as it comes past
}
import ...
import static BarApplication.getApplicationContext;

@Slf4j
public class IMakeItAllFail {
   public IMakeItAllFail() {
      log.info("{}", getApplicationContext());
   }
}
@Slf4j
public class Foo {
  Foo() {
    log.info("I fail to compile but I have nothing to do with the other classes!");
  }
}

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

java.lang.ClassNotFoundException: org.apache.log4j.Level

You need to download log4j and add in your classpath.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

In the Websphere case, you have an older version of slf4j-api.jar, 1.4.x. or 1.5.x lying around somewhere. The behavior you observe on tcServer, that is fail-over to NOP, occurs on slf4j versions 1.6.0 and later. Make sure that you are using slf4j-api-1.6.x.jar on all platforms and that no older version of slf4j-api is placed on the class path.

SLF4J: Class path contains multiple SLF4J bindings

I got this issue in a non-maven project, two depended jar each contained a slf4j. I solved by remove one depended jar, compile the project(which of course getting failure) then add the removed one back.

ClassNotFoundException: org.slf4j.LoggerFactory

Add the following JARs to the build path or lib folder of the project:

  1. slf4j-api-1.7.2.jar
  2. slf4j-jdk14-1.7.2.jar

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I am assuming you are using Eclipse as your developing environment.

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

How to get SLF4J "Hello World" working with log4j?

I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:


    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1

    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

I created a reusable function for this. It actually parses an entire directory of requirements files and sets them to extras_require.

Latest always available here: https://gist.github.com/akatrevorjay/293c26fefa24a7b812f5

import glob
import itertools
import os

# This is getting ridiculous
try:
    from pip._internal.req import parse_requirements
    from pip._internal.network.session import PipSession
except ImportError:
    try:
        from pip._internal.req import parse_requirements
        from pip._internal.download import PipSession
    except ImportError:
        from pip.req import parse_requirements
        from pip.download import PipSession


def setup_requirements(
        patterns=[
            'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
        ],
        combine=True):
    """
    Parse a glob of requirements and return a dictionary of setup() options.
    Create a dictionary that holds your options to setup() and update it using this.
    Pass that as kwargs into setup(), viola

    Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
    basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.

    Keep in mind all literally contains `all` packages in your extras.
    This means if you have conflicting packages across your extras, then you're going to have a bad time.
    (don't use all in these cases.)

    If you're running this for a Docker build, set `combine=True`.
    This will set `install_requires` to all distinct reqs combined.

    Example:

    >>> import setuptools
    >>> _conf = dict(
    ...     name='mainline',
    ...     version='0.0.1',
    ...     description='Mainline',
    ...     author='Trevor Joynson <[email protected],io>',
    ...     url='https://trevor.joynson.io',
    ...     namespace_packages=['mainline'],
    ...     packages=setuptools.find_packages(),
    ...     zip_safe=False,
    ...     include_package_data=True,
    ... )
    >>> _conf.update(setup_requirements())
    >>> # setuptools.setup(**_conf)

    :param str pattern: Glob pattern to find requirements files
    :param bool combine: Set True to set install_requires to extras_require['all']
    :return dict: Dictionary of parsed setup() options
    """
    session = PipSession()

    # Handle setuptools insanity
    key_map = {
        'requirements': 'install_requires',
        'install': 'install_requires',
        'tests': 'tests_require',
        'setup': 'setup_requires',
    }
    ret = {v: set() for v in key_map.values()}
    extras = ret['extras_require'] = {}
    all_reqs = set()

    files = [glob.glob(pat) for pat in patterns]
    files = itertools.chain(*files)

    for full_fn in files:
        # Parse
        reqs = {
            str(r.req)
            for r in parse_requirements(full_fn, session=session)
            # Must match env marker, eg:
            #   yarl ; python_version >= '3.0'
            if r.match_markers()
        }
        all_reqs.update(reqs)

        # Add in the right section
        fn = os.path.basename(full_fn)
        barefn, _ = os.path.splitext(fn)
        key = key_map.get(barefn)

        if key:
            ret[key].update(reqs)
            extras[key] = reqs

        extras[barefn] = reqs

    if 'all' not in extras:
        extras['all'] = list(all_reqs)

    if combine:
        extras['install'] = ret['install_requires']
        ret['install_requires'] = list(all_reqs)

    def _listify(dikt):
        ret = {}

        for k, v in dikt.items():
            if isinstance(v, set):
                v = list(v)
            elif isinstance(v, dict):
                v = _listify(v)
            ret[k] = v

        return ret

    ret = _listify(ret)

    return ret


__all__ = ['setup_requirements']

if __name__ == '__main__':
    reqs = setup_requirements()
    print(reqs)

How do I copy to the clipboard in JavaScript?

document.querySelector('#some_your_textfield_id').select();
document.execCommand('copy');

The first line is to select the text that you want to copy.

The second line is to copy the selected text.

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Can't push to the heroku

If your app is a Scala app, it must have a build.sbt in the root directory, and that file must be checked into Git. You can confirm this by running:

$ git ls-files build.sbt

If that file exists and is checked into Git, try running this command:

$ heroku buildpacks:set heroku/scala

VBA Count cells in column containing specified value

one way;

var = count("find me", Range("A1:A100"))

function count(find as string, lookin as range) As Long
   dim cell As Range
   for each cell in lookin
       if (cell.Value = find) then count = count + 1 '//case sens
   next
end function

How to set iPhone UIView z index?

IB and Swift

Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,

views - red view on top

the goal is to move a subview (let's say green) to the top.

views - green view on top

In Interface Builder

In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.

order of views in Interface Builder

Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.

In Swift

There are a couple of different ways to do this programmatically.

Method 1

yellowView.bringSubviewToFront(greenView)
  • This method is the programmatic equivalent of the IB answer above.

  • It only works if the subviews are siblings of each other.

  • An array of the subviews is contained in yellowView.subviews. Here, bringSubviewToFront moves the greenView from index 0 to 2. This can be observed with

      print(yellowView.subviews.indexOf(greenView))
    

Method 2

greenView.layer.zPosition = 1
  • This method just moves the 3D position of the layer higher (closer to the user) on the z-axis. Since the default is 0 for all the other views, the result is that the greenView looks like it is on top. However, it still remains at index 0 of the yellowView.subviews array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.
  • The zPosition could be set to CGFloat.greatestFiniteMagnitude (CGFloat(FLT_MAX) in older versions of Swift) to ensure that it is on top.

Get exception description and stack trace which caused an exception, all as a string

With Python 3, the following code will format an Exception object exactly as would be obtained using traceback.format_exc():

import traceback

try: 
    method_that_can_raise_an_exception(params)
except Exception as ex:
    print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))

The advantage being that only the Exception object is needed (thanks to the recorded __traceback__ attribute), and can therefore be more easily passed as an argument to another function for further processing.

End-line characters from lines read from text file, using Python

You may also consider using line.rstrip() to remove the whitespaces at the end of your line.

Why are empty catch blocks a bad idea?

I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all

So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.

An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

get all keys set in memcached

Base on @mu ? answer here. I've written a cache dump script.

The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.

#!/usr/bin/env bash

echo 'stats items'  \
| nc localhost 11211  \
| grep -oe ':[0-9]*:'  \
| grep -oe '[0-9]*'  \
| sort  \
| uniq  \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'

What it does, it goes through all the cache slabs and print 1000 entries of each.

Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.

imagecreatefromjpeg and similar functions are not working in PHP

For php 7 on Ubuntu:

sudo apt-get install php7.0-gd

Gaussian fit for Python

Actually, you do not need to do a first guess. Simply doing

import matplotlib.pyplot as plt  
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)

P.S.: use numpy.exp() better, says a warning of scipy

How can I view array structure in JavaScript with alert()?

Better use Firebug (chrome console etc) and use console.dir()

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Laravel Soft Delete posts

Updated Version (Version 5.0 & Later):

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model {

    use SoftDeletes;

    protected $table = 'posts';

    // ...
}

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model (Documentation).

For (Version 4.2):

use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required

class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $table = 'posts';

    // ...
}

Prior to Version 4.2 (But not 4.2 & Later)

For example (Using a posts table and Post model):

class Post extends Eloquent {

    protected $table = 'posts';
    protected $softDelete = true;
    
    // ...
}

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

For example (Migration class' up method for posts table) :

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('posts', function(Blueprint $table)
    {
        $table->increments('id');
        // more fields
        $table->softDeletes(); // <-- This will add a deleted_at field
        $table->timeStamps();
    });
}

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:

$model = Contents::find( $id );
$model->delete();

Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.

How would you count occurrences of a string (actually a char) within a string?

string search = "/string";
var occurrences = (regex.Match(search, @"\/")).Count;

This will count each time the program finds "/s" exactly (case sensitive) and the number of occurrences of this will be stored in the variable "occurrences"

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Changing plot scale by a factor in matplotlib

To set the range of the x-axis, you can use set_xlim(left, right), here are the docs

Update:

It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:

ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)

Biggest advantage to using ASP.Net MVC vs web forms

You don't feel bad about using 'non post-back controls' anymore - and figuring how to smush them into a traditional asp.net environment.

This means that modern (free to use) javascript controls such this or this or this can all be used without that trying to fit a round peg in a square hole feel.

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?
});
Response.Write(json);

Pick images of root folder from sub-folder

when you upload your files to the server be careful ,some tomes your images will not appear on the web page and a crashed icon will appear that means your file path is not properly arranged or coded when you have the the following file structure the code should be like this File structure: ->web(main folder) ->images(subfolder)->logo.png(image in the sub folder)the code for the above is below follow this standard

 <img src="../images/logo.jpg" alt="image1" width="50px" height="50px">

if you uploaded your files to the web server by neglecting the file structure with out creating the folder web if you directly upload the files then your images will be broken you can't see images,then change the code as following

 <img src="images/logo.jpg" alt="image1" width="50px" height="50px">

thank you->vamshi krishnan

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I faced the same issue once. I think its because of the URL

String xmlServerURL = "https://example.com/soap/WsRouter";

Check whether its a proper one or not ??

javax.net.ssl.SSLHandshakeException is because the server not able to connect to the specified URL because of following reason-

  • Either the identity of the website is not verified.
  • Server's certificate does not match the URL.
  • Or, Server's certificate is not trusted.

How to add external JS scripts to VueJS Components

This can be simply done like this.

  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }

How to calculate difference between two dates in oracle 11g SQL

There is no DATEDIFF() function in Oracle. On Oracle, it is an arithmetic issue

select DATE1-DATE2 from table 

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

edit the init.py file in your project origin directory

import pymysql

pymysql.install_as_MySQLdb()

How to close a thread from within?

A little late, but I use a _is_running variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.

def stop(self):
  self._is_running = False

And in run() just loop on while(self._is_running)

Opening the Settings app from another app

Swift 3:

guard let url = URL(string: UIApplicationOpenSettingsURLString) else {return}
if #available(iOS 10.0, *) {
  UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
  // Fallback on earlier versions
  UIApplication.shared.openURL(url)
}

Animate text change in UILabel

Swift 4.2 version of SwiftArchitect's solution above (works great):

    // Usage: insert view.fadeTransition right before changing content    

extension UIView {

        func fadeTransition(_ duration:CFTimeInterval) {
            let animation = CATransition()
            animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            animation.type = CATransitionType.fade
            animation.duration = duration
            layer.add(animation, forKey: CATransitionType.fade.rawValue)
        }
    }

Invocation:

    // This will fade

aLabel.fadeTransition(0.4)
aLabel.text = "text"

How can I delete all Git branches which have been merged?

You'll want to exclude the master, main & develop branches from those commands.

Local git clear:

git branch --merged | grep -v '\*\|master\|main\|develop' | xargs -n 1 git branch -d

Remote git clear:

git branch -r --merged | grep -v '\*\|master\|main\|develop' | sed 's/origin\///' | xargs -n 1 git push --delete origin

Sync local registry of remote branches:

git fetch -p

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

You haven't accepted an answer, so here's what worked for me in PuTTY:

enter image description here

Without allowing username changes, i got this question's subject as error on the gateway machine.

Ignoring NaNs with str.contains

import folium
import pandas

data= pandas.read_csv("maps.txt")

lat = list(data["latitude"])
lon = list(data["longitude"])

map= folium.Map(location=[31.5204, 74.3587], zoom_start=6, tiles="Mapbox Bright")

fg = folium.FeatureGroup(name="My Map")

for lt, ln in zip(lat, lon):
c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))

child = fg.add_child(folium.Marker(location=[31.5204, 74.5387], popup="Welcome to Lahore", icon= folium.Icon(color='green')))

map.add_child(fg)

map.save("Lahore.html")


Traceback (most recent call last):
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\check2.py", line 14, in <module>
    c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\map.py", line 647, in __init__
    self.location = _validate_coordinates(location)
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\utilities.py", line 48, in _validate_coordinates
    'got:\n{!r}'.format(coordinates))
ValueError: Location values cannot contain NaNs, got:
[nan, nan]

Installing a specific version of angular with angular cli

use the following command to install the specific version. say you want to install angular/cli version 1.6.8 then enter the following command :

sudo npm install -g @angular/[email protected]

this will install angular/cli version 1.6.8

If isset $_POST

You can try,

 <?php

     if (isset($_POST["mail"])) {
            echo "Yes, mail is set";    
        }else{  
            echo "N0, mail is not set";
        }
  ?>

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

Oracle DateTime in Where Clause?

You could also do:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = DATE '2011-01-26'

How to use unicode characters in Windows command line?

As I haven't seen any full answers for Python 2.7, I'll outline the two important steps and an optional step that is quite useful.

  1. You need a font with Unicode support. Windows comes with Lucida Console which may be selected by right-clicking the title bar of command prompt and clicking the Defaults option. This also gives access to colours. Note that you can also change settings for command windows invoked in certain ways (e.g, open here, Visual Studio) by choosing Properties instead.
  2. You need to set the code page to cp65001, which appears to be Microsoft's attempt to offer UTF-7 and UTF-8 support to command prompt. Do this by running chcp 65001 in command prompt. Once set, it remains this way until the window is closed. You'll need to redo this every time you launch cmd.exe.

For a more permanent solution, refer to this answer on Super User. In short, create a REG_SZ (String) entry using regedit at HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor and name it AutoRun. Change the value of it to chcp 65001. If you don't want to see the output message from the command, use @chcp 65001>nul instead.

Some programs have trouble interacting with this encoding, MinGW being a notable one that fails while compiling with a nonsensical error message. Nonetheless, this works very well and doesn't cause bugs with the majority of programs.

In Python, what does dict.pop(a,b) mean?

So many questions here. I see at least two, maybe three:

  • What does pop(a,b) do?/Why are there a second argument?
  • What is *args being used for?

The first question is trivially answered in the Python Standard Library reference:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.


The second question is covered in the Python Language Reference:

If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

In other words, the pop function takes at least two arguments. The first two get assigned the names self and key; and the rest are stuffed into a tuple called args.

What's happening on the next line when *args is passed along in the call to self.data.pop is the inverse of this - the tuple *args is expanded to of positional parameters which get passed along. This is explained in the Python Language Reference:

If the syntax *expression appears in the function call, expression must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments

In short, a.pop() wants to be flexible and accept any number of positional parameters, so that it can pass this unknown number of positional parameters on to self.data.pop().

This gives you flexibility; data happens to be a dict right now, and so self.data.pop() takes either one or two parameters; but if you changed data to be a type which took 19 parameters for a call to self.data.pop() you wouldn't have to change class a at all. You'd still have to change any code that called a.pop() to pass the required 19 parameters though.

Using Mockito with multiple calls to the same method with the same arguments

BDD style:

import static org.mockito.BDDMockito.given;
        ...

        given(yourMock.yourMethod()).willReturn(1, 2, 3);

Classic style:

import static org.mockito.Mockito.when;
        ...

        when(yourMock.yourMethod()).thenReturn(1, 2, 3);

Android check internet connection

All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

Network Call from async Task

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

Actual Class which will ping to server

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

Default string initialization: NULL or Empty?

According to MSDN:

By initializing strings with the Empty value instead of null, you can reduce the chances of a NullReferenceException occurring.

Always using IsNullOrEmpty() is good practice nevertheless.

Oracle: SQL query that returns rows with only numeric values

You can use following command -

LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))

This will return NULL if your string1 is Numeric

your query would be -

select * from tablename 
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

What is the difference between statically typed and dynamically typed languages?

Compiled vs. Interpreted

"When source code is translated"

  • Source Code: Original code (usually typed by a human into a computer)
  • Translation: Converting source code into something a computer can read (i.e. machine code)
  • Run-Time: Period when program is executing commands (after compilation, if compiled)
  • Compiled Language: Code translated before run-time
  • Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.


Python Example

Dynamic, Interpreted

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.


Go Example

Static, Compiled

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.


Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.


More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

num = 2
num = '3' // ERROR

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Rewrite the query into this

SELECT st1.*, st2.relevant_field FROM sometable st1
INNER JOIN sometable st2 ON (st1.relevant_field = st2.relevant_field)
GROUP BY st1.id  /* list a unique sometable field here*/
HAVING COUNT(*) > 1

I think st2.relevant_field must be in the select, because otherwise the having clause will give an error, but I'm not 100% sure

Never use IN with a subquery; this is notoriously slow.
Only ever use IN with a fixed list of values.

More tips

  1. If you want to make queries faster, don't do a SELECT * only select the fields that you really need.
  2. Make sure you have an index on relevant_field to speed up the equi-join.
  3. Make sure to group by on the primary key.
  4. If you are on InnoDB and you only select indexed fields (and things are not too complex) than MySQL will resolve your query using only the indexes, speeding things way up.

General solution for 90% of your IN (select queries

Use this code

SELECT * FROM sometable a WHERE EXISTS (
  SELECT 1 FROM sometable b
  WHERE a.relevant_field = b.relevant_field
  GROUP BY b.relevant_field
  HAVING count(*) > 1) 

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

What is the difference between Google App Engine and Google Compute Engine?

Google Compute Engine (GCE)

Virtual Machines (VMs) hosted in the cloud. Before the cloud, these were often called Virtual Private Servers (VPS). You'd use these the same way you'd use a physical server, where you install and configure the operating system, install your application, install the database, keep the OS up-to-date, etc. This is known as Infrastructure-as-a-Service (IaaS).

VMs are most useful when you have an existing application running on a VM or server in your datacenter, and want to easily migrate it to GCP.

Google App Engine

App Engine hosts and runs your code, without requiring you to deal with the operating system, networking, and many of the other things you'd have to manage with a physical server or VM. Think of it as a runtime, which can automatically deploy, version, and scale your application. This is called Platform-as-a-Service (PaaS).

App Engine is most useful when you want automated deployment and automated scaling of your application. Unless your application requires custom OS configuration, App Engine is often advantageous over configuring and managing VMs by hand.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

What is the minimum length of a valid international phone number?

As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:

  • For Israel: The minimum phone number length (excluding the country code) is 8 digits. - Official Source (Country Code 972)
  • For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)

  • For Solomon Islands its 5 for fixed line phones. - Source (country code 677)

... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.

Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:

String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
    boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
    if (isValid) {
        // Actions to perform if the number is valid
    } else {
        // Do necessary actions if its not valid 
    }
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse function instead of passing null.

JQuery, setTimeout not working

SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.

How to make a <ul> display in a horizontal row

As others have mentioned, you can set the li to display:inline;, or float the li left or right. Additionally, you can also use display:flex; on the ul. In the snippet below I also added justify-content:space-around to give it more spacing.

For more information on flexbox, checkout this complete guide.

_x000D_
_x000D_
#div_top_hypers {_x000D_
    background-color:#eeeeee;_x000D_
    display:inline;      _x000D_
}_x000D_
#ul_top_hypers {_x000D_
    display: flex;_x000D_
    justify-content:space-around;_x000D_
    list-style-type:none;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
    <ul id="ul_top_hypers">_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
        <li>&#8227; <a href="" class="a_top_hypers"> logout</a></li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Working with SQL views in Entity Framework Core

The EF Core doesn't create DBset for the SQL views automatically in the context calss, we can add them manually as below.

public partial class LocalDBContext : DbContext
{ 

    public LocalDBContext(DbContextOptions<LocalDBContext> options) : base(options)
    {

    }

    public virtual DbSet<YourView> YourView { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourView>(entity => {
            entity.HasKey(e => e.ID);
            entity.ToTable("YourView");
            entity.Property(e => e.Name).HasMaxLength(50);
        });
    }

}

The sample view is defined as below with few properties

using System;
using System.Collections.Generic;

namespace Project.Entities
{
    public partial class YourView
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
}

After adding a class for the view and DB set in the context class, you are good to use the view object through your context object in the controller.

nodeJs callbacks simple example

A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.

The simplest example I can think of in JavaScript is the setTimeout() function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);

You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);

Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs library to read a file. The fs module exposes two unique API functions: readFile and readFileSync.

The readFile function is asynchronous while readFileSync is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile and readFileSync instead of readFile and readFileAsync. Here is an example of using both functions.

Synchronous:

var data = fs.readFileSync('test.txt');
console.log(data);

The code above blocks thread execution until all the contents of test.txt are read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.

Asynchronous (with callback):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);

First we create a callback function that accepts two arguments err and data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err has a value before you do anything else. If so, stop execution of the callback and log the error.

Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch block.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}

In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.

In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.

How to do one-liner if else statement?

You can use a closure for this:

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, func() { dothis() }, func() { dothat() })
}

The only gripe I have with the closure syntax in Go is there is no alias for the default zero parameter zero return function, then it would be much nicer (think like how you declare map, array and slice literals with just a type name).

Or even the shorter version, as a commenter just suggested:

func doif(b bool, f1, f2 func()) {
    switch{
    case b:
        f1()
    case !b:   
        f2()
    }
}

func dothis() { fmt.Println("Condition is true") }

func dothat() { fmt.Println("Condition is false") }

func main () {
    condition := true
    doif(condition, dothis, dothat)
}

You would still need to use a closure if you needed to give parameters to the functions. This could be obviated in the case of passing methods rather than just functions I think, where the parameters are the struct associated with the methods.

How can I add "href" attribute to a link dynamically using JavaScript?

I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).

To add any attribute, just use the setAttribute method on the DOM object:

a = document.getElementById(...);
a.setAttribute("href", "somelink url");

Read specific columns from a csv file with csv module?

import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('file.txt') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value 
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

print(columns['name'])
print(columns['phone'])
print(columns['street'])

With a file like

name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.

Will output

>>> 
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']

Or alternatively if you want numerical indexing for the columns:

with open('file.txt') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
print(columns[0])

>>> 
['Bob', 'James', 'Smithers']

To change the deliminator add delimiter=" " to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can analyze the core dump file using the "gdb" command.

 gdb - The GNU Debugger

 syntax:

 # gdb executable-file core-file

 example: # gdb out.txt core.xxx 

Extracting the last n characters from a string in R

Use stri_sub function from stringi package. To get substring from the end, use negative numbers. Look below for the examples:

stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"

You can install this package from github: https://github.com/Rexamine/stringi

It is available on CRAN now, simply type

install.packages("stringi")

to install this package.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

CSS rounded corners in IE8

http://fetchak.com/ie-css3/ works for IE 6+. Use this if css3pie doesn't work for you.

Permutations between two lists of unequal length

I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.

import itertools
itertools.combinations(list, n_times)

Here as an excerpt from the Python docs on itertools That might help you find what your looking for.

Combinatoric generators:

Iterator                                 | Results
-----------------------------------------+----------------------------------------
product(p, q, ... [repeat=1])            | cartesian product, equivalent to a 
                                         |   nested for-loop
-----------------------------------------+----------------------------------------
permutations(p[, r])                     | r-length tuples, all possible 
                                         |   orderings, no repeated elements
-----------------------------------------+----------------------------------------
combinations(p, r)                       | r-length tuples, in sorted order, no 
                                         |   repeated elements
-----------------------------------------+----------------------------------------
combinations_with_replacement(p, r)      | r-length tuples, in sorted order, 
                                         | with repeated elements
-----------------------------------------+----------------------------------------
product('ABCD', repeat=2)                | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)                  | AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)                  | AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD

How to parse Excel (XLS) file in Javascript/HTML5

Old question, but I should note that the general task of parsing XLS files from javascript is tedious and difficult but not impossible.

I have basic parsers implemented in pure JS:

Both pages are HTML5 File API-driven XLS/XLSX parsers (you can drag-drop your file and it will print out the data in the cells in a comma-separated list). You can also generate JSON objects (assuming the first row is a header row).

The test suite http://oss.sheetjs.com/ shows a version that uses XHR to get and parse files.

How do you define a class of constants in Java?

enums are fine. IIRC, one item in effective Java (2nd Ed) has enum constants enumerating standard options implementing a [Java keyword] interface for any value.

My preference is to use a [Java keyword] interface over a final class for constants. You implicitly get the public static final. Some people will argue that an interface allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.

Which looks better?

public final class SomeStuff {
     private SomeStuff() {
         throw new Error();
     }
     public static final String SOME_CONST = "Some value or another, I don't know.";
}

Or:

public interface SomeStuff {
     String SOME_CONST = "Some value or another, I don't know.";
}

Facebook Callback appends '#_=_' to Return URL

For PHP SDK users

I fixed the problem simply by removing the extra part before forwarding.

 $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);
 $loginURL = str_replace("#_=_", "", $loginURL);
 header("Location: " . $loginURL);

Getting the name of a variable as a string

>> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
>> my_var_name 
'my_var'

In case you get an error if myvar points to another variable, try this (suggested by @mherzog)-

 >> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v is my_var][0]
>> my_var_name 
'my_var'

locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You tried to do a.setText(a1). a1 is an int value, but setText() requires a string value. For this reason you need use String.valueOf(a1) to pass the value of a1 as a String and not as an int to a.setText(), like so:

a.setText(String.valueOf(a1))

that was the exact solution to the problem with my case.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Magento How to debug blank white screen

As you said - there is one stand alone answer to this issue.

I had same issue after changing theme. Memory was set to 1024 before, so that's not the problem. Cache was cleared and there was nothing useful in error log.

In my case solution was different - old theme had custom homepage template... Switching it to standard one fixed it.

How to 'update' or 'overwrite' a python list

You may try this

alist[0] = 2014

but if you are not sure about the position of 123 then you may try like this:

for idx, item in enumerate(alist):
   if 123 in item:
       alist[idx] = 2014

Best way to access a control on another form in Windows Forms?

@Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right?

You have my sympathy! ;)


@Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates many child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :)

'ls' is not recognized as an internal or external command, operable program or batch file

If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.

PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.

The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Best way to check if MySQL results returned in PHP?

One way to do it is to check what mysql_num_rows returns. A minimal complete example would be the following:

if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
    // there are results in $result
} else {
    // no results
}

But it's recommended that you check the return value of mysql_query and handle it properly in the case it's false (which would be caused by an error); probably by also calling mysql_error and logging the error somewhere.

outline on only one border

I know this is old. But yeah. I prefer much shorter solution, than Giona answer

[contenteditable] {
    border-bottom: 1px solid transparent;
    &:focus {outline: none; border-bottom: 1px dashed #000;}
}

Reset select2 value and show placeholder

For users loading remote data, this will reset the select2 to the placeholder without firing off ajax. Works with v4.0.3:

$("#lstProducts").val("").trigger("change.select2");

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

SQL 'LIKE' query using '%' where the search criteria contains '%'

You need to escape it: on many databases this is done by preceding it with backslash, \%.

So abc becomes abc\%.

Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

How to add a class to a given element?

To add, remove or check element classes in a simple way:

var uclass = {
    exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
    add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
    remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/  /g,' ');elem.className = c;}
};

var elem = document.getElementById('someElem');
//Add a class, only if not exists yet.
uclass.add(elem,'someClass');
//Remove class
uclass.remove(elem,'someClass');

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

How to update column with null value

Use IS instead of = This will solve your problem example syntax:

UPDATE studentdetails
SET contactnumber = 9098979690
WHERE contactnumber IS NULL;

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

How to prompt for user input and read command-line arguments

If you are running Python <2.7, you need optparse, which as the doc explains will create an interface to the command line arguments that are called when your application is run.

However, in Python =2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs...

The following code is a Python program that takes a list of integers and produces either the sum or the max:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

Why is Spring's ApplicationContext.getBean considered bad?

There is another time when using getBean makes sense. If you're reconfiguring a system that already exists, where the dependencies are not explicitly called out in spring context files. You can start the process by putting in calls to getBean, so that you don't have to wire it all up at once. This way you can slowly build up your spring configuration putting each piece in place over time and getting the bits lined up properly. The calls to getBean will eventually be replaced, but as you understand the structure of the code, or lack there of, you can start the process of wiring more and more beans and using fewer and fewer calls to getBean.

How to implement the --verbose or -v option into a script?

What I do in my scripts is check at runtime if the 'verbose' option is set, and then set my logging level to debug. If it's not set, I set it to info. This way you don't have 'if verbose' checks all over your code.

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

Using cut command to remove multiple columns

Sometimes it's easier to think in terms of which fields to exclude.

If the number of fields not being cut (not being retained in the output) is small, it may be easier to use the --complement flag, e.g. to include all fields 1-20 except not 3, 7, and 12 -- do this:

cut -d, --complement -f3,7,12 <inputfile

Rather than

cut -d, -f-2,4-6,8-11,13-

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Cell spacing in UICollectionView

Try playing around with this method:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout*)collectionViewLayout
    insetForSectionAtIndex:(NSInteger)section {

    UIEdgeInsets insets = UIEdgeInsetsMake(?, ?, ?, ?);

    return insets;
}

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to make a phone call programmatically?

If anyone is looking for in Kotlin

    val  uri = "tel:+800******"
    val call_customer_service = Intent(Intent.ACTION_CALL)
    call_customer_service.setData(Uri.parse(uri))
    startActivity(call_customer_service)

Like some other solutions it requires android.permission.CALL_PHONE permission.

How to sort an array of objects with jquery or javascript

var array = [[1, "grape", 42], [2, "fruit", 9]];

array.sort(function(a, b)
{
    // a and b will here be two objects from the array
    // thus a[1] and b[1] will equal the names

    // if they are equal, return 0 (no sorting)
    if (a[1] == b[1]) { return 0; }
    if (a[1] > b[1])
    {
        // if a should come after b, return 1
        return 1;
    }
    else
    {
        // if b should come after a, return -1
        return -1;
    }
});

The sort function takes an additional argument, a function that takes two arguments. This function should return -1, 0 or 1 depending on which of the two arguments should come first in the sorting. More info.

I also fixed a syntax error in your multidimensional array.

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Oracle PL/SQL : remove "space characters" from a string

To replace one or more white space characters by a single blank you should use {2,} instead of *, otherwise you would insert a blank between all non-blank characters.

REGEXP_REPLACE( my_value, '[[:space:]]{2,}', ' ' )

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

How do I get the current timezone name in Postgres 9.3?

See this answer: Source

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source

This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.

It seems to have the System's timezone to be set is possible indeed.

Get the OS local time zone from the shell. In psql:

=> \! date +%Z

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

cursor.fetchall() vs list(cursor) in Python

A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor is that list(cursor) will always give you a list, while cursor.fetchall() gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.

Given the above, I suggest always favouring list(cursor) over cursor.fetchall(), to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.

What is the best open source help ticket system?

Howabout Bugzilla. Open source and what Mozilla uses.

Node JS Promise.all and forEach

Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.

/**
 * 
 * @param items An array of items.
 * @param fn A function that accepts an item from the array and returns a promise.
 * @returns {Promise}
 */
function forEachPromise(items, fn) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item);
        });
    }, Promise.resolve());
}

And use it like this:

var items = ['a', 'b', 'c'];

function logItem(item) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            resolve();
        })
    });
}

forEachPromise(items, logItem).then(() => {
    console.log('done');
});

We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.

function forEachPromise(items, fn, context) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item, context);
        });
    }, Promise.resolve());
}

Your promise function would look like this:

function logItem(item, context) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            context.itemCount++;
            resolve();
        })
    });
}

Finding the number of days between two dates

    // Change this to the day in the future
$day = 15;

// Change this to the month in the future
$month = 11;

// Change this to the year in the future
$year = 2012;

// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);

echo "There are $days days until $day/$month/$year";

How to add a JAR in NetBeans

Project Files Services Tabls

go files tabs

drag drop file to libs files hover.

return project tabs and what are you see :)

Fastest way to find second (third...) highest/lowest value in vector or column

Here is an easy way to find the indices of N smallest/largest values in a vector(Example for N = 3):

N <- 3

N Smallest:

ndx <- order(x)[1:N]

N Largest:

ndx <- order(x, decreasing = T)[1:N]

So you can extract the values as:

x[ndx]

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I ran into this problem on NetBeans when working with a ready-made project from this Murach JSP book. The problem was caused by using the 5.1.23 Connector J with a MySQL 8.0.13 Database. I needed to replace the old driver with a new one. After downloading the Connector J, this took three steps.

How to replace NetBeans project Connector J:

  1. Download the current Connector J from here. Then copy it in your OS.

  2. In NetBeans, click on the Files tab which is next to the Projects tab. Find the mysql-connector-java-5.1.23.jar or whatever old connector you have. Delete this old connector. Paste in the new Connector.

  3. Click on the Projects tab. Navigate to the Libraries folder. Delete the old mysql connector. Right click on the Libraries folder. Select Add Jar / Folder. Navigate to the location where you put the new connector, and select open.

  4. In the Project tab, right click on the project. Select Resolve Data Sources on the bottom of the popup menu. Click on Add Connection. At this point NetBeans skips forward and assumes you want to use the old connector. Click the Back button to get back to the skipped window. Remove the old connector, and add the new connector. Click Next and Test Connection to make sure it works.

For video reference, I found this to be useful. For IntelliJ IDEA, I found this to be useful.

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

Xcode - ld: library not found for -lPods

This was my issue while trying to integrate Firebase to my Xcode project using cocoapods

library not found for -lGoogleToolboxForMac
linker command failed with exit code 1 (use -v to see invocation)

After hours of searching and trying out various fixes listed in the stackoverflow, my issue was finally fixed doing following steps

  1. Go to Build Settings, search for Other Linker Flags, remove all values expect $(inherited) Image

Do this for all targets.

  1. Delete the pods folder. (ios/Pods)
  2. Do pod update

Voila! All linker errors will be gone.

Unix command-line JSON parser?

I just made jkid which is a small command-line json explorer that I made to easily explore big json objects. Objects can be explored "transversally" and a "preview" option is there to avoid console overflow.

$  echo '{"john":{"size":20, "eyes":"green"}, "bob":{"size":30, "eyes":"brown"}}' > test3.json
$  jkid . eyes test3.json 
object[.]["eyes"]
{
  "bob": "brown", 
  "john": "green"
}

Nested Git repositories?

Just for completeness:

There is another solution, I would recommend: subtree merging.

In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.

$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`

Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:

$ git pull -s subtree OtherRepository master

I'm using this method for years now, it works :-)

More about this way including comparing it with sub modules may be found in this git howto doc.

Specify path to node_modules in package.json

I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

I found the following workaround:

  1. Copy the package.json file to a temp folder on a different filesystem
  2. Run npm install there
  3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

Other options

There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

  • $ mkdir /home/dan/myproject && cd /home/dan/myproject
  • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
  • $ npm install
  • $ cd /media/sf_shared/myproject
  • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib

Handling InterruptedException in Java

I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Delete all data rows from an Excel table (apart from the first)

I suggest first clearcontents, then resize Table:

Sub DeleteTableRows(ByRef Table As ListObject)

     Dim R               As Range

On Error Resume Next

    Table.DataBodyRange.ClearContents
    Set R = Table.Range.Rows(1).Resize(2)
    Table.Resize R

On Error GoTo 0

End Sub

how to open an URL in Swift3

If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.

import UIKit
import SafariServices

let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I fixed it by add a property to renderSeparator Component,the code is here:

_renderSeparator(sectionID,rowID){
    return (
        <View style={styles.separatorLine} key={"sectionID_"+sectionID+"_rowID_"+rowID}></View>
    );
}

The key words of this warning is "unique", sectionID + rowID return a unique value in ListView.

Write single CSV file using spark-csv

spark's df.write() API will create multiple part files inside given path ... to force spark write only a single part file use df.coalesce(1).write.csv(...) instead of df.repartition(1).write.csv(...) as coalesce is a narrow transformation whereas repartition is a wide transformation see Spark - repartition() vs coalesce()

df.coalesce(1).write.csv(filepath,header=True) 

will create folder in given filepath with one part-0001-...-c000.csv file use

cat filepath/part-0001-...-c000.csv > filename_you_want.csv 

to have a user friendly filename

Does Python have an ordered set?

As other answers mention, as for python 3.7+, the dict is ordered by definition. Instead of subclassing OrderedDict we can subclass abc.collections.MutableSet or typing.MutableSet using the dict's keys to store our values.

class OrderedSet(typing.MutableSet[T]):
    """A set that preserves insertion order by internally using a dict."""

    def __init__(self, iterable: t.Iterator[T]):
        self._d = dict.fromkeys(iterable)

    def add(self, x: T) -> None:
        self._d[x] = None

    def discard(self, x: T) -> None:
        self._d.pop(x)

    def __contains__(self, x: object) -> bool:
        return self._d.__contains__(x)

    def __len__(self) -> int:
        return self._d.__len__()

    def __iter__(self) -> t.Iterator[T]:
        return self._d.__iter__()

Then just:

x = OrderedSet([1, 2, -1, "bar"])
x.add(0)
assert list(x) == [1, 2, -1, "bar", 0]

I put this code in a small library, so anyone can just pip install it.

Angular-Material DateTime Picker Component?

Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648

Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

Python 3 does not allow deletion while iterating (using for loop above) dictionary. There are various alternatives to do; one simple way is the to change following line

for i in x.keys():

With

for i in list(x)

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

How to convert DateTime? to DateTime

You can use a simple cast:

DateTime dtValue = (DateTime) dtNullAbleSource;

As Leandro Tupone said, you have to check if the var is null before

Find by key deep in a nested array

I found this page through googling for the similar functionalities. Based on the work provided by Zach and regularmike, I created another version which suits my needs.
BTW, teriffic work Zah and regularmike! I'll post the code here:

function findObjects(obj, targetProp, targetValue, finalResults) {

  function getObject(theObject) {
    let result = null;
    if (theObject instanceof Array) {
      for (let i = 0; i < theObject.length; i++) {
        getObject(theObject[i]);
      }
    }
    else {
      for (let prop in theObject) {
        if(theObject.hasOwnProperty(prop)){
          console.log(prop + ': ' + theObject[prop]);
          if (prop === targetProp) {
            console.log('--found id');
            if (theObject[prop] === targetValue) {
              console.log('----found porop', prop, ', ', theObject[prop]);
              finalResults.push(theObject);
            }
          }
          if (theObject[prop] instanceof Object || theObject[prop] instanceof Array){
            getObject(theObject[prop]);
          }
        }
      }
    }
  }

  getObject(obj);

}

What it does is it find any object inside of obj with property name and value matching to targetProp and targetValue and will push it to the finalResults array. And Here's the jsfiddle to play around: https://jsfiddle.net/alexQch/5u6q2ybc/

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

In case someone doesn't fix the problem use methods above. I fixed mine by surrounding the async func by an arrow function. As in:

describe("Profile Tab Exists and Clickable: /settings/user", () => {
    test(`Assert that you can click the profile tab`, (() => {
      async () => {
        await page.waitForSelector(PROFILE.TAB)
        await page.click(PROFILE.TAB)
      }
    })(), 30000);
});

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

Int to Decimal Conversion - Insert decimal point at specified location

Simple math.

double result = ((double)number) / 100.0;

Although you may want to use decimal rather than double: decimal vs double! - Which one should I use and when?

Position a div container on the right side

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

How to concatenate two numbers in javascript?

You can now make use of ES6 template literals.

const numbersAsString = `${5}${6}`;
console.log(numbersAsString); // Outputs 56

Or, if you have variables:

const someNumber = 5;
const someOtherNumber = 6;
const numbersAsString = `${someNumber}${someOtherNumber}`;

console.log(numbersAsString); // Outputs 56

Personally I find the new syntax much clearer, albeit slightly more verbose.

Cast IList to List

How about this:

List<SubProduct> subProducts = Model.subproduct.ToList();

Parsing json and searching through it

Seems there's a typo (missing colon) in the JSON dict provided by jro.

The correct syntax would be:

jdata = json.load('{"uri": "http:", "foo": "bar"}')

This cleared it up for me when playing with the code.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Convert Variable Name to String?

Does Django not do this when generating field names?

http://docs.djangoproject.com/en/dev//topics/db/models/#verbose-field-names

Seems reasonable to me.

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

How much faster is C++ than C#?

C++ (or C for that matter) gives you fine-grained control over your data structures. If you want to bit-twiddle you have that option. Large managed Java or .NET apps (OWB, Visual Studio 2005) that use the internal data structures of the Java/.NET libraries carry the baggage with them. I've seen OWB designer sessions using over 400 MB of RAM and BIDS for cube or ETL design getting into the 100's of MB as well.

On a predictable workload (such as most benchmarks that repeat a process many times) a JIT can get you code that is optimised well enough that there is no practical difference.

IMO on large applications the difference is not so much the JIT as the data structures that the code itself is using. Where an application is memory-heavy you will get less efficient cache usage. Cache misses on modern CPUs are quite expensive. Where C or C++ really win is where you can optimise your usage of data structures to play nicely with the CPU cache.

System.Timers.Timer vs System.Threading.Timer

I found a short comparison from MSDN

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

When to use std::size_t?

Soon most computers will be 64-bit architectures with 64-bit OS:es running programs operating on containers of billions of elements. Then you must use size_t instead of int as loop index, otherwise your index will wrap around at the 2^32:th element, on both 32- and 64-bit systems.

Prepare for the future!

How to determine the version of the C++ standard used by the compiler?

From the Bjarne Stroustrup C++0x FAQ:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.

These are the C++ standards and what value you should be able to expect in __cplusplus:

  • C++ pre-C++98: __cplusplus is 1.
  • C++98: __cplusplus is 199711L.
  • C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
  • C++11: __cplusplus is 201103L.
  • C++14: __cplusplus is 201402L.
  • C++17: __cplusplus is 201703L.

If the compiler might be an older gcc, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.

The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).

Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

How can I shrink the drawable on a button?

Buttons do not resize their inner images.

My solution does not require code manipulation.

It uses a layout with TextView and ImageView.

The background of the layout should have the red 3d drawable.

You may need to define the android:scaleType xml attribute.

Example:

<LinearLayout
    android:id="@+id/list_item"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:padding="2dp" >

    <ImageView
        android:layout_width="50dp"
        android:layout_height="fill_parent"
        android:src="@drawable/camera" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:lines="1"
        android:gravity="center_vertical"
        android:text="Hello - primary" />

</LinearLayout>

BTW:

  1. Counting on different resolution icons may result in a non predictable UI (icon too big or too small)
  2. Text in textview (including in buttons) does not fill the component. This is an Android problem and I don't know how to solve it.
  3. You can use it as an include.

Good luck

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

Finding an elements XPath using IE Developer tool

This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62

Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?

Is it possible to get a list of files under a directory of a website? How?

Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Cast Double to Integer in Java

Double and Integer are wrapper classes for Java primitives for double and int respectively. You can cast between those, but you will lose the floating point. That is, 5.4 casted to an int will be 5. If you cast it back, it will be 5.0.

Using WGET to run a cronjob PHP

you can just use this code to hit the script using cron job using cpanel:

wget https://www.example.co.uk/unique-code

What is Unicode, UTF-8, UTF-16?

ASCII - Software allocates only 8 bit byte in memory for a given character. It works well for English & adopted (loanwords like façade) characters as their corresponding decimal values falls below 128 in the decimal value. Example C program.

UTF-8 - Software allocates 1 to 4 variable 8 bit bytes for a given character. What does mean by variable here? Let us say you are sending the character 'A' through your HTML pages in the browser (HTML is UTF-8), the corresponding decimal value of A is 65, when you convert it into decimal it becomes 01000010. This requires only 1 bytes, 1 byte memory is allocated even for special adopted English characters like 'ç' in a word façade. However, when you want to store European characters, it requires 2 bytes, so you need UTF-8. However, when you go for Asian characters, you require minimum of 2 bytes and maximum of 4 bytes. Similarly, Emoji's require 3 to 4 bytes. UTF-8 will solve all your needs.

UTF-16 will allocate minimum 2 bytes and maximum of 4 bytes per character, it will not allocate 1 or 3 bytes. Each character is either represented in 16 bit or 32 bit.

Then why exists UTF-16? Originally, Unicode was 16 bit not 8 bit. Java adopted the original version of UTF-16.

In a nutshell, you don't need UTF-16 anywhere unless it has been already been adopted by the language or platform you are working on.

Java program invoked by web browsers uses UTF-16 but the web browser sends characters using UTF-8.

Variable number of arguments in C++?

// spawn: allocate and initialize (a simple function)
template<typename T>
T * spawn(size_t n, ...){
  T * arr = new T[n];
  va_list ap;
  va_start(ap, n);
  for (size_t i = 0; i < n; i++)
    T[i] = va_arg(ap,T);
  return arr;
}

User writes:

auto arr = spawn<float> (3, 0.1,0.2,0.3);

Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.

Copy a git repo without history

Isn't this exactly what squashing a rebase does? Just squash everything except the last commit and then (force) push it.

Basic calculator in Java

Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:

if (operation == "+");
                     ^

Also use .equals for Strings, == compares Object references:

 if (operation.equals("+")) {

Getting time elapsed in Objective-C

Use the timeIntervalSinceDate method

NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];

NSTimeInterval is just a double, define in NSDate like this:

typedef double NSTimeInterval;

How can I query a value in SQL Server XML column

select
  Roles
from
  MyTable
where
  Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'

In case your column is not XML, you need to convert it. You can also use other syntax to query certain attributes of your XML data. Here is an example...

Let's suppose that data column has this:

<Utilities.CodeSystems.CodeSystemCodes iid="107" CodeSystem="2" Code="0001F" CodeTags="-19-"..../>

... and you only want the ones where CodeSystem = 2 then your query will be:

select 
  [data] 
from
  [dbo].[CodeSystemCodes_data]
  
where
  CAST([data] as XML).value('(/Utilities.CodeSystems.CodeSystemCodes/@CodeSystem)[1]', 'varchar(max)') = '2'

These pages will show you more about how to query XML in T-SQL:

Querying XML fields using t-sql

Flattening XML Data in SQL Server

EDIT

After playing with it a little bit more, I ended up with this amazing query that uses CROSS APPLY. This one will search every row (role) for the value you put in your like expression...

Given this table structure:

create table MyTable (Roles XML)

insert into MyTable values
('<root>
   <role>Alpha</role>
   <role>Gamma</role>
   <role>Beta</role>
</root>')

We can query it like this:

select * from 

(select 
       pref.value('(text())[1]', 'varchar(32)') as RoleName
from 
       MyTable CROSS APPLY

       Roles.nodes('/root/role') AS Roles(pref)
)  as Result

where RoleName like '%ga%'

You can check the SQL Fiddle here: http://sqlfiddle.com/#!18/dc4d2/1/0

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

How do I handle newlines in JSON?

You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.

The JavaScript implementation of all major browsers have the unescape command.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Easiest way to copy a table from one database to another?

If your tables are on the same mysql server you can run the following

CREATE TABLE destination_db.my_table SELECT * FROM source_db.my_table;
ALTER TABLE destination_db.my_table ADD PRIMARY KEY (id); 
ALTER TABLE destination_db.my_table MODIFY COLUMN id INT AUTO_INCREMENT;

Convert JSONObject to Map

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

Exit from app when click button in android phonegap?

Try this code.

<!DOCTYPE HTML>
<html>
  <head>
    <title>PhoneGap</title>

        <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>      
        <script type="text/javascript" charset="utf-8">

            function onLoad()
            {
                  document.addEventListener("deviceready", onDeviceReady, true);
            }

            function exitFromApp()
             {
                navigator.app.exitApp();
             }

        </script>

    </head>

    <body onload="onLoad();">
       <button name="buttonClick" onclick="exitFromApp()">Click Me!</button>
    </body>
</html>

Replace src="cordova-1.5.0.js" with your phonegap js .

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

Running Command Line in Java

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

Internet Explorer 11 detection

Okay try this, simple and for IE11 and IE below 11 version

browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;

navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 for IE 11 version navigator.userAgent.toUpperCase().indexOf("MSIE") != -1 for IE below 11 version

_x000D_
_x000D_
browserIsIE = navigator.userAgent.toUpperCase().indexOf("TRIDENT/") != -1 || navigator.userAgent.toUpperCase().indexOf("MSIE") != -1;_x000D_
_x000D_
console.log('Is IE Browser : '+ browserIsIE)
_x000D_
_x000D_
_x000D_

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

Importing text file into excel sheet

I think my answer to my own question here is the simplest solution to what you are trying to do:

  1. Select the cell where the first line of text from the file should be.

  2. Use the Data/Get External Data/From File dialog to select the text file to import.

  3. Format the imported text as required.

  4. In the Import Data dialog that opens, click on Properties...

  5. Uncheck the Prompt for file name on refresh box.

  6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.

Note: in your case, you should probably want to skip step #5.

Show tables, describe tables equivalent in redshift

Shortcut

\d for show all tables

\d tablename to describe table

\? for more shortcuts for redshift

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

Search an Oracle database for tables with specific column names?

To find all tables with a particular column:

select owner, table_name from all_tab_columns where column_name = 'ID';

To find tables that have any or all of the 4 columns:

select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');

To find tables that have all 4 columns (with none missing):

select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

How do you clear Apache Maven's cache?

So there are some commands which you can use for cleaning

 1. mvn clean cache   
 2. mvn clean install 
 3. mvn clean install -Pclean-database

also deleting repository folder from .m2 can help.

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete /*# sourceMappingURL=bootstrap.min.css.map */ in css/bootstrap.min.css

and delete /*# sourceMappingURL=bootstrap.css.map */ in css/bootstrap.css

How to check for file lock?

A variation of DixonD's excellent answer (above).

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           TimeSpan timeout,
                           out Stream stream)
{
    var endTime = DateTime.Now + timeout;

    while (DateTime.Now < endTime)
    {
        if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))
            return true;
    }

    stream = null;
    return false;
}

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           out Stream stream)
{
    try
    {
        stream = File.Open(path, fileMode, fileAccess, fileShare);
        return true;
    }
    catch (IOException e)
    {
        if (!FileIsLocked(e))
            throw;

        stream = null;
        return false;
    }
}

private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;

private static bool FileIsLocked(IOException ioException)
{
    var errorCode = (uint)Marshal.GetHRForException(ioException);
    return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}

Usage:

private void Sample(string filePath)
{
    Stream stream = null;

    try
    {
        var timeOut = TimeSpan.FromSeconds(1);

        if (!TryOpen(filePath,
                     FileMode.Open,
                     FileAccess.ReadWrite,
                     FileShare.ReadWrite,
                     timeOut,
                     out stream))
            return;

        // Use stream...
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
}

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

How to set a timer in android

I believe the way to do this on the android is that you need a background service to be running. In that background application, create the timer. When the timer "ticks" (set the interval for how long you want to wait), launch your activity which you want to start.

http://developer.android.com/guide/topics/fundamentals.html (<-- this article explains the relationship between activities, services, intents and other core fundamentals of Android development)

How to split a String by space

Not only white space, but my solution also solves the invisible characters as well.

str = "Hello I'm your String";
String[] splited = str.split("\p{Z}");

Purpose of ESI & EDI registers?

Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,

mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

Pie chart with jQuery

Tons of great suggestions here, just going to throw ZingChart onto the stack for good measure. We recently released a jQuery wrapper for the library that makes it even easier to build and customize charts. The CDN links are in the demo below.

I'm on the ZingChart team and we're here to answer any questions any of you might have!

_x000D_
_x000D_
$('#pie-chart').zingchart({_x000D_
  "data": {_x000D_
    "type": "pie",_x000D_
    "legend": {},_x000D_
    "series": [{_x000D_
      "values": [5]_x000D_
    }, {_x000D_
      "values": [10]_x000D_
    }, {_x000D_
      "values": [15]_x000D_
    }]_x000D_
  }_x000D_
});
_x000D_
<script src="http://cdn.zingchart.com/zingchart.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.zingchart.com/zingchart.jquery.min.js"></script>_x000D_
_x000D_
<div id="pie-chart"></div>
_x000D_
_x000D_
_x000D_

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

how to Call super constructor in Lombok

Version 1.18 of Lombok introduced the @SuperBuilder annotation. We can use this to solve our problem in a simpler way.

You can refer to https://www.baeldung.com/lombok-builder-inheritance#lombok-builder-and-inheritance-3.

so in your child class, you will need these annotations:

@Data
@SuperBuilder
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)

in your parent class:

@Data
@SuperBuilder
@NoArgsConstructor

How to get just the date part of getdate()?

Try this:

SELECT CONVERT(date, GETDATE())

Check a radio button with javascript

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Cancel a UIView animation?

Simplest way to stop all animations on a particular view, immediately, is this:

Link the project to QuartzCore.framework. At the start of your code:

#import <QuartzCore/QuartzCore.h>

Now, when you want to stop all animations on a view dead in their tracks, say this:

[CATransaction begin];
[theView.layer removeAllAnimations];
[CATransaction commit];

The middle line would work all by itself, but there's a delay until the runloop finishes (the "redraw moment"). To prevent that delay, wrap the command in an explicit transaction block as shown. This works provided no other changes have been performed on this layer in the current runloop.

Backbone.js fetch with parameters

You can also set processData to true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery will auto process data object into param string,

but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...

in Backbone source:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

Sorting hashmap based on keys

Use a TreeMap, although having a map "look like that" is a bit nebulous--you could also just sort the keys based on your criteria and iterate over the map, retrieving each object.

Encoding as Base64 in Java

For Java 6-7, the best option is to borrow code from the Android repository. It has no dependencies.

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Base64.java

Uncaught TypeError: Cannot read property 'length' of undefined

You are accessing an object that is not defined.

The solution is check for null or undefined (to see whether the object exists) and only then iterate.

git returns http error 407 from proxy after CONNECT

Removing "@" from password worked for me and in anyways never keep @ in your password it will give you issue with maven and further installation

Get Android API level of phone currently running my application

Check android.os.Build.VERSION, which is a static class that holds various pieces of information about the Android OS a system is running.

If you care about all versions possible (back to original Android version), as in minSdkVersion is set to anything less than 4, then you will have to use android.os.Build.VERSION.SDK, which is a String that can be converted to the integer of the release.

If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of android.os.Build.VERSION.SDK_INT, which is an integer.

In either case, the integer you get maps to an enum value from all those defined in android.os.Build.VERSION_CODES:

SDK_INT value        Build.VERSION_CODES        Human Version Name       
    1                  BASE                      Android 1.0 (no codename)
    2                  BASE_1_1                  Android 1.1 Petit Four
    3                  CUPCAKE                   Android 1.5 Cupcake
    4                  DONUT                     Android 1.6 Donut
    5                  ECLAIR                    Android 2.0 Eclair
    6                  ECLAIR_0_1                Android 2.0.1 Eclair                  
    7                  ECLAIR_MR1                Android 2.1 Eclair
    8                  FROYO                     Android 2.2 Froyo
    9                  GINGERBREAD               Android 2.3 Gingerbread
   10                  GINGERBREAD_MR1           Android 2.3.3 Gingerbread
   11                  HONEYCOMB                 Android 3.0 Honeycomb
   12                  HONEYCOMB_MR1             Android 3.1 Honeycomb
   13                  HONEYCOMB_MR2             Android 3.2 Honeycomb
   14                  ICE_CREAM_SANDWICH        Android 4.0 Ice Cream Sandwich
   15                  ICE_CREAM_SANDWICH_MR1    Android 4.0.3 Ice Cream Sandwich
   16                  JELLY_BEAN                Android 4.1 Jellybean
   17                  JELLY_BEAN_MR1            Android 4.2 Jellybean
   18                  JELLY_BEAN_MR2            Android 4.3 Jellybean
   19                  KITKAT                    Android 4.4 KitKat
   20                  KITKAT_WATCH              Android 4.4 KitKat Watch
   21                  LOLLIPOP                  Android 5.0 Lollipop
   22                  LOLLIPOP_MR1              Android 5.1 Lollipop
   23                  M                         Android 6.0 Marshmallow
   24                  N                         Android 7.0 Nougat
   25                  N_MR1                     Android 7.1.1 Nougat
   26                  O                         Android 8.0 Oreo
   27                  O_MR1                     Android 8 Oreo MR1
   28                  P                         Android 9 Pie
   29                  Q                         Android 10
  10000                CUR_DEVELOPMENT           Current Development Version

Note that some time between Android N and O, the Android SDK began aliasing CUR_DEVELOPMENT and the developer preview of the next major Android version to be the same SDK_INT value (10000).