Programs & Examples On #Maven plugin

Do not use this tag for the use of specific Maven plugins. Use it only for Maven plugins development related questions.

Eclipse : Maven search dependencies doesn't work

It is neccesary to provide Group Id and Artifact Id to download the jar file you need. If you want to search it just use * , * for these fields.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

Unsupported major.minor version 52.0 in my app

I'd had this issue for too long (SO etc hadn't helped) and only just solved it (using sdk 25).

-The local.properties file proguard.dir var was not applying with ant; I'd specified 5.3.2, but a command line call and signed export build (eclipse) was using 4.7, from the sdk dir(only 5+ supports java 8)

My solution was to replace the proguard jars (android-sdk/tools/proguard/libs directory) in the sdk with a current (5+) version of proguard.

Maven 3 warnings about build.plugins.plugin.version

Maven 3 is more restrictive with the POM-Structure. You have to set versions of Plugins for instance.

With maven 3.1 these warnings may break you build. There are more changes between maven2 and maven3: https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

The error is due to maven official repository being not accessible. This repo (https://repo.maven.apache.org/maven2/) is not accessible so follow these steps:

  1. Firstly delete your /home/user/.m2 folder
  2. create .m2 folder at user home and repository folder within .m2
  3. copy the default settings.xml to .m2 folder
  4. Change mirrors as follows in the settings.xml as shown in below snap mirror_settings

_x000D_
_x000D_
<mirrors>_x000D_
  <mirror>_x000D_
    <id>UK</id>_x000D_
    <name>UK Central</name>_x000D_
    <url>http://uk.maven.org/maven2</url>_x000D_
    <mirrorOf>central</mirrorOf>_x000D_
  </mirror>_x000D_
</mirrors>
_x000D_
_x000D_
_x000D_

  1. Execute the mvn clean commands now .....

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

In my case the targetPath was not having any value it was blank in the resources --> resource for the file directory with files that had issue. I had to update it to global as seen in the Code Sample 2 and re-run build to fix the issue.

Code Sample 1 (with issue)

<build>
    <resources>
        <resource>
            <directory>src/main/locale</directory>
            <filtering>true</filtering>
            <targetPath></targetPath>
            <includes>
                <include>*.xml</include>
                <include>*.config</include>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>

Code Sample 2 (fix applied)

<build>
    <resources>
        <resource>
            <directory>src/main/locale</directory>
            <filtering>true</filtering>
            <targetPath>global</targetPath>
            <includes>
                <include>*.xml</include>
                <include>*.config</include>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>

m2e lifecycle-mapping not found

Suprisingly these 3 steps helped me:

mvn clean
mvn package
mvn spring-boot:run

c# dictionary one key many values

A .NET dictionary does only have a 1-to-1 relationship for keys and values. But that doesn't mean that a value can't be another array/list/dictionary.

I can't think of a reason to have a 1 to many relationship in a dictionary, but obviously there is one.

If you have different types of data that you want to store to a key, then that sounds like the ideal time to create your own class. Then you have a 1 to 1, but you have the value class storing more that 1 piece of data.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

How to split the screen with two equal LinearLayouts?

I am answering this question after 4-5 years but best practices to do this as below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <LinearLayout
      android:id="@+id/firstLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toLeftOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>

   <View
      android:id="@+id/secondView"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_centerHorizontal="true" />

   <LinearLayout
      android:id="@+id/thirdLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_toRightOf="@+id/secondView"
      android:orientation="vertical"></LinearLayout>
</RelativeLayout>

This is right approach as use of layout_weight is always heavy for UI operations. Splitting Layout equally using LinearLayout is not good practice

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

python's re: return True if string contains regex pattern

Here's a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex, text)
    return pattern.search(text) is not None

The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.

Examples:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

CSS: How can I set image size relative to parent height?

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

Using ALTER to drop a column if it exists in MySQL

There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.

drop procedure if exists schema_change;

delimiter ';;'
create procedure schema_change() begin

    /* delete columns if they exist */
    if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
        alter table table1 drop column `column1`;
    end if;
    if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
        alter table table1 drop column `column2`;
    end if;

    /* add columns */
    alter table table1 add column `column1` varchar(255) NULL;
    alter table table1 add column `column2` varchar(255) NULL;

end;;

delimiter ';'
call schema_change();

drop procedure if exists schema_change;

I wrote some more detailed information in a blog post.

Oracle: Import CSV file

SQL Loader is the way to go. I recently loaded my table from a csv file,new to this concept,would like to share an example.

LOAD DATA
    infile '/ipoapplication/utl_file/LBR_HE_Mar16.csv'
    REPLACE
    INTO TABLE LOAN_BALANCE_MASTER_INT
    fields terminated by ',' optionally enclosed by '"'
    (
    ACCOUNT_NO,
    CUSTOMER_NAME,
    LIMIT,
    REGION

    )

Place the control file and csv at the same location on the server. Locate the sqlldr exe and invoce it.

sqlldr userid/passwd@DBname control= Ex : sqlldr abc/xyz@ora control=load.ctl

Hope it helps.

Get spinner selected items text?

spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

            String selected_val=spinner_button.getSelectedItem().toString();

            Toast.makeText(getApplicationContext(), selected_val ,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}

Parsing query strings on Android

public static Map<String, List<String>> getUrlParameters(String url)
        throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length > 1) {
        String query = urlParts[1];
        for (String param : query.split("&")) {
            String pair[] = param.split("=", 2);
            String key = URLDecoder.decode(pair[0], "UTF-8");
            String value = "";
            if (pair.length > 1) {
                value = URLDecoder.decode(pair[1], "UTF-8");
            }
            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<String>();
                params.put(key, values);
            }
            values.add(value);
        }
    }
    return params;
}

On - window.location.hash - Change?

The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.


Update to keep this answer fresh:

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..
});

The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

How do I tell if a regular file does not exist in Bash?

To test file existence, the parameter can be any one of the following:

-e: Returns true if file exists (regular file, directory, or symlink)
-f: Returns true if file exists and is a regular file
-d: Returns true if file exists and is a directory
-h: Returns true if file exists and is a symlink

All the tests below apply to regular files, directories, and symlinks:

-r: Returns true if file exists and is readable
-w: Returns true if file exists and is writable
-x: Returns true if file exists and is executable
-s: Returns true if file exists and has a size > 0

Example script:

#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exist"
fi

How do I find out if the GPS of an Android device is enabled

Best way seems to be the following:

 final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

How do I store the select column in a variable?

Assuming such a query would return a single row, you could use either

select @EmpId = Id from dbo.Employee

Or

set @EmpId = (select Id from dbo.Employee)

Is there more to an interface than having the correct methods

Don't forget that at a later date you can take an existing class, and make it implement IBox, and it will then become available to all your box-aware code.

This becomes a bit clearer if interfaces are named -able. e.g.

public interface Saveable {
....

public interface Printable {
....

etc. (Naming schemes don't always work e.g. I'm not sure Boxable is appropriate here)

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

To make it clear, in addition to @SLaks' answer, that meant you need to change this line :

List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);

to something like this :

RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

Getting current device language in iOS?

iOS13, Swift 5+, WWDC2019 https://developer.apple.com/videos/play/wwdc2019/403/

Users can select the preferred language of an app independently from the OS language.

You can use these:

    // Returns a list of the user's preferred languages.
    // Maybe more than (or none of) your app supports!
    Locale.preferredLanguages

    // a subset of this bundle's localizations, re-ordered into the preferred order
    // for this process's current execution environment; the main bundle's preferred localizations
    // indicate the language (of text) the user is most likely seeing in the UI
    Bundle.main.preferredLocalizations



    // The current running app language
    Bundle.main.preferredLocalizations.first

    // list of language names this bundle appears to be localized to
    Bundle.main.localizations

Can enums be subclassed to add new elements?

In the hopes this elegant solution of a colleague of mine is even seen in this long post I'd like to share this approach for subclassing which follows the interface approach and beyond.

Please be aware that we use custom exceptions here and this code won't compile unless you replace it with your exceptions.

The documentation is extensive and I hope it's understandable for most of you.

The interface that every subclassed enum needs to implement.

public interface Parameter {
  /**
   * Retrieve the parameters name.
   *
   * @return the name of the parameter
   */
  String getName();

  /**
   * Retrieve the parameters type.
   *
   * @return the {@link Class} according to the type of the parameter
   */
  Class<?> getType();

  /**
   * Matches the given string with this parameters value pattern (if applicable). This helps to find
   * out if the given string is a syntactically valid candidate for this parameters value.
   *
   * @param valueStr <i>optional</i> - the string to check for
   * @return <code>true</code> in case this parameter has no pattern defined or the given string
   *         matches the defined one, <code>false</code> in case <code>valueStr</code> is
   *         <code>null</code> or an existing pattern is not matched
   */
  boolean match(final String valueStr);

  /**
   * This method works as {@link #match(String)} but throws an exception if not matched.
   *
   * @param valueStr <i>optional</i> - the string to check for
   * @throws ArgumentException with code
   *           <dl>
   *           <dt>PARAM_MISSED</dt>
   *           <dd>if <code>valueStr</code> is <code>null</code></dd>
   *           <dt>PARAM_BAD</dt>
   *           <dd>if pattern is not matched</dd>
   *           </dl>
   */
  void matchEx(final String valueStr) throws ArgumentException;

  /**
   * Parses a value for this parameter from the given string. This method honors the parameters data
   * type and potentially other criteria defining a valid value (e.g. a pattern).
   *
   * @param valueStr <i>optional</i> - the string to parse the parameter value from
   * @return the parameter value according to the parameters type (see {@link #getType()}) or
   *         <code>null</code> in case <code>valueStr</code> was <code>null</code>.
   * @throws ArgumentException in case <code>valueStr</code> is not parsable as a value for this
   *           parameter.
   */
  Object parse(final String valueStr) throws ArgumentException;

  /**
   * Converts the given value to its external form as it is accepted by {@link #parse(String)}. For
   * most (ordinary) parameters this is simply a call to {@link String#valueOf(Object)}. In case the
   * parameter types {@link Object#toString()} method does not return the external form (e.g. for
   * enumerations), this method has to be implemented accordingly.
   *
   * @param value <i>mandatory</i> - the parameters value
   * @return the external form of the parameters value, never <code>null</code>
   * @throws InternalServiceException in case the given <code>value</code> does not match
   *           {@link #getType()}
   */
  String toString(final Object value) throws InternalServiceException;
}

The implementing ENUM base class.

public enum Parameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(new ParameterImpl<String>("VALUE", String.class, "[A-Za-z]{3,10}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param <i>mandatory</i> - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

The subclassed ENUM which "inherits" from base class.

public enum ExtendedParameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(my.package.name.VALUE);

  /**
   * EXTENDED ENUM VALUE
   */
  EXTENDED_VALUE(new ParameterImpl<String>("EXTENDED_VALUE", String.class, "[0-9A-Za-z_.-]{1,20}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param <i>mandatory</i> - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

Finally the generic ParameterImpl to add some utilities.

public class ParameterImpl<T> implements Parameter {
  /**
   * The default pattern for numeric (integer, long) parameters.
   */
  private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");

  /**
   * The default pattern for parameters of type boolean.
   */
  private static final Pattern BOOLEAN_PATTERN = Pattern.compile("0|1|true|false");

  /**
   * The name of the parameter, never <code>null</code>.
   */
  private final String name;

  /**
   * The data type of the parameter.
   */
  private final Class<T> type;

  /**
   * The validation pattern for the parameters values. This may be <code>null</code>.
   */
  private final Pattern validator;

  /**
   * Shortcut constructor without <code>validatorPattern</code>.
   *
   * @param name <i>mandatory</i> - the value for {@link #name}
   * @param type <i>mandatory</i> - the value for {@link #type}
   */
  public ParameterImpl(final String name, final Class<T> type) {
    this(name, type, null);
  }

  /**
   * Constructor.
   *
   * @param name <i>mandatory</i> - the value for {@link #name}
   * @param type <i>mandatory</i> - the value for {@link #type}
   * @param validatorPattern - <i>optional</i> - the pattern for {@link #validator}
   *          <dl>
   *          <dt style="margin-top:0.25cm;"><i>Note:</i>
   *          <dd>The default validation patterns {@link #NUMBER_PATTERN} or
   *          {@link #BOOLEAN_PATTERN} are applied accordingly.
   *          </dl>
   */
  public ParameterImpl(final String name, final Class<T> type, final String validatorPattern) {
    this.name = name;
    this.type = type;
    if (null != validatorPattern) {
      this.validator = Pattern.compile(validatorPattern);

    } else if (Integer.class == this.type || Long.class == this.type) {
      this.validator = NUMBER_PATTERN;
    } else if (Boolean.class == this.type) {
      this.validator = BOOLEAN_PATTERN;
    } else {
      this.validator = null;
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    if (null == valueStr) {
      return false;
    }
    if (null != this.validator) {
      final Matcher matcher = this.validator.matcher(valueStr);
      return matcher.matches();
    }
    return true;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) throws ArgumentException {
    if (false == this.match(valueStr)) {
      if (null == valueStr) {
        throw ArgumentException.createEx(ErrorCode.PARAM_MISSED, "The value must not be null",
            this.name);
      }
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value must match the pattern: "
          + this.validator.pattern(), this.name);
    }
  }

  /**
   * Parse the parameters value from the given string value according to {@link #type}. Additional
   * the value is checked by {@link #matchEx(String)}.
   *
   * @param valueStr <i>optional</i> - the string value to parse the value from
   * @return the parsed value, may be <code>null</code>
   * @throws ArgumentException in case the parameter:
   *           <ul>
   *           <li>does not {@link #matchEx(String)} the {@link #validator}</li>
   *           <li>cannot be parsed according to {@link #type}</li>
   *           </ul>
   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  @Override
  public T parse(final String valueStr) throws ArgumentException, InternalServiceException {
    if (null == valueStr) {
      return null;
    }
    this.matchEx(valueStr);

    if (String.class == this.type) {
      return this.type.cast(valueStr);
    }
    if (Boolean.class == this.type) {
      return this.type.cast(Boolean.valueOf(("1".equals(valueStr)) || Boolean.valueOf(valueStr)));
    }
    try {
      if (Integer.class == this.type) {
        return this.type.cast(Integer.valueOf(valueStr));
      }
      if (Long.class == this.type) {
        return this.type.cast(Long.valueOf(valueStr));
      }
    } catch (final NumberFormatException e) {
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value cannot be parsed as "
          + this.type.getSimpleName().toLowerCase() + ".", this.name);
    }

    return this.parseOther(valueStr);
  }

  /**
   * Field access for {@link #name}.
   *
   * @return the value of {@link #name}.
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Field access for {@link #type}.
   *
   * @return the value of {@link #type}.
   */
  @Override
  public Class<T> getType() {
    return this.type;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public final String toString(final Object value) throws InternalServiceException {
    if (false == this.type.isAssignableFrom(value.getClass())) {
      throw new InternalServiceException(ErrorCode.PANIC,
          "Parameter.toString(): Bad type of value. Expected {0} but is {1}.", this.type.getName(),
          value.getClass().getName());
    }
    if (String.class == this.type || Integer.class == this.type || Long.class == this.type) {
      return String.valueOf(value);
    }
    if (Boolean.class == this.type) {
      return Boolean.TRUE.equals(value) ? "1" : "0";
    }

    return this.toStringOther(value);
  }

  /**
   * Parse parameter values of other (non standard types). This method is called by
   * {@link #parse(String)} in case {@link #type} is none of the supported standard types (currently
   * String, Boolean, Integer and Long). It is intended for extensions.
   * <dl>
   * <dt style="margin-top:0.25cm;"><i>Note:</i>
   * <dd>This default implementation always throws an InternalServiceException.
   * </dl>
   *
   * @param valueStr <i>mandatory</i> - the string value to parse the value from
   * @return the parsed value, may be <code>null</code>
   * @throws ArgumentException in case the parameter cannot be parsed according to {@link #type}
   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  protected T parseOther(final String valueStr) throws ArgumentException, InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.parseOther(): Unsupported parameter type: " + this.type.getName());
  }

  /**
   * Convert the values of other (non standard types) to their external form. This method is called
   * by {@link #toString(Object)} in case {@link #type} is none of the supported standard types
   * (currently String, Boolean, Integer and Long). It is intended for extensions.
   * <dl>
   * <dt style="margin-top:0.25cm;"><i>Note:</i>
   * <dd>This default implementation always throws an InternalServiceException.
   * </dl>
   *
   * @param value <i>mandatory</i> - the parameters value
   * @return the external form of the parameters value, never <code>null</code>
   * @throws InternalServiceException in case the given <code>value</code> does not match
   *           {@link #getClass()}
   */
  protected String toStringOther(final Object value) throws InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.toStringOther(): Unsupported parameter type: " + this.type.getName());
  }
}

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Nodemailer with Gmail and NodeJS

It is resolved using nodemailer-smtp-transport module inside createTransport.

var smtpTransport = require('nodemailer-smtp-transport');

var transport = nodemailer.createTransport(smtpTransport({
    service: 'gmail',
    auth: {
        user: '*******@gmail.com',
        pass: '*****password'
    }
}));

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

Finding whether a point lies inside a rectangle or not

If you can't solve the problem for the rectangle try dividing the problem in to easier problems. Divide the rectangle into 2 triangles an check if the point is inside any of them like they explain in here

Essentially, you cycle through the edges on every two pairs of lines from a point. Then using cross product to check if the point is between the two lines using the cross product. If it's verified for all 3 points, then the point is inside the triangle. The good thing about this method is that it does not create any float-point errors which happens if you check for angles.

How to identify server IP address in PHP

You may have to use $HTTP_SERVER_VARS['server_ADDR'] if you are not getting anything from above answers and if you are using older version of PHP

bootstrap initially collapsed element

need to delete show from class:

<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">

It have to be

<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">

Simple dictionary in C++

Until I was really concerned about performance, I would use a function, that takes a base and returns its match:

char base_pair(char base)
{
    switch(base) {
        case 'T': return 'A';
        ... etc
        default: // handle error
    }
}

If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.

How do I disable form fields using CSS?

This can be helpful:

<input type="text" name="username" value="admin" >

<style type="text/css">
input[name=username] {
    pointer-events: none;
 }
</style>

Update:

and if want to disable from tab index you can use it this way:

 <input type="text" name="username" value="admin" tabindex="-1" >

 <style type="text/css">
  input[name=username] {
    pointer-events: none;
   }
 </style>

How can I access each element of a pair in a pair list?

A 2-tuple is a pair. You can access the first and second elements like this:

x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1

libpng warning: iCCP: known incorrect sRGB profile

Use pngcrush to remove the incorrect sRGB profile from the png file:

pngcrush -ow -rem allb -reduce file.png
  • -ow will overwrite the input file
  • -rem allb will remove all ancillary chunks except tRNS and gAMA
  • -reduce does lossless color-type or bit-depth reduction

In the console output you should see Removed the sRGB chunk, and possibly more messages about chunk removals. You will end up with a smaller, optimized PNG file. As the command will overwrite the original file, make sure to create a backup or use version control.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

So here is the brief summary for Bootstrap 4:

<div class="container-fluid px-0">
  <div class="row no-gutters">
    <div class="col-12">          //any cols you need
        ...
    </div>
  </div>
</div>

It works for me.

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

AngularJS sorting by property

You should really improve your JSON structure to fix your problem:

$scope.testData = [
   {name:"CData", order: 1},
   {name:"BData", order: 2},
   {name:"AData", order: 3},
]

Then you could do

<li ng-repeat="test in testData | orderBy:order">...</li>

The problem, I think, is that the (key, value) variables are not available to the orderBy filter, and you should not be storing data in your keys anyways

nginx - read custom header from upstream server

$http_name_of_the_header_key

i.e if you have origin = domain.com in header, you can use $http_origin to get "domain.com"

In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores

Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_

For your example the variable would be $http_my_custom_header.

How do I lock the orientation to portrait mode in a iPhone Web Application?

This answer is not yet possible, but I am posting it for "future generations". Hopefully, some day we will be able to do this via the CSS @viewport rule:

@viewport {
    orientation: portrait;
}

Here is the "Can I Use" page (as of 2019 only IE and Edge):
https://caniuse.com/#feat=mdn-css_at-rules_viewport_orientation

Spec(in process):
https://drafts.csswg.org/css-device-adapt/#orientation-desc

MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/@viewport/orientation

Based on the MDN browser compatibility table and the following article, looks like there is some support in certain versions of IE and Opera:
http://menacingcloud.com/?c=cssViewportOrMetaTag

This JS API Spec also looks relevant:
https://w3c.github.io/screen-orientation/

I had assumed that because it was possible with the proposed @viewport rule, that it would be possible by setting orientation in the viewport settings in a meta tag, but I have had no success with this thus far.

Feel free to update this answer as things improve.

Creating Roles in Asp.net Identity MVC 5

In ASP.NET 5 rc1-final, I did following:

Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(
        IRoleStore<IdentityRole> store,
        IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<RoleManager<IdentityRole>> logger,
        IHttpContextAccessor contextAccessor)
        : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
    {
    }
}

To ConfigureServices in Startup.cs, I added it as RoleManager

services.
    .AddIdentity<ApplicationUser, IdentityRole>()
    .AddRoleManager<ApplicationRoleManager>();

For creating new Roles, call from Configure following:

public static class RoleHelper
{
    private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
    {
        if (!await roleManager.RoleExistsAsync(roleName))
        {
            await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
    public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
    {
        // add all roles, that should be in database, here
        await EnsureRoleCreated(roleManager, "Developer");
    }
}

public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
     ...
     await roleManager.EnsureRolesCreated();
     ...
}

Now, the rules can be assigned to user

await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");

Or used in Authorize attribute

[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}

CodeIgniter htaccess and URL rewrite issues

if not working

$config['uri_protocol'] = 'AUTO';

change it to

$config['uri_protocol'] = 'PATH_INFO';

if not working change it to

$config['uri_protocol'] = 'QUERY_STRING';

if use this

$config['uri_protocol'] = 'ORIG_PATH_INFO';

with redirect or header location to url not in htaccess will not work you must add the url in htaccess to work

How do I pass multiple parameters into a function in PowerShell?

I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:

Splat With Arrays (Positional Arguments)

Test-Connection with Positional Arguments

Test-Connection www.google.com localhost

With Array Splatting

$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray

Note that when splatting, we reference the splatted variable with an @ instead of a $. It is the same when using a Hashtable to splat as well.

Splat With Hashtable (Named Arguments)

Test-Connection with Named Arguments

Test-Connection -ComputerName www.google.com -Source localhost

With Hashtable Splatting

$argumentHash = @{
  ComputerName = 'www.google.com'
  Source = 'localhost'
}
Test-Connection @argumentHash

Splat Positional and Named Arguments Simultaneously

Test-Connection With Both Positional and Named Arguments

Test-Connection www.google.com localhost -Count 1

Splatting Array and Hashtables Together

$argumentHash = @{
  Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray

Convert java.time.LocalDate into java.util.Date type

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

Is there a way to automatically build the package.json file for Node.js projects

I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.

var fs = require("fs");

function main() {
  fs.readdir("./node_modules", function (err, dirs) {
    if (err) {
      console.log(err);
      return;
    }
    dirs.forEach(function(dir){
      if (dir.indexOf(".") !== 0) {
        var packageJsonFile = "./node_modules/" + dir + "/package.json";
        if (fs.existsSync(packageJsonFile)) {
          fs.readFile(packageJsonFile, function (err, data) {
            if (err) {
              console.log(err);
            }
            else {
              var json = JSON.parse(data);
              console.log('"'+json.name+'": "' + json.version + '",');
            }
          });
        }
      }
    });

  });
}

main();

In my case, the above script outputs:

"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0",   // Remember: remove the comma character in the last line.

Now, you can copy&paste them. Have fun!

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

Emulator: ERROR: x86 emulation currently requires hardware acceleration

If you are using an AMD CPU, AMD Virtualization (CPUs such as Ryzen) is now officially supported. Make sure you have virtualization switched on in the BIOS.

In "Turn Windows Features On or Off" (you can find it through Windows Search), you'll need to enable

Once you restart and start up the emulator (an x86 build), it should start booting up without the mentioned error.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

You can also use this extension method to easily register a handler for item property change in relevant collections. This method is automatically added to all the collections implementing INotifyCollectionChanged that hold items that implement INotifyPropertyChanged:

public static class ObservableCollectionEx
{
    public static void SetOnCollectionItemPropertyChanged<T>(this T _this, PropertyChangedEventHandler handler)
        where T : INotifyCollectionChanged, ICollection<INotifyPropertyChanged> 
    {
        _this.CollectionChanged += (sender,e)=> {
            if (e.NewItems != null)
            {
                foreach (Object item in e.NewItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged += handler;
                }
            }
            if (e.OldItems != null)
            {
                foreach (Object item in e.OldItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged -= handler;
                }
            }
        };
    }
}

How to use:

public class Test
{
    public static void MyExtensionTest()
    {
        ObservableCollection<INotifyPropertyChanged> c = new ObservableCollection<INotifyPropertyChanged>();
        c.SetOnCollectionItemPropertyChanged((item, e) =>
        {
             //whatever you want to do on item change
        });
    }
}

Equivalent of LIMIT for DB2

Try this

SELECT * FROM
    (
        SELECT T.*, ROW_NUMBER() OVER() R FROM TABLE T
    )
    WHERE R BETWEEN 10000 AND 20000

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

How to get the html of a div on another page with jQuery ajax?

Ok, You should "construct" the html and find the .content div.

like this:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#content').html());
   }
});

Simple!

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

char *array and char array[]

It's very similar to

char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};

but gives you read-only memory.

For a discussion of the difference between a char[] and a char *, see comp.lang.c FAQ 1.32.

How to Export Private / Secret ASC Key to Decrypt GPG Files

I think you had not yet import the private key as the message error said, To import public/private key from gnupg:

gpg --import mypub_key
gpg --allow-secret-key-import --import myprv_key

Using print statements only to debug

I don't know about others, but I was used to define a "global constant" (DEBUG) and then a global function (debug(msg)) that would print msg only if DEBUG == True.

Then I write my debug statements like:

debug('My value: %d' % value)

...then I pick up unit testing and never did this again! :)

Border Height on CSS

I have another possibility. This is of course a "newer" technique, but for my projects works sufficient.

It only works if you need one or two borders. I've never done it with 4 borders... and to be honest, I don't know the answer for that yet.

.your-item {
  position: relative;
}

.your-item:after {
  content: '';
  height: 100%; //You can change this if you want smaller/bigger borders
  width: 1px;

  position: absolute;
  right: 0;
  top: 0; // If you want to set a smaller height and center it, change this value

  background-color: #000000; // The color of your border
}

I hope this helps you too, as for me, this is an easy workaround.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

`Follow below steps:

its working for me.To resolve this issue,

1.Right Click on appcompat_v7 library and select Properties

2.Now, Click on Android Option, Set Project Build Path as Android 5.0 (API level 21) Apply Changes.

3.Now go to project.properties file under appcompat_v7 library,

4.Set the project target as : target=android-21

5.Now Clean + Build appcompat_v7 library and your projects`

Should switch statements always contain a default clause?

Should switch statements always contain a default clause ? No switch cases can exist with out default case, in switch case default case will trigger switch value switch(x) in this case x when not match with any other case values.

How to insert an element after another element in JavaScript without using a library?

I know this question has far too many answers already, but none of them met my exact requirements.

I wanted a function that has the exact opposite behavior of parentNode.insertBefore - that is, it must accept a null referenceNode (which the accepted answer does not) and where insertBefore would insert at the end of the children this one must insert at the start, since otherwise there'd be no way to insert at the start location with this function at all; the same reason insertBefore inserts at the end.

Since a null referenceNode requires you to locate the parent, we need to know the parent - insertBefore is a method of the parentNode, so it has access to the parent that way; our function doesn't, so we'll need to pass the parent as a parameter.

The resulting function looks like this:

function insertAfter(parentNode, newNode, referenceNode) {
  parentNode.insertBefore(
    newNode,
    referenceNode ? referenceNode.nextSibling : parentNode.firstChild
  );
}

Or (if you must, I don't recommend it) you can of course enhance the Node prototype:

if (! Node.prototype.insertAfter) {
  Node.prototype.insertAfter = function(newNode, referenceNode) {
    this.insertBefore(
      newNode,
      referenceNode ? referenceNode.nextSibling : this.firstChild
    );
  };
}

Android scale animation on view

Resize using helper methods and start-repeat-end handlers like this:

resize(
    view1,
    1.0f,
    0.0f,
    1.0f,
    0.0f,
    0.0f,
    0.0f,
    150,
    null,
    null,
    null);

  return null;
}

Helper methods:

/**
 * Resize a view.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration) {

  resize(
    view,
    fromX,
    toX,
    fromY,
    toY,
    pivotX,
    pivotY,
    duration,
    null,
    null,
    null);
}

/**
 * Resize a view with handlers.
 *
 * @param view     A view to resize.
 * @param fromX    X scale at start.
 * @param toX      X scale at end.
 * @param fromY    Y scale at start.
 * @param toY      Y scale at end.
 * @param pivotX   Rotate angle at start.
 * @param pivotY   Rotate angle at end.
 * @param duration Animation duration.
 * @param start    Actions on animation start. Otherwise NULL.
 * @param repeat   Actions on animation repeat. Otherwise NULL.
 * @param end      Actions on animation end. Otherwise NULL.
 */
public static void resize(
  View view,
  float fromX,
  float toX,
  float fromY,
  float toY,
  float pivotX,
  float pivotY,
  int duration,
  Callable start,
  Callable repeat,
  Callable end) {

  Animation animation;

  animation =
    new ScaleAnimation(
      fromX,
      toX,
      fromY,
      toY,
      Animation.RELATIVE_TO_SELF,
      pivotX,
      Animation.RELATIVE_TO_SELF,
      pivotY);

  animation.setDuration(
    duration);

  animation.setInterpolator(
    new AccelerateDecelerateInterpolator());

  animation.setFillAfter(true);

  view.startAnimation(
    animation);

  animation.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) {

      if (start != null) {
        try {

          start.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    }

    @Override
    public void onAnimationEnd(Animation animation) {

      if (end != null) {
        try {

          end.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    @Override
    public void onAnimationRepeat(
      Animation animation) {

      if (repeat != null) {
        try {

          repeat.call();

        } catch (Exception e) {
          e.printStackTrace();
        }
      }  
    }
  });
}

TypeError: got multiple values for argument

Simply put you can't do the following:

class C(object):
    def x(self, y, **kwargs):
        # Which y to use, kwargs or declaration? 
        pass

c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS

Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.

How to get row data by clicking a button in a row in an ASP.NET gridview

You can also use button click event like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" 
                    OnClick="MyButtonClick" />
    </ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
    //Get the button that raised the event
    Button btn = (Button)sender;

    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
} 

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
 {

    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    

      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
    }
}

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">

        <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
        </columns>
  </asp:gridview>

Check full example on MSDN

Public class is inaccessible due to its protection level

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

Error: Local workspace file ('angular.json') could not be found

I was getting the same error messages. It was a silly mistake on my end, I was not running ng serve in the directory where my Angular project is. Make sure you are in the correct directory (project directory) before running this command.

How do you set the document title in React?

you should set document title in the life cycle of 'componentWillMount':

componentWillMount() {
    document.title = 'your title name'
  },

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Input group - two inputs close to each other

With Bootstrap 4.1 I found a width solution by percentage:

The following shows an input-group with 4 Elements: 1 text an 3 selects - working well:

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">_x000D_
_x000D_
<div class="input-group input-group-sm">_x000D_
 <div class="input-group-prepend">_x000D_
  <div class="input-group-text">TEXT:</div>_x000D_
 </div>_x000D_
 <select name="name1" id="name1" size="1" style="width:4%;" class="form-control">_x000D_
  <option value="">option</option>_x000D_
  <!-- snip -->_x000D_
 </select>    _x000D_
 <select name="name2" id="name2" size="1" style="width:60%;" class="form-control">_x000D_
  <option value="">option</option>_x000D_
  <!-- snip -->_x000D_
 </select>     _x000D_
 <select name="name3" id="name3" size="1" style="width:25%;" class="form-control">_x000D_
  <option value="">option</option>_x000D_
  <!-- snip -->_x000D_
 </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Upload video files via PHP and save them in appropriate folder and have a database entry

HTML Code

<html>
<body>

<head>
<title></title>
</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file"><span>Filename:</span></label>
    <input type="file" name="file" id="file" /> 
    <br />
<input type="submit" name="submit" value="Submit" />
</form>



<?php

    //============================= DATABASE CONNECTIVITY d ====================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    //============================= DATABASE CONNECTIVITY u ====================
    //============================= Retrieve data from DB d ====================
    $sql = "SELECT name, size, type FROM videos";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) 
        {
        $path = "uploaded/" . $row["name"];

            echo $path . "<br>";

        }
    } else {
        echo "0 results";
    }
    $conn->close();
    //============================= Retrieve data from DB d ====================

?>


</body>
</html>

What is the difference between Scrum and Agile Development?

SCRUM :

SCRUM is a type of Agile approach. It is a Framework not a Methodology.

It does not provide detailed instructions to what needs to be done rather most of it is dependent on the team that is developing the software. Because the developing the project knows how the problem can be solved that is why much is left on them

Cross-functional and self-organizing teams are essential in case of scrum. There is no team leader in this case who will assign tasks to the team members rather the whole team addresses the issues or problems. It is cross-functional in a way that everyone is involved in the project right from the idea to the implementation of the project.

The advantage of scrum is that a project’s direction to be adjusted based on completed work, not on speculation or predictions.

Roles Involved : Product Owner, Scrum Master, Team Members

Agile Methodology :

Build Software applications that are unpredictable in nature

Iterative and incremental work cadences called sprints are used in this methodology.

Both Agile and SCRUM follows the system -- some of the features are developed as a part of the sprint and at the end of each sprint; the features are completed right from coding, testing and their integration into the product. A demonstration of the functionality is provided to the owner at the end of each sprint so that feedback can be taken which can be helpful for the next sprint.

Manifesto for Agile Development :

  1. Individuals and interactions over processes and tools
  2. Working software over comprehensive documentation
  3. Customer collaboration over contract negotiation
  4. Responding to change over following a plan

That is, while there is value in the items on the right, we value the items on the left more.

How to assign text size in sp value using java code

Cleaner and more reusable approach is

define text size in dimens.xml file inside res/values/ directory:

</resources>
   <dimen name="text_medium">14sp</dimen>
</resources>

and then apply it to the TextView:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));

right align an image using CSS HTML

There are a few different ways to do this but following is a quick sample of one way.

<img src="yourimage.jpg" style="float:right" /><div style="clear:both">Your text here.</div>

I used inline styles for this sample but you can easily place these in a stylesheet and reference the class or id.

enabling cross-origin resource sharing on IIS7

With ASP.net Web API 2 install Microsoft ASP.NET Cross Origin support via nuget.

http://enable-cors.org/server_aspnet.html

public static void Register(HttpConfiguration config)
{
 var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com",
                                                   "Origin, Content-Type, Accept",
                                                   "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
}

Why the switch statement cannot be applied on strings?

You can't use string in switch case.Only int & char are allowed. Instead you can try enum for representing the string and use it in the switch case block like

enum MyString(raj,taj,aaj);

Use it int the swich case statement.

Get the item doubleclick event of listview

The sender is of type ListView not ListViewItem.

    private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ListView triggerView = sender as ListView;
        if (triggerView != null)
        {
            btnEditTrigger_Click(null, null);
        }
    }

Show animated GIF

Try this:

// I suppose you have already set your JFrame 
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);

Found on this tutorial on how to display animated gif in java

Or live on youtube : https://youtu.be/_NEnhm9mgdE

How to completely uninstall kubernetes

use kubeadm reset command. this will un-configure the kubernetes cluster.

Input button target="_blank" isn't causing the link to load in a new window/tab

Just use the javascript window.open function with the second parameter at "_blank"

<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>

Count the number of occurrences of a character in a string in Javascript

s = 'dir/dir/dir/dir/'
for(i=l=0;i<s.length;i++)
if(s[i] == '/')
l++

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

.rar, .zip files MIME Type

I see many answer reporting for zip and rar the Media Types application/zip and application/x-rar-compressed, respectively.

While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed is a deprecated alias name and instead application/vnd.rar is the official one. So, right Media Types from IANA in 2020 are:

  1. zip: application/zip
  2. rar: application/vnd.rar

How to get JSON objects value if its name contains dots?

What you want is:

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.

How does one generate a random number in Apple's Swift language?

Example for random number in between 10 (0-9);

import UIKit

let randomNumber = Int(arc4random_uniform(10))

Very easy code - simple and short.

Error in contrasts when defining a linear model in R

If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

Capture screenshot of active window?

Here is a snippet to capture either the desktop or the active window. It has no reference to Windows Forms.

public class ScreenCapture
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }   

    [DllImport("user32.dll")]
    private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    public static Image CaptureDesktop()
    {
        return CaptureWindow(GetDesktopWindow());
    }

    public static Bitmap CaptureActiveWindow()
    {
        return CaptureWindow(GetForegroundWindow());
    }

    public static Bitmap CaptureWindow(IntPtr handle)
    {
        var rect = new Rect();
        GetWindowRect(handle, ref rect);
        var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
        var result = new Bitmap(bounds.Width, bounds.Height);

        using (var graphics = Graphics.FromImage(result))
        {
            graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }

        return result;
    }
}

How to capture the whole screen:

var image = ScreenCapture.CaptureDesktop();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

How to capture the active window:

var image = ScreenCapture.CaptureActiveWindow();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

Originally found here: http://www.snippetsource.net/Snippet/158/capture-screenshot-in-c

How to calculate age (in years) based on Date of Birth and getDate()

I've done a lot of thinking and searching about this and I have 3 solutions that

  • calculate age correctly
  • are short (mostly)
  • are (mostly) very understandable.

Here are testing values:

DECLARE @NOW DATETIME = '2013-07-04 23:59:59' 
DECLARE @DOB DATETIME = '1986-07-05' 

Solution 1: I found this approach in one js library. It's my favourite.

DATEDIFF(YY, @DOB, @NOW) - 
  CASE WHEN DATEADD(YY, DATEDIFF(YY, @DOB, @NOW), @DOB) > @NOW THEN 1 ELSE 0 END

It's actually adding difference in years to DOB and if it is bigger than current date then subtracts one year. Simple right? The only thing is that difference in years is duplicated here.

But if you don't need to use it inline you can write it like this:

DECLARE @AGE INT = DATEDIFF(YY, @DOB, @NOW)
IF DATEADD(YY, @AGE, @DOB) > @NOW
SET @AGE = @AGE - 1

Solution 2: This one I originally copied from @bacon-bits. It's the easiest to understand but a bit long.

DATEDIFF(YY, @DOB, @NOW) - 
  CASE WHEN MONTH(@DOB) > MONTH(@NOW) 
    OR MONTH(@DOB) = MONTH(@NOW) AND DAY(@DOB) > DAY(@NOW) 
  THEN 1 ELSE 0 END

It's basically calculating age as we humans do.


Solution 3: My friend refactored it into this:

DATEDIFF(YY, @DOB, @NOW) - 
  CEILING(0.5 * SIGN((MONTH(@DOB) - MONTH(@NOW)) * 50 + DAY(@DOB) - DAY(@NOW)))

This one is the shortest but it's most difficult to understand. 50 is just a weight so the day difference is only important when months are the same. SIGN function is for transforming whatever value it gets to -1, 0 or 1. CEILING(0.5 * is the same as Math.max(0, value) but there is no such thing in SQL.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

You can make the query using convert to varbinary – it’s very easy. Example:

Select * from your_table where convert(varbinary, your_column) = convert(varbinary, 'aBcD') 

How to change href attribute using JavaScript after opening the link in a new window?

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

function changeLink() {
    var link = document.getElementById("mylink");

    window.open(
      link.href,
      '_blank'
    );

    link.innerHTML = "facebook";
    link.setAttribute('href', "http://facebook.com");

    return false;
}

Improve SQL Server query performance on large tables

How is this possible? Without an index on the er101_upd_date_iso column how can a clustered index scan be used?

An index is a B-Tree where each leaf node is pointing to a 'bunch of rows'(called a 'Page' in SQL internal terminology), That is when the index is a non-clustered index.

Clustered index is a special case, in which the leaf nodes has the 'bunch of rows' (rather than pointing to them). that is why...

1) There can be only one clustered index on the table.

this also means the whole table is stored as the clustered index, that is why you started seeing index scan rather than a table scan.

2) An operation that utilizes clustered index is generally faster than a non-clustered index

Read more at http://msdn.microsoft.com/en-us/library/ms177443.aspx

For the problem you have, you should really consider adding this column to a index, as you said adding a new index (or a column to an existing index) increases INSERT/UPDATE costs. But it might be possible to remove some underutilized index (or a column from an existing index) to replace with 'er101_upd_date_iso'.

If index changes are not possible, i recommend adding a statistics on the column, it can fasten things up when the columns have some correlation with indexed columns

http://msdn.microsoft.com/en-us/library/ms188038.aspx

BTW, You will get much more help if you can post the table schema of ER101_ACCT_ORDER_DTL. and the existing indices too..., probably the query could be re-written to use some of them.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

It looks like a bug http://code.google.com/p/android/issues/detail?id=939.

Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          /> 

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp" 
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/> 

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

How to use Redirect in the new react-router-dom of Reactjs

The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:

<script>
  {
    localStorage.setItem("redirect", "/ansible/");
    location.href = "/";
  }
</script>

Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):

import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";

class App extends Component {
  render() {
    const redirect = localStorage.getItem("redirect");

    if(redirect) {
      localStorage.removeItem("redirect");
    }

    return (
      <Router>
        {redirect ?<Redirect to={redirect}/> : ""}
        <div className="App">
        ...
          <Link to="/">
            <li>Home</li>
          </Link>
          <Link to="/dev">
            <li>Development</li>
          </Link>
          <Link to="/wood">
            <li>Wood Working</li>
          </Link>
        ...
          <Route
            path="/"
            exact
            render={(props) => (
              <Home {...props} />
            )}
          />
          <Route
            path="/dev"
            render={(props) => (
              <Code {...props} />
            )}
          />
          <Route
            path="/wood"
            render={(props) => (
              <Wood {...props} />
            )}
          />
          <Route
            path="/ansible/"
            exact
            render={(props) => (
              <Ansible {...props} checked={this.state.checked} />
            )}
          />
          ...
      </Router>
    );
  }
}

export default App;

Actual usage: chizl.com

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

Why is there no Constant feature in Java?

What does const mean
First, realize that the semantics of a "const" keyword means different things to different people:

  • read-only reference - Java final semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable
  • readable-only reference - C const pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instance
  • immutable object - means the instance itself cannot be modified - applies to instance, so any non-const reference would not be allowed or could not be used to modify the instance
  • some combination of the the above?
  • others?

Why or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070

While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const include:

  • may have confusing semantics that may be misused and/or abused (see the What does const mean above)
  • may duplicate capability otherwise available (e.g. designing an immutable class, using an immutable interface)
  • may be feature creep, leading to a need for other semantic changes such as support for passing objects by value

Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.

How to print instances of a class using print()?

Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

Given this class definition:

class Test(object):
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def __str__(self):
        return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)

    def __repr__(self):
        return 'Test("%s","%s")' % (self._a, self._b)

Now, is easy to serialize instance of Test class:

x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print

y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print

So, running last piece of code, we'll get:

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

Human readable:  An instance of class Test with state: a=hello b=world
Object representation:  Test("hello","world")

But, as I said in my last comment: more info is just here!

Easiest way to convert int to string in C++

int i = 255; std::string s = std::to_string(i);

In c++, to_string() will create a string object of the integer value by representing the value as a sequence of characters.

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

Why is textarea filled with mysterious white spaces?

Basically it should be

<textarea>something here with no spaces in the begining</textarea>

If there are some predefined spaces lets say due to code formatting like below

<textarea>.......
....some_variable
</textarea>

The spaces shown by dots keeps on adding on each submit.

What is a Question Mark "?" and Colon ":" Operator Used for?

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4 since the condition is false it takes y value.

A question mark (?)
. The value to use if the condition is true

A colon (:)
. The value to use if the condition is false

Checking whether the pip is installed?

If you are on a linux machine running Python 2 you can run this commands:

1st make sure python 2 is installed:

python2 --version

2nd check to see if pip is installed:

pip --version

If you are running Python 3 you can run this command:

1st make sure python 3 is installed:

python3 --version

2nd check to see if pip3 is installed:

pip3 --version

If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):

Install pip for Python 2:

sudo apt install python-pip

Then verify if it is installed correctly:

pip --version

Install pip for Python 3:

sudo apt install python3-pip

Then verify if it is installed correctly:

pip3 --version

For more info see: https://itsfoss.com/install-pip-ubuntu/

UPDATE I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python and pip command alias's to python 3 with alias python=python3 is not recommended. Therefore I use the python3 and pip3 commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8.

Keep In Mind When you are going to use your package in the future you will want to use the pip or pip3 command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3 command and not pip like so, pip3 install Django==3.0.11.

Notice When running checking the packages version for python: $ python -m django --version and python3: $ python3 -m django --version, two different versions of django will show because I installed django v3.0.11 with pip3 and django v1.11.29 with pip.

how to apply click event listener to image in android

Try this example.

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<GridView
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/grid"
    android:background="#fff7ff"
    />

    </LinearLayout>

grid_single.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/grid_image"
        android:layout_width="60dp"
        android:layout_height="60dp"

        >
    </ImageView>

    <TextView
        android:id="@+id/grid_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textSize="9sp"
        android:textColor="#3a0fff">
    </TextView>

</LinearLayout>

CustomGrid.java:

package com.example.lalit.gridtest;

import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

public class CustomGrid extends BaseAdapter {
    private Context mContext;
    private final String[] web;
    private final int[] Imageid;

    public CustomGrid(Context c, String[] web, int[] Imageid) {
        mContext = c;
        this.Imageid = Imageid;
        this.web = web;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return web.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
            textView.setText(web[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

MainActivity.java:

package com.example.lalit.gridtest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    GridView grid;
    String[] web = {
            "Mom",
            "Mahendra",
            "Narayan",
            "Bhai",
            "Deepak",
            "Sanjay",
            "Navdeep",
            "Lovesh",


    };
    int[] imageId = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
        grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id){

                if (web[position].toString().equals("Mom")) {
                    try {
                        String uri ="te:"+ "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }


                    if (web[position].toString().equals("Mahendra")) {
                        try {
                            String uri = "tel:" + "**********";

                            Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                            startActivity(callIntent);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Your call has failed...",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }


                      if(web[position].toString().equals("Narayan")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


             }
                if(web[position].toString().equals("Bhai")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                if(web[position].toString().equals("Deepak")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }


                if(web[position].toString().equals("Sanjay")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Navdeep")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Lovesh")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                }



        });

    }

    }

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lalit.gridtest" >
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Update TextView Every Second

Extending @endian 's answer, you could use a thread and call a method to update the TextView. Below is some code I made up on the spot.

java.util.Date noteTS;
String time, date;
TextView tvTime, tvDate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.deskclock);

    tvTime = (TextView) findViewById(R.id.tvTime);
    tvDate = (TextView) findViewById(R.id.tvDate);

    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateTextView();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
}

private void updateTextView() {
    noteTS = Calendar.getInstance().getTime();

    String time = "hh:mm"; // 12:00
    tvTime.setText(DateFormat.format(time, noteTS));

    String date = "dd MMMMM yyyy"; // 01 January 2013
    tvDate.setText(DateFormat.format(date, noteTS));
}

HQL Hibernate INNER JOIN

You can do it without having to create a real Hibernate mapping. Try this:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team

Log exception with traceback

Here is a version that uses sys.excepthook

import traceback
import sys

logger = logging.getLogger()

def handle_excepthook(type, message, stack):
     logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')

sys.excepthook = handle_excepthook

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:

<ul>
  <li>...</li>
  <li>...</li>
  <li>...</li>
</ul>

Thanks.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

In PHP 7.0 it's now possible to use Null coalescing operator:

echo "My index value is: " . ($my_array["my_index"] ?? '');

Equals to:

echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');

PHP manual PHP 7.0

Android SQLite Example

The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

Select method of Range class failed via VBA

This worked for me.

RowCounter = Sheets(3).UsedRange.Rows.Count + 1

Sheets(1).Rows(rowNum).EntireRow.Copy
Sheets(3).Activate
Sheets(3).Cells(RowCounter, 1).Select
Sheets(3).Paste
Sheets(1).Activate

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

Bash: Strip trailing linebreak from output

There is also direct support for white space removal in Bash variable substitution:

testvar=$(wc -l < log.txt)
trailing_space_removed=${testvar%%[[:space:]]}
leading_space_removed=${testvar##[[:space:]]}

Confirm deletion using Bootstrap 3 modal box

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

_x000D_
_x000D_
   _x000D_
_x000D_
 $('button[name="remove_levels"]').on('click', function(e) {_x000D_
      var $form = $(this).closest('form');_x000D_
      e.preventDefault();_x000D_
      $('#confirm').modal({_x000D_
          backdrop: 'static',_x000D_
          keyboard: false_x000D_
      })_x000D_
      .on('click', '#delete', function(e) {_x000D_
          $form.trigger('submit');_x000D_
        });_x000D_
      $("#cancel").on('click',function(e){_x000D_
       e.preventDefault();_x000D_
       $('#confirm').modal.model('hide');_x000D_
      });_x000D_
    });
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
  <div class="modal-body">_x000D_
    Are you sure?_x000D_
  </div>_x000D_
  <div class="modal-footer">_x000D_
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get past the login page with Wget?

You can log in via browser and copy the needed headers afterwards:

screenshot

Use "Copy as cURL" in the Network tab of browser developer tools and replace curl's flag -H with wget's --header (and also --data with --post-data if needed).

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.

If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:

public class AllowCors : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext == null)
        {
            throw new ArgumentNullException("actionExecutedContext");
        }
        else
        {
            actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

Then just use it on your Controller action:

[AllowCors]
public IHttpActionResult Get()
{
    return Ok("value");
}

I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.

And of course it is simple to modify the above to allow only certain origins, methods etc.

How to set standard encoding in Visual Studio

Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents, named Save documents as Unicode when data cannot be saved in codepage. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.

Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.

How to enumerate an object's properties in Python?

for property, value in vars(theObject).items():
    print(property, ":", value)

Be aware that in some rare cases there's a __slots__ property, such classes often have no __dict__.

How to use pip with Python 3.x alongside Python 2.x

First, install Python 3 pip using:

sudo apt-get install python3-pip

Then, to use Python 3 pip use:

pip3 install <module-name>

For Python 2 pip use:

pip install <module-name>

How to send HTTP request in java?

You can use java.net.HttpUrlConnection.

Example (from here), with improvements. Included in case of link rot:

public static String executePost(String targetURL, String urlParameters) {
  HttpURLConnection connection = null;

  try {
    //Create connection
    URL url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", 
        Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");  

    connection.setUseCaches(false);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
    String line;
    while ((line = rd.readLine()) != null) {
      response.append(line);
      response.append('\r');
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Private class declaration

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

This is a really unclear and unhelpful error message. After much trial and error I found that LocalDateTime will give the above error if you do not attempt to parse a time. By using LocalDate instead, it works without erroring.

This is poorly documented and the related exception is very unhelpful.

Log.INFO vs. Log.DEBUG

Debug: fine-grained statements concerning program state, typically used for debugging;

Info: informational statements concerning program state, representing program events or behavior tracking;

Warn: statements that describe potentially harmful events or states in the program;

Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;

Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.

Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

What is the difference between class and instance methods?

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

How do I delete files programmatically on Android?

Why don't you test this with this code:

File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + uri.getPath());
    } else {
        System.out.println("file not Deleted :" + uri.getPath());
    }
}

I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.

So in your case you could try:

File file = new File(uri.getPath());
file.delete();
if(file.exists()){
      file.getCanonicalFile().delete();
      if(file.exists()){
           getApplicationContext().deleteFile(file.getName());
      }
}

However I think that's a little overkill.

You added a comment that you are using an external directory rather than a uri. So instead you should add something like:

String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918"); 

Then try to delete the file.

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

Fatal error: Call to undefined function mb_strlen()

This worked for me on Debian stretch

sudo apt-get update
sudo apt install php-mbstring
service apache2 restart

Two decimal places using printf( )

For %d part refer to this How does this program work? and for decimal places use %.2f

What special characters must be escaped in regular expressions?

Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with.

For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes:

.^$*+?()[{\|

and these inside character classes:

^-]\

For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE):

.^$*+?()[{\|

Escaping any other characters is an error with POSIX ERE.

Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.:

[]^-]

In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning:

.^$*[\

Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs.

Inside character classes, BREs follow the same rule as EREs.

If all this makes your head spin, grab a copy of RegexBuddy. On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.

How to create a Java / Maven project that works in Visual Studio Code?

I surprise no one had mentioned this possible easy approach in visual studio code.

Install VS Code and Apache maven ( just as mentioned by @Steve Chambers)

After installing this extension vscode:extension/vscjava.vscode-java-pack

In the java overview page , there is a an option which reads 'Create Maven Project' which further takes to a simple wizard to generate maven project.

Its pretty quick which is intutitive enough, even newbies can very well start with a Maven project.

what is the difference between OLE DB and ODBC data sources?

I'm not sure of all the details, but my understanding is that OLE DB and ODBC are two APIs that are available for connecting to various types of databases without having to deal with all the implementation specific details of each. According to the Wikipedia article on OLE DB, OLE DB is Microsoft's successor to ODBC, and provides some features that you might not be able to do with ODBC such as accessing spreadsheets as database sources.

How can you remove all documents from a collection with Mongoose?

DateTime.remove({}, callback) The empty object will match all of them.

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

How to do a Jquery Callback after form submit?

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • grab all necessary values from the form
  • fire off an HTTP request
  • handle the response to the request

First, you'll have to cancel the form submit action like so:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

Package doesn't exist error in intelliJ

Here is a solution worked for me: Disable the "Use --release option for cross-compilation like the following in intellij idea: got Settings -> Build,Execution,Deployment -> Compiler -> Java Compiler and disable:

Use '--release' option for cross compilation(java 9 and later)

How to parse XML using vba

This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.

You can find more on MSXML2.DOMDocument at the following sites:

Py_Initialize fails - unable to load the file system codec

For me this happened when I updated Python 64 bit from 3.6.4 to 3.6.5. It threw some error like "unable to extract python.dll. Do you have permissions."

Pycharm also failed to load interpreter, even though I reloaded it in settings. Running python command gave same error, with and without administrator mode.

Reason

There was error in installation of Python, include folder in python installation directory C:\Users\USERNAME\AppData\Local\Programs\Python\Python36 was missing

Reinstalling Python also dint solve the issue.(Not removal and install)

Solution

Uninstall Python and Install of Python again.

Because running installer was just extracting same files excluding include folder

How do I create a message box with "Yes", "No" choices and a DialogResult?

The MessageBox does produce a DialogResults

DialogResult r = MessageBox.Show("Some question here");

You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx

How do I include image files in Django templates?

If your file is a model field within a model, you can also use ".url" in your template tag to get the image.

For example.

If this is your model:

class Foo(models.Model):
    foo = models.TextField()
    bar = models.FileField(upload_to="foo-pictures", blank = True)  

Pass the model in context in your views.

return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)})

In your template you could have:

<img src = "{{foo.bar.url}}">

How to fix request failed on channel 0

Should a person find themselves reading this QA while they are trying to ssh into a NetGear ReadyNAS device, be sure that the "rsync only" checkbox is unchecked in the dialog box for the ssh service in the admin interface.

Can linux cat command be used for writing text to file?

The Solution to your problem is :

echo " Some Text Goes Here " > filename.txt

But you can use cat command if you want to redirect the output of a file to some other file or if you want to append the output of a file to another file :

cat filename > newfile -- To redirect output of filename to newfile

cat filename >> newfile -- To append the output of filename to newfile

How do I get the HTTP status code with jQuery?

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

Build Eclipse Java Project from Command Line

This question contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.

Run PHP Task Asynchronously

Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.

If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.

How to read attribute value from XmlNode in C#?

To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:

if (node.Attributes != null)
{
   var nameAttribute = node.Attributes["Name"];
   if (nameAttribute != null) 
      return nameAttribute.Value;

   throw new InvalidOperationException("Node 'Name' not found.");
}

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How to fix Python indentation

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type

:ret

all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.


If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

How to get JS variable to retain value after page refresh?

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage

Ex: using localStorage and cookies library

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

MAMP mysql server won't start. No mysql processes are running

rm /Applications/MAMP/db/mysql56/*

Works fine, but then it shows "No database found" in phpmyadmin although there are databases, so my drupal gave me errors because of this.

All I need to do is simply remove two files ib_logfile0 and ib_logfile1 from /Applications/MAMP/db/mysql56/ and that did the trick for me.

How do you convert a byte array to a hexadecimal string in C?

Slightly modified Yannith version. It is just I like to have it as a return value

_x000D_
_x000D_
typedef struct {_x000D_
   size_t len;_x000D_
   uint8_t *bytes;_x000D_
} vdata;_x000D_
_x000D_
char* vdata_get_hex(const vdata data)_x000D_
{_x000D_
   char hex_str[]= "0123456789abcdef";_x000D_
_x000D_
   char* out;_x000D_
   out = (char *)malloc(data.len * 2 + 1);_x000D_
   (out)[data.len * 2] = 0;_x000D_
   _x000D_
   if (!data.len) return NULL;_x000D_
   _x000D_
   for (size_t i = 0; i < data.len; i++) {_x000D_
      (out)[i * 2 + 0] = hex_str[(data.bytes[i] >> 4) & 0x0F];_x000D_
      (out)[i * 2 + 1] = hex_str[(data.bytes[i]     ) & 0x0F];_x000D_
   }_x000D_
   return out;_x000D_
}
_x000D_
_x000D_
_x000D_

How to check if an email address is real or valid using PHP

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>

Inserting HTML elements with JavaScript

Have a look at insertAdjacentHTML

var element = document.getElementById("one");
var newElement = '<div id="two">two</div>'
element.insertAdjacentHTML( 'afterend', newElement )
// new DOM structure: <div id="one">one</div><div id="two">two</div>

position is the position relative to the element you are inserting adjacent to:

'beforebegin' Before the element itself

'afterbegin' Just inside the element, before its first child

'beforeend' Just inside the element, after its last child

'afterend' After the element itself

How to extract code of .apk file which is not working?

step 1:

enter image description hereDownload dex2jar here. Create a java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .

Copy apk file into java project

Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files

step 2: Download java decompiler here

Android Studio Gradle Already disposed Module

below solution works for me

  1. Delete all .iml files
  2. Rebuild project

How to get the full url in Express?

async function (request, response, next) {
  const url = request.rawHeaders[9] + request.originalUrl;
  //or
  const url = request.headers.host + request.originalUrl;
}

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

How to reload a div without reloading the entire page?

$("#div_element").load('script.php');

demo: http://sandbox.phpcode.eu/g/2ecbe/3

whole code:

<div id="submit">ajax</div> 
<div id="div_element"></div> 
<script> 
$('#submit').click(function(event){ 
   $("#div_element").load('script.php?html=some_arguments');  

}); 
</script> 

How can I pass a parameter to a setTimeout() callback?

How i resolved this stage ?

just like that :

setTimeout((function(_deepFunction ,_deepData){
    var _deepResultFunction = function _deepResultFunction(){
          _deepFunction(_deepData);
    };
    return _deepResultFunction;
})(fromOuterFunction, fromOuterData ) , 1000  );

setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !

Maybe you can improve this part :

_deepFunction(_deepData);

// change to something like :
_deepFunction.apply(contextFromParams , args); 

I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.

a sample test :

myDelay_function = function(fn , params , ctxt , _time){
setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                //_deepFunction(_deepData);
                _deepFunction.call(  _deepCtxt , _deepData);
            };
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 
};

// the function to be used :
myFunc = function(param){ console.log(param + this.name) }
// note that we call this.name

// a context object :
myObjet = {
    id : "myId" , 
    name : "myName"
}

// setting a parmeter
myParamter = "I am the outer parameter : ";

//and now let's make the call :
myDelay_function(myFunc , myParamter  , myObjet , 1000)

// this will produce this result on the console line :
// I am the outer parameter : myName

Maybe you can change the signature to make it more complient :

myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                //_deepFunction(_deepData);
                _deepFunction.apply(  _deepCtxt , _deepData);
            };
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 
};

// and try again :
for(var i=0; i<10; i++){
   myNass_setTimeOut(console.log ,1000 , [i] , console)
}

And finaly to answer the original question :

 myNass_setTimeOut( postinsql, 4000, topicId );

Hope it can help !

ps : sorry but english it's not my mother tongue !

Simulating ENTER keypress in bash script

echo -ne '\n' | <yourfinecommandhere>

or taking advantage of the implicit newline that echo generates (thanks Marcin)

echo | <yourfinecommandhere>

Now we can simply use the --sk option:

--sk, --skip-keypress Don't wait for a keypress after each test

i.e. sudo rkhunter --sk --checkall

How to create named and latest tag in Docker?

ID=$(docker build -t creack/node .) doesn't work for me since ID will contain the output from the build.

SO I'm using this small BASH script:

#!/bin/bash

set -o pipefail

IMAGE=...your image name...
VERSION=...the version...

docker build -t ${IMAGE}:${VERSION} . | tee build.log || exit 1
ID=$(tail -1 build.log | awk '{print $3;}')
docker tag $ID ${IMAGE}:latest

docker images | grep ${IMAGE}

docker run --rm ${IMAGE}:latest /opt/java7/bin/java -version

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Bootstrap 3 collapsed menu doesn't close on click

 $(function(){ 
    var navMain = $("#your id");
    navMain.on("click", "a", null, function () {
      navMain.collapse('hide');
    });
});

Switch on Enum in Java

Article on Programming.Guide: Switch on enum


enum MyEnum { CONST_ONE, CONST_TWO }

class Test {
        public static void main(String[] args) {
            MyEnum e = MyEnum.CONST_ONE;

            switch (e) {
                case CONST_ONE: System.out.println(1); break;
                case CONST_TWO: System.out.println(2); break;
            }
        }
    }

Switches for strings are implemented in Java 7.

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').click(function(){saveQuestion(id)});

How can I get the current page's full URL on a Windows/IIS server?

Maybe, because you are under IIS,

$_SERVER['PATH_INFO']

is what you want, based on the URLs you used to explain.

For Apache, you'd use $_SERVER['REQUEST_URI'].

Create HTML table using Javascript

This beautiful code here creates a table with each td having array values. Not my code, but it helped me!

var rows = 6, cols = 7;

for(var i = 0; i < rows; i++) {
  $('table').append('<tr></tr>');
  for(var j = 0; j < cols; j++) {
    $('table').find('tr').eq(i).append('<td></td>');
    $('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
  }
}

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(model => model.IsActive, new { readonly= "readonly" })

This is just fine for text box. However, if you try to do same for the checkbox then try using this if you are using it:

@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })

But don't use disable, because disable always sends the default value false to the server - either it was in the checked or unchecked state. And the readonly does not work for checkbox and radio button. readonly only works for text fields.

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

android:drawableLeft margin and/or padding

android:drawablePadding will only create a padding gap between the text and the drawable if the button is small enough to squish the 2 together. If your button is wider than the combined width (for drawableLeft/drawableRight) or height (for drawableTop/drawableBottom) then drawablePadding doesn't do anything.

I'm struggling with this right now as well. My buttons are quite wide, and the icon is hanging on the left edge of the button and the text is centered in the middle. My only way to get around this for now has been to bake in a margin on the drawable by adding blank pixels to the left edge of the canvas with photoshop. Not ideal, and not really recommended either. But thats my stop-gap solution for now, short of rebuilding TextView/Button.

jQuery .val() vs .attr("value")

jquery - Get the value in an input text box

<script type="text/javascript"> 

jQuery(document).ready(function(){

var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")

jQuery('input[name=your-p-name]').val(classValues);

//alert(classValues);

});

</script>

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

How can I get the current class of a div with jQuery?

var className=$('selector').attr('class');

or

var className=$(this).attr('class');

the classname of the current element

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

paint() and repaint() in Java

Difference between Paint() and Repaint() method

Paint():

This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.

Repaint():

This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.

How to float 3 divs side by side using CSS?

But does it work in Chrome?

Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11

Click for JS Fiddle

HTML

<div class="stack">
    <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
    </div>
        <div class="row">
        <div class="col">
            One
        </div>
        <div class="col">
            Two
        </div>
                    <div class="col">
            Three
        </div>
    </div>
</div>

CSS

.stack .row { 
clear:both;

}
.stack .row  .col    {
    float:left;
      border:1px solid;

}

How do I loop through rows with a data reader in C#?

There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        string value1 = rdr.GetString(0);
        string value2 = rdr.GetString(1);
        string value3 = rdr.GetString(2);
    }
}

What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....

How to set initial value and auto increment in MySQL?

MySQL Workbench

If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.

When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.

Don't forget to hit "Apply" when you are done with all changes.

PhpMyAdmin:

If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

How to quickly check if folder is empty (.NET)?

If you don't mind leaving pure C# and going for WinApi calls, then you might want to consider the PathIsDirectoryEmpty() function. According to the MSDN, the function:

Returns TRUE if pszPath is an empty directory. Returns FALSE if pszPath is not a directory, or if it contains at least one file other than "." or "..".

That seems to be a function which does exactly what you want, so it is probably well optimised for that task (although I haven't tested that).

To call it from C#, the pinvoke.net site should help you. (Unfortunately, it doesn't describe this certain function yet, but you should be able to find some functions with similar arguments and return type there and use them as the basis for your call. If you look again into the MSDN, it says that the DLL to import from is shlwapi.dll)

How do I find the length/number of items present for an array?

Do you mean how long is the array itself, or how many customerids are in it?

Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).

But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"

C can't tell you this. You will need to keep a separate variable, int numCustIds (for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.

Select data from "show tables" MySQL query

Have you looked into querying INFORMATION_SCHEMA.Tables? As in

SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls, 
    ic.ordinal_position as OrdinalPos, 
    ic.column_default as ColDefault, 
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

you have to include two more jar files.

xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.

Note: It is required for the files with .xlsx formats only, not for just .xlt formats.

How to activate JMX on my JVM for access with jconsole?

Running in a Docker container introduced a whole slew of additional problems for connecting so hopefully this helps someone. I ended up needed to add the following options which I'll explain below:

-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=${DOCKER_HOST_IP}
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.rmi.port=9998

DOCKER_HOST_IP

Unlike using jconsole locally, you have to advertise a different IP than you'll probably see from within the container. You'll need to replace ${DOCKER_HOST_IP} with the externally resolvable IP (DNS Name) of your Docker host.

JMX Remote & RMI Ports

It looks like JMX also requires access to a remote management interface (jstat) that uses a different port to transfer some data when arbitrating the connection. I didn't see anywhere immediately obvious in jconsole to set this value. In the linked article the process was:

  • Try and connect from jconsole with logging enabled
  • Fail
  • Figure out which port jconsole attempted to use
  • Use iptables/firewall rules as necessary to allow that port to connect

While that works, it's certainly not an automatable solution. I opted for an upgrade from jconsole to VisualVM since it let's you to explicitly specify the port on which jstatd is running. In VisualVM, add a New Remote Host and update it with values that correlate to the ones specified above:

Add Remote Host

Then right-click the new Remote Host Connection and Add JMX Connection...

Add JMX Connection

Don't forget to check the checkbox for Do not require SSL connection. Hopefully, that should allow you to connect.

Pass connection string to code-first DbContext

In your DbContext, create a default constructor for your DbContext and inherit the base like this:

    public myDbContext()
        : base("MyConnectionString")  // connectionstring name define in your web.config
    {
    }