Programs & Examples On #Java interop

Failed to open/create the internal network Vagrant on Windows10

I have worked around for a while, all you need to do is open VirtualBox,

File > Preferences / Network > Host-Only Networks

You will see VirtualBox Host-Only Ethernet Adapter

click on it, and edit.

My IP settings for vagrant VM was 192.168.10.10, you should edit up to your VM IP

Here is my adapter settings;

Adapter Settings

DHCP Server Settings

Difference between "on-heap" and "off-heap"

The on-heap store refers to objects that will be present in the Java heap (and also subject to GC). On the other hand, the off-heap store refers to (serialized) objects that are managed by EHCache, but stored outside the heap (and also not subject to GC). As the off-heap store continues to be managed in memory, it is slightly slower than the on-heap store, but still faster than the disk store.

The internal details involved in management and usage of the off-heap store aren't very evident in the link posted in the question, so it would be wise to check out the details of Terracotta BigMemory, which is used to manage the off-disk store. BigMemory (the off-heap store) is to be used to avoid the overhead of GC on a heap that is several Megabytes or Gigabytes large. BigMemory uses the memory address space of the JVM process, via direct ByteBuffers that are not subject to GC unlike other native Java objects.

Check if a row exists using old mysql_* API

This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName is Assigned, otherwise it's Available.

function checkLectureStatus($lectureName)
{
    $con = connectvar();
    mysql_select_db("mydatabase", $con);
    $result = mysql_query(
        "SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");

    if(mysql_fetch_array($result) !== false)
        return 'Assigned';
    return 'Available';
}

Getting Serial Port Information

There is a post about this same issue on MSDN:

Getting more information about a serial port in C#

Hi Ravenb,

We can't get the information through the SerialPort type. I don't know why you need this info in your application. However, there's a solved thread with the same question as you. You can check out the code there, and see if it can help you.

If you have any further problem, please feel free to let me know.

Best regards, Bruce Zhou

The link in that post goes to this one:

How to get more info about port using System.IO.Ports.SerialPort

You can probably get this info from a WMI query. Check out this tool to help you find the right code. Why would you care though? This is just a detail for a USB emulator, normal serial ports won't have this. A serial port is simply know by "COMx", nothing more.

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

How to set entire application in portrait mode only?

Adding <preference name="orientation" value="portrait" /> under <widget> in my config.xml worked for me.

(The other solutions either didn't work on my device, were overwritten during building or gave deprecation errors during the build process.)

Submit form without page reloading

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>

How to execute two mysql queries as one in PHP/MYSQL?

Like this:

$result1 = mysql_query($query1);
$result2 = mysql_query($query2);

// do something with the 2 result sets...

if ($result1)
    mysql_free_result($result1);

if ($result2)
    mysql_free_result($result2);

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

python: Change the scripts working directory to the script's own directory

This will change your current working directory to so that opening relative paths will work:

import os
os.chdir("/home/udi/foo")

However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path functions:

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.

How to query a CLOB column in Oracle

Another option is to create a function and call that function everytime you need to select clob column.

create or replace function clob_to_char_func
(clob_column in CLOB,
 for_how_many_bytes in NUMBER,
 from_which_byte in NUMBER)
return VARCHAR2
is
begin
Return substrb(dbms_lob.substr(clob_column
                            ,for_how_many_bytes
                            ,from_which_byte)
            ,1
            ,for_how_many_bytes);
end;

and call that function as;

SELECT tocharvalue, clob_to_char_func(tocharvalue, 1, 9999)
FROM (SELECT clob_column AS tocharvalue FROM table_name);

How do I decompile a .NET EXE into readable C# source code?

Telerik JustDecompile is free and has a feature to create projects from .NET assemblies.

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

open existing java project in eclipse

If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.

Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.

Associating enums with strings in C#

A small tweak to Glennular Extension method, so you could use the extension on other things than just ENUM's;

using System;
using System.ComponentModel;
namespace Extensions {
    public static class T_Extensions {
        /// <summary>
        /// Gets the Description Attribute Value
        /// </summary>
        /// <typeparam name="T">Entity Type</typeparam>
        /// <param name="val">Variable</param>
        /// <returns>The value of the Description Attribute or an Empty String</returns>
        public static string Description<T>(this T t) {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])t.GetType().GetField(t.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }
    }
}

Or Using Linq

using System;
using System.ComponentModel;
using System.Linq;

namespace Extensions {


public static class T_Extensions {
        public static string Description<T>(this T t) =>
            ((DescriptionAttribute[])t
            ?.GetType()
            ?.GetField(t?.ToString())
            ?.GetCustomAttributes(typeof(DescriptionAttribute), false))
            ?.Select(a => a?.Description)
            ?.FirstOrDefault() 
            ?? string.Empty;  
    }
}

Can you create nested WITH clauses for Common Table Expressions?

we can create nested cte.please see the below cte in example

;with cte_data as 
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)

select * from cte_data,cte_data1

How to open in default browser in C#

After researching a lot I feel most of the given answer will not work with dotnet core. 1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core

2.It will work but it will block the new window opening in case default browser is chrome

 myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();

Below is the simplest and will work in all the scenarios.

Process.Start("explorer", url);

unsigned int vs. size_t

Type size_t must be big enough to store the size of any possible object. Unsigned int doesn't have to satisfy that condition.

For example in 64 bit systems int and unsigned int may be 32 bit wide, but size_t must be big enough to store numbers bigger than 4G

Disable text input history

<input type="text" autocomplete="off" />

What does "The APR based Apache Tomcat Native library was not found" mean?

I just went through this and configured it with the following:

Ubuntu 16.04

Tomcat 8.5.9

Apache2.4.25

APR 1.5.2

Tomcat-native 1.2.10

Java 8

These are the steps i used based on the older posts here:

Install package

sudo apt-get update
sudo apt-get install libtcnative-1

Verify these packages are installed

sudo apt-get install make 
sudo apt-get install gcc
sudo apt-get install openssl

Install package

sudo apt-get install libssl-dev

Install and compile Apache APR

cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install

verify installation

cd /usr/local/apr/lib/
ls 

you should see the compiled file as

libapr-1.la

Download and install Tomcat Native source package

cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native

verify JAVA_HOME

sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install

Edit the /opt/tomcat/bin/setenv.sh file with following line:

sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

restart tomcat

sudo service tomcat restart

SQLite in Android How to update a specific row

Simple way:

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

Boolean vs boolean in Java

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.

Limit characters displayed in span

Yes, sort of.

You can explicitly size a container using units relative to font-size:

  • 1em = 'the horizontal width of the letter m'
  • 1ex = 'the vertical height of the letter x'
  • 1ch = 'the horizontal width of the number 0'

In addition you can use a few CSS properties such as overflow:hidden; white-space:nowrap; text-overflow:ellipsis; to help limit the number as well.

Cannot ignore .idea/workspace.xml - keeps popping up

I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:

mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea 
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea

After than make sure to ignore .idea in your .gitignore

Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.

Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Pagination on a list using ng-repeat

Here is a demo code where there is pagination + Filtering with AngularJS :

https://codepen.io/lamjaguar/pen/yOrVym

JS :

var app=angular.module('myApp', []);

// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html

app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    $scope.q = '';

    $scope.getData = function () {
      // needed for the pagination calc
      // https://docs.angularjs.org/api/ng/filter/filter
      return $filter('filter')($scope.data, $scope.q)
     /* 
       // manual filter
       // if u used this, remove the filter from html, remove above line and replace data with getData()

        var arr = [];
        if($scope.q == '') {
            arr = $scope.data;
        } else {
            for(var ea in $scope.data) {
                if($scope.data[ea].indexOf($scope.q) > -1) {
                    arr.push( $scope.data[ea] );
                }
            }
        }
        return arr;
       */
    }

    $scope.numberOfPages=function(){
        return Math.ceil($scope.getData().length/$scope.pageSize);                
    }

    for (var i=0; i<65; i++) {
        $scope.data.push("Item "+i);
    }
  // A watch to bring us back to the 
  // first pagination after each 
  // filtering
$scope.$watch('q', function(newValue,oldValue){             if(oldValue!=newValue){
      $scope.currentPage = 0;
  }
},true);
}]);

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

HTML :

<div ng-app="myApp" ng-controller="MyCtrl">
  <input ng-model="q" id="search" class="form-control" placeholder="Filter text">
  <select ng-model="pageSize" id="pageSize" class="form-control">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
     </select>
  <ul>
    <li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
      {{item}}
    </li>
  </ul>
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button> {{currentPage+1}}/{{numberOfPages()}}
  <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
    </button>
</div>

How do you change the value inside of a textfield flutter?

If you simply want to replace the entire text inside the text editing controller, then the other answers here work. However, if you want to programmatically insert, replace a selection, or delete, then you need to have a little more code.

Making your own custom keyboard is one use case for this. All of the inserts and deletions below are done programmatically:

enter image description here

Inserting text

The _controller here is a TextEditingController for the TextField.

void _insertText(String myText) {
  final text = _controller.text;
  final textSelection = _controller.selection;
  final newText = text.replaceRange(
    textSelection.start,
    textSelection.end,
    myText,
  );
  final myTextLength = myText.length;
  _controller.text = newText;
  _controller.selection = textSelection.copyWith(
    baseOffset: textSelection.start + myTextLength,
    extentOffset: textSelection.start + myTextLength,
  );
}

Thanks to this Stack Overflow answer for help with this.

Deleting text

There are a few different situations to think about:

  1. There is a selection (delete the selection)
  2. The cursor is at the beginning (don’t do anything)
  3. Anything else (delete the previous character)

Here is the implementation:

void _backspace() {
  final text = _controller.text;
  final textSelection = _controller.selection;
  final selectionLength = textSelection.end - textSelection.start;

  // There is a selection.
  if (selectionLength > 0) {
    final newText = text.replaceRange(
      textSelection.start,
      textSelection.end,
      '',
    );
    _controller.text = newText;
    _controller.selection = textSelection.copyWith(
      baseOffset: textSelection.start,
      extentOffset: textSelection.start,
    );
    return;
  }

  // The cursor is at the beginning.
  if (textSelection.start == 0) {
    return;
  }

  // Delete the previous character
  final newStart = textSelection.start - 1;
  final newEnd = textSelection.start;
  final newText = text.replaceRange(
    newStart,
    newEnd,
    '',
  );
  _controller.text = newText;
  _controller.selection = textSelection.copyWith(
    baseOffset: newStart,
    extentOffset: newStart,
  );
}

Full code

You can find the full code and more explanation in my article Custom In-App Keyboard in Flutter.

How can I find out the current route in Rails?

You can do this

Rails.application.routes.recognize_path "/your/path"

It works for me in rails 3.1.0.rc4

Javascript - Track mouse position

onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}

Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.

Add & delete view from Layout

This is the best way

LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them 
lp.removeViewAt(0); // and so on

If you have xml layout then no need to add dynamically.just call

lp.removeViewAt(0);

What should a JSON service return on failure / error

For server/protocol errors I would try to be as REST/HTTP as possible (Compare this with you typing in URL's in your browser):

  • a non existing item is called (/persons/{non-existing-id-here}). Return a 404.
  • an unexpected error on the server (code bug) occured. Return a 500.
  • the client user is not authorised to get the resource. Return a 401.

For domain/business logic specific errors I would say the protocol is used in the right way and there's no server internal error, so respond with an error JSON/XML object or whatever you prefer to describe your data with (Compare this with you filling in forms on a website):

  • a user wants to change its account name but the user did not yet verify its account by clicking a link in an email which was sent to the user. Return {"error":"Account not verified"} or whatever.
  • a user wants to order a book, but the book was sold (state changed in DB) and can't be ordered anymore. Return {"error":"Book already sold"}.

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

How do I download NLTK data?

You may try:

>> $ import nltk
>> $ nltk.download_shell()
>> $ d
>> $ *name of the package*

happy nlp'ing.

Access-control-allow-origin with multiple domains

After reading every answer and trying them, none of them helped me. What I found while searching elsewhere is that you can create a custom attribute that you can then add to your controller. It overwrites the EnableCors ones and add the whitelisted domains in it.

This solution is working well because it lets you have the whitelisted domains in the webconfig (appsettings) instead of harcoding them in the EnableCors attribute on your controller.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// <summary>
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// </summary>
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// <summary>
    /// Enables Cross Origin
    /// </summary>
    /// <param name="appSettingKey">AppSetting key that defines valid origins</param>
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// <summary>
    /// Build Cors policy
    /// </summary>
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection<string> current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List<string>(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

I found this guide online and it worked like a charm :

http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support

I thought i'd drop that here for anyone in need.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Not sure if this solution works for you or not but just want to heads you up on compiler and build tools version compatibility issues.

This could be because of Java and Gradle version mismatch.

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Gradle 4.4 is compatible with only Java 7 and 8. So, point your global variable JAVA_HOME to Java 7 or 8.

In mac, add below line to your ~/.bash_profile

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

You can have multiple java versions. Just change the JAVA_HOME path based on need. You can do it easily, check this

How to get the current loop index when using Iterator?

just do something like this:

        ListIterator<String> it = list1.listIterator();
        int index = -1;
        while (it.hasNext()) {
            index++;
            String value = it.next();
            //At this point the index can be checked for the current element.

        }

Should I write script in the body or the head of the html?

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

Sending commands and strings to Terminal.app with Applescript

The last example get errors under 10.6.8 (Build 10K549) caused by the keyword "pause".

Replacing it by the word "wait" makes it work:

tell application "Terminal"
    activate
    my execCmd("ssh me@localhost", 1)
    my execCmd("myPassw0rd", 0)
    my execCmd("ls", 2)
    my execCmd("exit", 0)
end tell

on execCmd(cmd, wait)
    tell application "System Events"
       tell application process "Terminal"
          set frontmost to true
          keystroke cmd
          keystroke return
       end tell
    end tell

    delay wait
end execCmd

What does %w(array) mean?

Excerpted from the documentation for Percent Strings at http://ruby-doc.org/core/doc/syntax/literals_rdoc.html#label-Percent+Strings:

Besides %(...) which creates a String, the % may create other types of object. As with strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

These are the types of percent strings in ruby:
...
%w: Array of Strings

How can I capitalize the first letter of each word in a string?

In case you want to downsize

# Assuming you are opening a new file
with open(input_file) as file:
    lines = [x for x in reader(file) if x]

# for loop to parse the file by line
for line in lines:
    name = [x.strip().lower() for x in line if x]
    print(name) # Check the result

Escape text for HTML

You can use actual html tags <xmp> and </xmp> to output the string as is to show all of the tags in between the xmp tags.

Or you can also use on the server Server.UrlEncode or HttpUtility.HtmlEncode.

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Extracting extension from filename in Python

def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Any way to Invoke a private method?

One more variant is using very powerfull JOOR library https://github.com/jOOQ/jOOR

MyObject myObject = new MyObject()
on(myObject).get("privateField");  

It allows to modify any fields like final static constants and call yne protected methods without specifying concrete class in the inheritance hierarhy

<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
     <groupId>org.jooq</groupId>
     <artifactId>joor-java-8</artifactId>
     <version>0.9.7</version>
</dependency>

Reload browser window after POST without prompting user to resend POST data

What you probably need to do is redirect the user after the POST / Form Handler script has been ran.

In PHP this is done like so...

<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>

... this should allow you to refresh the page without getting that "Send Data Again" warning.

You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)

TSQL DATETIME ISO 8601

You technically have two options when speaking of ISO dates.

In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd or y-m-d. Which are both valid ISO formats.

Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

Because of this, your safest bet is to persist/filter based on the always netural ymd format.

The code:

select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)

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

Set -Dspring.profiles.active=local under program arguments.

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Programmatically Add CenterX/CenterY Constraints

A solution for me was to create a UILabel and add it to the UIButton as a subview. Finally I added a constraint to center it within the button.

UILabel * myTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
myTextLabel.text = @"Some Text";
myTextLabel.translatesAutoresizingMaskIntoConstraints = false;

[myButton addSubView:myTextLabel];

// Add Constraints
[[myTextLabel centerYAnchor] constraintEqualToAnchor:myButton.centerYAnchor].active = true;
[[myTextLabel centerXAnchor] constraintEqualToAnchor:myButton.centerXAnchor].active = true; 

How do I select an entire row which has the largest ID in the table?

One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.

Where is Developer Command Prompt for VS2013?

I'm using VS 2012, so I navigated to "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 2012\Visual Studio Tools" and ran as administrator this "Developer Command Prompt for VS2012" shortcut. In command shell I pasted the suggested

aspnet_regiis -i

and as I suspected this did not yield any success on Windows 10: enter image description here

So all I needed to do was "Turn Windows Features On/Off" at Control Panel and restart my machine to effect the changes. That did resolve the issue. Thanks.

Custom method names in ASP.NET Web API

See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Passing a 2D array to a C++ function

We can use several ways to pass a 2D array to a function:

  • Using single pointer we have to typecast the 2D array.

     #include<bits/stdc++.h>
     using namespace std;
    
    
     void func(int *arr, int m, int n)
     {
         for (int i=0; i<m; i++)
         {
            for (int j=0; j<n; j++)
            {
               cout<<*((arr+i*n) + j)<<" ";
            }
            cout<<endl;
         }
     }
    
     int main()
     {
         int m = 3, n = 3;
         int arr[m][n] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
         func((int *)arr, m, n);
         return 0;
     }
    
  • Using double pointer In this way, we also typecast the 2d array

     #include<bits/stdc++.h>
     using namespace std;
    
    void func(int **arr, int row, int col)
    {
       for (int i=0; i<row; i++)
       {
          for(int j=0 ; j<col; j++)
          {
            cout<<arr[i][j]<<" ";
          }
          printf("\n");
       }
    }
    
    int main()
    {
      int row, colum;
      cin>>row>>colum;
      int** arr = new int*[row];
    
      for(int i=0; i<row; i++)
      {
         arr[i] = new int[colum];
      }
    
      for(int i=0; i<row; i++)
      {
          for(int j=0; j<colum; j++)
          {
             cin>>arr[i][j];
          }
      }
      func(arr, row, colum);
    
      return 0;
    }
    

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I imported the project as general project from git repository.

  • Deleted .settings, .project and .classpath in project's folder
  • Configure -> Convert to Maven Project. Only this solved the problem in my case.

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I too had to face the same problem. This worked for me. Right click and run as admin than run usual command to install. But first run update command to update the pip

python -m pip install --upgrade pip

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem because I had a typo in my template near [(ngModel)]]. Extra bracket. Example:

<input id="descr" name="descr" type="text" required class="form-control width-half"
      [ngClass]="{'is-invalid': descr.dirty && !descr.valid}" maxlength="16" [(ngModel)]]="category.descr"
      [disabled]="isDescrReadOnly" #descr="ngModel">

Delayed rendering of React components

Another approach for a delayed component:

Delayed.jsx:

import React from 'react';
import PropTypes from 'prop-types';

class Delayed extends React.Component {

    constructor(props) {
        super(props);
        this.state = {hidden : true};
    }

    componentDidMount() {
        setTimeout(() => {
            this.setState({hidden: false});
        }, this.props.waitBeforeShow);
    }

    render() {
        return this.state.hidden ? '' : this.props.children;
    }
}

Delayed.propTypes = {
  waitBeforeShow: PropTypes.number.isRequired
};

export default Delayed;

Usage:

 import Delayed from '../Time/Delayed';
 import React from 'react';

 const myComp = props => (
     <Delayed waitBeforeShow={500}>
         <div>Some child</div>
     </Delayed>
 )

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Update to the latest release

Since this commit, this is is fixed in the development version of Tomcat. And now in released versions 9.0.13, 8.5.35, and 7.0.92.

From the 9.0.13 changelog:

Ignore an attribute named source on Context elements provided by StandardContext. This is to suppress warnings generated by the Eclipse / Tomcat integration provided by Eclipse. Based on a patch by mdfst13. (markt)

There are similar entries in the 7.0.92 and 8.5.35 changelogs.

The effect of this change is to suppress a warning when a source attribute is declared on a Context element in either server.xml or a context.xml. Since those are the two places that Eclipse puts such an attribute, that fixes this particular issue.

TL;DR: update to the latest Tomcat version in its branch, e.g. 9.0.13 or newer.

How to run SQL in shell script

sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;

connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;

truncate table tmp;

exit;
EOF

WPF C# button style

<!--Customize button -->

<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
    <GradientStop Color="#5e5e5e" Offset="1" />
    <GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush> 

<Style x:Key="hhh" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
                    </Border.Effect>

                    <Grid>

                        <Path Width="9" Height="16.5" Stretch="Fill" Fill="#000"  HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">

                        </Path>
                        <Path x:Name="PathIcon" Width="8" Height="15"  Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
                            <Path.Effect>
                                <DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
                            </Path.Effect>
                        </Path>


                        <Line  HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>  

Remove ALL white spaces from text

Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:

_x000D_
_x000D_
const text = ' a b    c d e   f g   ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
_x000D_
_x000D_

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

How to remove all CSS classes using jQuery/JavaScript?

try with removeClass

For instance:

_x000D_
_x000D_
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("after", nameClass[0]);_x000D_
$(".clase1").removeClass();_x000D_
var nameClass=document.getElementsByClassName("clase1");_x000D_
console.log("before", nameClass[0]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clase1">I am Div with class="clase1"</div>
_x000D_
_x000D_
_x000D_

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

bootstrap multiselect get selected values

more efficient, due to less DOM lookups:

$('#multiselect1').multiselect({
    // ...
    onChange: function() {
        var selected = this.$select.val();
        // ...
    }
});

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

When you add both to environment variables there will a be a conflict because the two executable have the same name: python.exe.

Just rename one of them. In my case I renamed it to python3.exe.

So when I run python it will execute python.exe which is 2.7 and when I run python3 it will execute python3.exe which is 3.6

enter image description here

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

I would set the focus to the newly created pop-over and remove it on blur. That way it's not needed to check which element of the DOM has been clicked and the pop-over can be clicked, and selected too: it will not lose its focus and will not disappear.

The code:

    $('.popup-marker').popover({
       html: true,
       trigger: 'manual'
    }).click(function(e) {
       $(this).popover('toggle');
       // set the focus on the popover itself 
       jQuery(".popover").attr("tabindex",-1).focus();
       e.preventDefault();
    });

    // live event, will delete the popover by clicking any part of the page
    $('body').on('blur','.popover',function(){
       $('.popup-marker').popover('hide');
    });

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

Undefined function mysql_connect()

In php.ini file

change this

;extension=php_mysql.dll

into

extension=php_mysql.dll

String to HashMap JAVA

You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

Example:

Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");

JSONObject json= new JSONObject(map);

String result= json.toString();

System.out.print(result);

result:

{'myNumber':100, 'myString':'String'}

Your can also get key from it like

System.out.print(json.get("myNumber"));

result:

100

How to check if a table is locked in sql server

Better yet, consider sp_getapplock which is designed for this. Or use SET LOCK_TIMEOUT

Otherwise, you'd have to do something with sys.dm_tran_locks which I'd use only for DBA stuff: not for user defined concurrency.

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Values of disabled inputs will not be submitted

There are two attributes, namely readonly and disabled, that can make a semi-read-only input. But there is a tiny difference between them.

<input type="text" readonly />
<input type="text" disabled />
  • The readonly attribute makes your input text disabled, and users are not able to change it anymore.
  • Not only will the disabled attribute make your input-text disabled(unchangeable) but also cannot it be submitted.

jQuery approach (1):

$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);

jQuery approach (2):

$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");

JavaScript approach:

document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;

PS disabled and readonly are standard html attributes. prop introduced with jQuery 1.6.

Concatenate a NumPy array to another NumPy array

Try this code :

import numpy as np

a1 = np.array([])

n = int(input(""))

for i in range(0,n):
    a = int(input(""))
    a1 = np.append(a, a1)
    a = 0

print(a1)

Also you can use array instead of "a"

Open another application from your own (intent)

If you're attempting to start a SERVICE rather than activity, this worked for me:

Intent intent = new Intent();
intent.setClassName("com.example.otherapplication", "com.example.otherapplication.ServiceName");
context.startService(intent);

If you use the intent.setComponent(...) method as mentioned in other answers, you may get an "Implicit intents with startService are not safe" warning.

Removing items from a list

You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:

List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        toRemove.add(a);
    }
}
list.removeAll(toRemove);

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using AWS Management Console:

  • Right-Click on the instance
    • Instance Lifecycle > Stop
    • Wait...
    • Instance Management > Change Instance Type

Flutter plugin not installed error;. When running flutter doctor

I had this problem when having multiple versions of Android Studio, it doesn't look like you have multiple versions. But you do use IntelliJ IDEA Community Edition so are you sure you did install the plugins in Android Studio?.

I would have said this in a comment but I dont have enough rep

How to import a .cer certificate into a java keystore?

Here's how this worked for me:

  1. Save as .txt the certificate data in the following format in a text editor

    -----BEGIN CERTIFICATE----- [data serialized by microsoft] -----END CERTIFICATE-----

  2. Open chrome browser (this step might work with other browsers too) settings > show advanced settings > HTTPS/SSL > manage certificates Import the .txt in step 1
  3. Select and export that certificate in Base-64 encoded format. Save it as .cer
  4. Now you can use keytool or Portecle to import it to your java keystore

How do I split a string into an array of characters?

To support emojis use this

('Dragon ').split(/(?!$)/u);

=> ['D', 'r', 'a', 'g', 'o', 'n', ' ', '']

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

Github Push Error: RPC failed; result=22, HTTP code = 413

when I used the https url to push to the remote master, I met the same proble, I changed it to the SSH address, and everything resumed working flawlessly.

Default behavior of "git push" without a branch specified

Rather than using aliases, I prefer creating git-XXX scripts so I can source control them more easily (our devs all have a certain source controlled dir on their path for this type of thing).

This script (called git-setpush) will set the config value for remote.origin.push value to something that will only push the current branch:

#!/bin/bash -eu

CURRENT_BRANCH=$(git branch | grep '^\*' | cut -d" " -f2)
NEW_PUSH_REF=HEAD:refs/for/$CURRENT_BRANCH

echo "setting remote.origin.push to $NEW_PUSH_REF"
git config remote.origin.push $NEW_PUSH_REF

note, as we're using Gerrit, it sets the target to refs/for/XXX to push into a review branch. It also assumes origin is your remote name.

Invoke it after checking out a branch with

git checkout your-branch
git setpush

It could obviously be adapted to also do the checkout, but I like scripts to do one thing and do it well

Set attribute without value

Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:

document.querySelector('#selector').toggleAttribute('data-something');

This will add the attribute in all lowercase without a value or remove it if it already exists on the element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

How to copy a directory structure but only include certain files (using windows batch files)

try piping output of find (ie. the file path) into cpio

find . -type f -name '*.jpg' | cpio -p -d -v targetdir/

cpio checks timestamp on target files -- so its safe and fast.

remove -v for faster op, once you get used to it.

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

How can I make space between two buttons in same div?

Another way to achieve this is to add a class .btn-space in your buttons

  <button type="button" class="btn btn-outline-danger btn-space"
  </button>
  <button type="button" class="btn btn-outline-primary btn-space"
  </button>

and define this class as follows

.btn-space {
    margin-right: 15px;
}

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

How to make an HTTP POST web request

Why is this not totally trivial? Doing the request is not and especially not dealing with the results and seems like there are some .NET bugs involved as well - see Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

I ended up with this code:

static async Task<(bool Success, WebExceptionStatus WebExceptionStatus, HttpStatusCode? HttpStatusCode, string ResponseAsString)> HttpRequestAsync(HttpClient httpClient, string url, string postBuffer = null, CancellationTokenSource cts = null) {
    try {
        HttpResponseMessage resp = null;

        if (postBuffer is null) {
            resp = cts is null ? await httpClient.GetAsync(url) : await httpClient.GetAsync(url, cts.Token);

        } else {
            using (var httpContent = new StringContent(postBuffer)) {
                resp = cts is null ? await httpClient.PostAsync(url, httpContent) : await httpClient.PostAsync(url, httpContent, cts.Token);
            }
        }

        var respString = await resp.Content.ReadAsStringAsync();
        return (resp.IsSuccessStatusCode, WebExceptionStatus.Success, resp.StatusCode, respString);

    } catch (WebException ex) {
        WebExceptionStatus status = ex.Status;
        if (status == WebExceptionStatus.ProtocolError) {
            // Get HttpWebResponse so that you can check the HTTP status code.
            using (HttpWebResponse httpResponse = (HttpWebResponse)ex.Response) {
                return (false, status, httpResponse.StatusCode, httpResponse.StatusDescription);
            }
        } else {
            return (false, status, null, ex.ToString()); 
        }

    } catch (TaskCanceledException ex) {
        if (cts is object && ex.CancellationToken == cts.Token) {
            // a real cancellation, triggered by the caller
            return (false, WebExceptionStatus.RequestCanceled, null, ex.ToString());
        } else {
            // a web request timeout (possibly other things!?)
            return (false, WebExceptionStatus.Timeout, null, ex.ToString());
        }

    } catch (Exception ex) {
        return (false, WebExceptionStatus.UnknownError, null, ex.ToString());
    }
}

This will do a GET or POST depends if postBuffer is null or not

if Success is true the response will then be in ResponseAsString

if Success is false you can check WebExceptionStatus, HttpStatusCode and ResponseAsString to try to see what went wrong.

405 method not allowed Web API

We had a similar issue. We were trying to GET from:

[RoutePrefix("api/car")]
public class CarController: ApiController{

    [HTTPGet]
    [Route("")]
    public virtual async Task<ActionResult> GetAll(){

    }

}

So we would .GET("/api/car") and this would throw a 405 error.


The Fix:

The CarController.cs file was in the directory /api/car so when we were requesting this api endpoint, IIS would send back an error because it looked like we were trying to access a virtual directory that we were not allowed to.

Option 1: change / rename the directory the controller is in
Option 2: change the route prefix to something that doesn't match the virtual directory.

Logical operator in a handlebars.js {{#if}} conditional

I have found a npm package made with CoffeeScript that has a lot of incredible useful helpers for Handlebars. Take a look of the documentation in the following URL:

https://npmjs.org/package/handlebars-helpers

You can do a wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz to download them and see the contents of the package.

You will be abled to do things like {{#is number 5}} or {{formatDate date "%m/%d/%Y"}}

finding first day of the month in python

from datetime import datetime

date_today = datetime.now()
month_first_day = date_today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
print(month_first_day)

What is the difference between Cloud Computing and Grid Computing?

I would say that the basic difference is this:

Grids are used as computing/storage platform.

We start talking about cloud computing when it offers services. I would almost say that cloud computing is higher-level grid. Now I know these are not definitions, but maybe it will make it more clear.

As far as application domains go, grids require users (developers mostly) to actually create services from low-level functions that grid offers. Cloud will offer complete blocks of functionality that you can use in your application.

Example (you want to create physical simulation of ball dropping from certain height): Grid: Study how to compute physics on a computer, create appropriate code, optimize it for certain hardware, think about paralellization, set inputs send application to grid and wait for answer

Cloud: Set diameter of a ball, material from pre-set types, height from which the ball is dropping, etc and ask for results

I would say that if you created OS for grid, you would actually create cloud OS.

Working with Enums in android

Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.

public enum Gender {
   MALE,
   FEMALE
}

If you want them to be more complex, you can add values to them like this.

public enum Gender {
    MALE("Male", 0),
    FEMALE("Female", 1);

    private String stringValue;
    private int intValue;
    private Gender(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

Then to use the enum, you would do something like this:

Gender me = Gender.MALE

Set a default font for whole iOS app?

There is also another solution which will be to override systemFont.

Just create a category

UIFont+SystemFontOverride.h

#import <UIKit/UIKit.h>

@interface UIFont (SystemFontOverride)
@end

UIFont+SystemFontOverride.m

@implementation UIFont (SystemFontOverride)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

+ (UIFont *)systemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

#pragma clang diagnostic pop

@end

This will replace the default implementation and most UIControls use systemFont.

How to select an item in a ListView programmatically?

if (listView1.Items.Count > 0)
{
    listView1.FocusedItem = listView1.Items[0];
    listView1.Items[0].Selected = true;
    listView1.Select();
}

sum two columns in R

You can use a for loop:

for (i in 1:nrow(df)) {
   df$col3[i] <- df$col1[i] + df$col2[i]
}

Sorting Values of Set

Use the Integer wrapper class instead of String because it is doing the hard work for you by implementing Comparable<Integer>. Then java.util.Collections.sort(list); would do the trick.

How does a Java HashMap handle different objects with the same hash code?

As it is said, a picture is worth 1000 words. I say: some code is better than 1000 words. Here's the source code of HashMap. Get method:

/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

So it becomes clear that hash is used to find the "bucket" and the first element is always checked in that bucket. If not, then equals of the key is used to find the actual element in the linked list.

Let's see the put() method:

  /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

It's slightly more complicated, but it becomes clear that the new element is put in the tab at the position calculated based on hash:

i = (n - 1) & hash here i is the index where the new element will be put (or it is the "bucket"). n is the size of the tab array (array of "buckets").

First, it is tried to be put as the first element of in that "bucket". If there is already an element, then append a new node to the list.

How to save a PNG image server-side, from a base64 data string

It worth to say that discussed topic is documented in RFC 2397 - The "data" URL scheme (https://tools.ietf.org/html/rfc2397)

Because of this PHP has a native way to handle such data - "data: stream wrapper" (http://php.net/manual/en/wrappers.data.php)

So you can easily manipulate your data with PHP streams:

$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';

$source = fopen($data, 'r');
$destination = fopen('image.gif', 'w');

stream_copy_to_stream($source, $destination);

fclose($source);
fclose($destination);

Max length UITextField

I posted a solution using IBInspectable, so you can change the max length value both in interface builder or programmatically. Check it out here

How do I get only directories using Get-ChildItem?

You'll want to use Get-ChildItem to recursively get all folders and files first. And then pipe that output into a Where-Object clause which only take the files.

# one of several ways to identify a file is using GetType() which
# will return "FileInfo" or "DirectoryInfo"
$files = Get-ChildItem E:\ -Recurse | Where-Object {$_.GetType().Name -eq "FileInfo"} ;

foreach ($file in $files) {
  echo $file.FullName ;
}

Jquery Smooth Scroll To DIV - Using ID value from Link

Here is my solution:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=\\#]:not([href=\\#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

With just this snippet you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

I already explained how it works in another thread here: https://stackoverflow.com/a/28631803/4566435 (or here's a direct link to my blog post)

For clarifications, let me know. Hope it helps!

Android open camera from button

You are correct about the action used in Intent but it's not the only thing you have to do. You'll also have to add

startActivityForResult(intent, YOUR_REQUEST_CODE);

To get it all done and retrieve the actual picture you could check the following thread.

Android - Capture photo

ORA-01882: timezone region not found

In my case I could get the query working by changing "TZR" with "TZD"..

String query = "select * from table1 to_timestamp_tz(origintime,'dd-mm-yyyy hh24:mi:ss TZD') between ?  and ?";

How to move a file?

  import os,shutil

  current_path = "" ## source path

  new_path = "" ## destination path

  os.chdir(current_path)

  for files in os.listdir():

        os.rename(files, new_path+'{}'.format(f))
        shutil.move(files, new_path+'{}'.format(f)) ## to move files from 

different disk ex. C: --> D:

How to rollback just one step using rake db:migrate

Best way is running Particular migration again by using down or up(in rails 4. It's change)

rails db:migrate:up VERSION=timestamp

Now how you get the timestamp. Go to this path

/db/migrate

Identify migration file you want to revert.pick the timestamp from that file name.

hadoop copy a local file system folder to HDFS

You can use :

1.LOADING DATA FROM LOCAL FILE TO HDFS

Syntax:$hadoop fs –copyFromLocal

EX: $hadoop fs –copyFromLocal localfile1 HDIR

2. Copying data From HDFS to Local

Sys: $hadoop fs –copyToLocal < new file name>

EX: $hadoop fs –copyToLocal hdfs/filename myunx;

What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 

or

1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>

How to rename JSON key

If you want to do it dynamically, for example, you have an array which you want to apply as a key to JSON object:

your Array will be like :

var keys = ["id", "name","Address","Phone"] // The array size should be same as JSON Object keys size

Now you have a JSON Array like:

var jArray = [
  {
    "_id": 1,
    "_name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "_id": 2,
    "_name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "_id": 3,
    "_name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]

$.each(jArray ,function(pos,obj){
    var counter = 0;
    $.each(obj,function(key,value){
        jArray [pos][keys[counter]] = value;
        delete jArray [pos][key];
        counter++;
    })  
})

Your resultant JSON Array will be like :

[
  {
    "id": 1,
    "name": "Asna",
    "Address": "NY",
    "Phone": 123
  },
  {
    "id": 2,
    "name": "Euphoria",
    "Address": "Monaco",
    "Phone": 124
  },
  {
    "id": 3,
    "name": "Ahmed",
    "Address": "Mumbai",
    "Phone": 125
  }
]

MySQL: Large VARCHAR vs. TEXT?

Can you predict how long the user input would be?

VARCHAR(X)

Max Length: variable, up to 65,535 bytes (64KB)
Case: user name, email, country, subject, password


TEXT

Max Length: 65,535 bytes (64KB)
Case: messages, emails, comments, formatted text, html, code, images, links


MEDIUMTEXT

Max Length: 16,777,215 bytes (16MB)
Case: large json bodies, short to medium length books, csv strings


LONGTEXT

Max Length: 4,294,967,29 bytes (4GB)
Case: textbooks, programs, years of logs files, harry potter and the goblet of fire, scientific research logging

There's more information on this question.

Array String Declaration

You are not initializing your String[]. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String> and then convert to a String[] (in case you do not know the length):

String[] title = {
        "Abundance",
        "Anxiety",
        "Bruxism",
        "Discipline",
        "Drug Addiction"
    };
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();

for(int i=0;i<title.length;i++) {
    mStrings.add(urlbase + title[i].toLowerCase() + imgSel);

    System.out.println(mStrings[i]);
}

String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array

How can you undo the last git add?

So the real answer to

Can this programmer now unstage his last changes with some magical git command?

is actually: No, you cannot unstage just the last git add.

That is if we interpret the question as in the following situation:

Initial file:

void foo() {

}

main() {
    foo();
}

First change followed by git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Second change followed by git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

In this case, git reset -p will not help, since its smallest granularity is lines. git doesn't know that about the intermediate state of:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

any more.

How to convert milliseconds into human readable form?

Let A be the amount of milliseconds. Then you have:

seconds=(A/1000)%60
minutes=(A/(1000*60))%60
hours=(A/(1000*60*60))%24

and so on (% is the modulus operator).

Hope this helps.

How to add a char/int to an char array in C?

The error is due the fact that you are passing a wrong to strcat(). Look at strcat()'s prototype:

   char *strcat(char *dest, const char *src);

But you pass char as the second argument, which is obviously wrong.

Use snprintf() instead.

char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);

snprintf(str + len, sizeof str - len, "%c", tmp);

As commented by OP:

That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array

In that case, snprintf() can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf() is that it's more flexible to concatenate various types of data into a char buffer.

For example to concatenate a string, char and an int:

char str[1024];
ch tmp = '.';
int i = 5;

// Fill str here

snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);

Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

Selenium C# WebDriver: Wait until element is present

Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls.

Many times you'll want the FindElement to fail right away when an element is not present (you're testing for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception. The default implicit wait is set to 0 seconds.

I've written a little extension method to IWebDriver that adds a timeout (in seconds) parameter to the FindElement() method. It's quite self-explanatory:

public static class WebDriverExtensions
{
    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }
        return driver.FindElement(by);
    }
}

I didn't cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.

Usage is straightforward:

var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost/mypage");
var btn = driver.FindElement(By.CssSelector("#login_button"));
btn.Click();
var employeeLabel = driver.FindElement(By.CssSelector("#VCC_VSL"), 10);
Assert.AreEqual("Employee", employeeLabel.Text);
driver.Close();

Can't load IA 32-bit .dll on a AMD 64-bit platform

Here is an answer for those who compile from the command line/Command Prompt. It doesn't require changing your Path environment variable; it simply lets you use the 32-bit JVM for the program with the 32-bit DLL.

For the compilation, it shouldn't matter which javac gets used - 32-bit or 64-bit.

>javac MyProgramWith32BitNativeLib.java

For the actual execution of the program, it is important to specify the path to the 32-bit version of java.exe

I'll post a code example for Windows, since that seems to be the OS used by the OP.

Windows

Most likely, the code will be something like:

>"C:\Program Files (x86)\Java\jre#.#.#_###\bin\java.exe" MyProgramWith32BitNativeLib 

The difference will be in the numbers after jre. To find which numbers you should use, enter:

>dir "C:\Program Files (x86)\Java\"

On my machine, the process is as follows

C:\Users\me\MyProject>dir "C:\Program Files (x86)\Java"
 Volume in drive C is Windows
 Volume Serial Number is 0000-9999

 Directory of C:\Program Files (x86)\Java

11/03/2016  09:07 PM    <DIR>          .
11/03/2016  09:07 PM    <DIR>          ..
11/03/2016  09:07 PM    <DIR>          jre1.8.0_111
               0 File(s)              0 bytes
               3 Dir(s)  107,641,901,056 bytes free

C:\Users\me\MyProject>

So I know that my numbers are 1.8.0_111, and my command is

C:\Users\me\MyProject>"C:\Program Files (x86)\Java\jre1.8.0_111\bin\java.exe" MyProgramWith32BitNativeLib

How to pass variable number of arguments to printf/sprintf

Using functions with the ellipses is not very safe. If performance is not critical for log function consider using operator overloading as in boost::format. You could write something like this:

#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;

class formatted_log_t {
public:
    formatted_log_t(const char* msg ) : fmt(msg) {}
    ~formatted_log_t() { cout << fmt << endl; }

    template <typename T>
    formatted_log_t& operator %(T value) {
        fmt % value;
        return *this;
    }

protected:
    boost::format                fmt;
};

formatted_log_t log(const char* msg) { return formatted_log_t( msg ); }

// use
int main ()
{
    log("hello %s in %d-th time") % "world" % 10000000;
    return 0;
}

The following sample demonstrates possible errors with ellipses:

int x = SOME_VALUE;
double y = SOME_MORE_VALUE;
printf( "some var = %f, other one %f", y, x ); // no errors at compile time, but error at runtime. compiler do not know types you wanted
log( "some var = %f, other one %f" ) % y % x; // no errors. %f only for compatibility. you could write %1% instead.

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

How to stop "setInterval"

This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:

$(function () {
  var timerId = 0;

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

  $('textarea').blur(function () {
    timerId = setInterval(function () {
     //some code here 
    }, 1000);
  });
});

No Exception while type casting with a null in java

This language feature is convenient in this situation.

public String getName() {
  return (String) memberHashMap.get("Name");
}

If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

grep a file, but show several surrounding lines?

ripgrep

If you care about the performance, use ripgrep which has similar syntax to grep, e.g.

rg -C5 "pattern" .

-C, --context NUM - Show NUM lines before and after each match.

There are also parameters such as -A/--after-context and -B/--before-context.

The tool is built on top of Rust's regex engine which makes it very efficient on the large data.

LINQ order by null column where order is ascending and nulls should be last

I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:

var newList = objList.Where(m=>m.Column != null)
                     .OrderBy(m => m.Column)
                     .Concat(objList.where(m=>m.Column == null));

Should I use Java's String.format() if performance is important?

Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).

Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder. Or use Java's StringBuilder explicitly.

How do you display code snippets in MS Word preserving format and syntax highlighting?

Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.

Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.


Input image:

Detected text object

Top-down view of text document

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None

for c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        displayCnt = approx
        break

# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Update

Official standard dialogs are coming to JavaFX in release 8u40, as part of the implemenation of RT-12643. These should be available in final release form around March of 2015 and in source code form in the JavaFX development repository now.

In the meantime, you can use the ControlsFX solution below...


ControlsFX is the defacto standard 3rd party library for common dialog support in JavaFX (error, warning, confirmation, etc).

There are numerous other 3rd party libraries available which provide common dialog support as pointed out in some other answers and you can create your own dialogs easily enough using the sample code in Sergey's answer.

However, I believe that ControlsFX easily provide the best quality standard JavaFX dialogs available at the moment. Here are some samples from the ControlsFX documentation.

standard dialog

command links

How to register multiple implementations of the same interface in Asp.Net Core?

My solution for what it's worth... considered switching to Castle Windsor as can't say I liked any of the solutions above. Sorry!!

public interface IStage<out T> : IStage { }

public interface IStage {
      void DoSomething();
}

Create your various implementations

public class YourClassA : IStage<YouClassA> { 
    public void DoSomething() 
    {
        ...TODO
    }
}

public class YourClassB : IStage<YourClassB> { .....etc. }

Registration

services.AddTransient<IStage<YourClassA>, YourClassA>()
services.AddTransient<IStage<YourClassB>, YourClassB>()

Constructor and instance usage...

public class Whatever
{
   private IStage ClassA { get; }

   public Whatever(IStage<YourClassA> yourClassA)
   {
         ClassA = yourClassA;
   }

   public void SomeWhateverMethod()
   {
        ClassA.DoSomething();
        .....
   }

Rails server says port already used, how to kill that process?

Using this command you can kill the server:

ps aux|grep rails 

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

apache ProxyPass: how to preserve original IP address

You can get the original host from X-Forwarded-For header field.

What does enumerate() mean?

The enumerate function works as follows:

doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):
     print(i)

The output is

(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')

Check if a string contains a string in C++

From so many answers in this website I didn't find out a clear answer so in 5-10 minutes I figured it out the answer myself. But this can be done in two cases:

  1. Either you KNOW the position of the sub-string you search for in the string
  2. Either you don't know the position and search for it, char by char...

So, let's assume we search for the substring "cd" in the string "abcde", and we use the simplest substr built-in function in C++

for 1:

#include <iostream>
#include <string>

    using namespace std;
int i;

int main()
{
    string a = "abcde";
    string b = a.substr(2,2);    // 2 will be c. Why? because we start counting from 0 in a string, not from 1.

    cout << "substring of a is: " << b << endl;
    return 0;
}

for 2:

#include <iostream>
#include <string>

using namespace std;
int i;

int main()
{
    string a = "abcde";

    for (i=0;i<a.length(); i++)
    {
        if (a.substr(i,2) == "cd")
        {
        cout << "substring of a is: " << a.substr(i,2) << endl;    // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled 
        }
    }
    return 0;
}

Slidedown and slideup layout with animation

I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :

public static void expand(final View v) {
    v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? WindowManager.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

How to keep :active css style after clicking an element

Combine JS & CSS :

button{
  /* 1st state */
}

button:hover{
  /* hover state */
}

button:active{
  /* click state */
}

button.active{
  /* after click state */
}


jQuery('button').click(function(){
   jQuery(this).toggleClass('active');
});

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

Bootstrap Accordion button toggle "data-parent" not working

Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.

$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
    var parent = $(this).data('parent');
    var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
    items.each(function() {
        var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
        $(target).filter('.in').collapse('hide');
    });
});

EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:

$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
    var parent = $(this).data('parent');
    var target = $(this).data('target') || $(this).prop('hash');
    $(parent).find('.collapse.in').not(target).collapse('hide');
});

How can I count the occurrences of a string within a file?

The number of string occurrences (not lines) can be obtained using grep with -o option and wc (word count):

$ echo "echo 1234 echo" | grep -o echo
echo
echo
$ echo "echo 1234 echo" | grep -o echo | wc -l
2

So the full solution for your problem would look like this:

$ grep -o "echo" FILE | wc -l

How to replace all occurrences of a string in Javascript?

while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

Load resources from relative path using local html in uiwebview

In Swift:

 func pathForResource(  name: String?, 
                        ofType ext: String?, 
                        inDirectory subpath: String?) -> String?  {

  // **name:** Name of Hmtl
  // **ofType ext:** extension for type of file. In this case "html"
  // **inDirectory subpath:** the folder where are the file. 
  //    In this case the file is in root folder

    let path = NSBundle.mainBundle().pathForResource(             "dados",
                                                     ofType:      "html", 
                                                     inDirectory: "root")
    var requestURL = NSURL(string:path!)
    var request = NSURLRequest(URL:requestURL)

    webView.loadRequest(request)
}

How do you connect localhost in the Android emulator?

Use 10.0.2.2 to access your actual machine.

As you've learned, when you use the emulator, localhost (127.0.0.1) refers to the device's own loopback service, not the one on your machine as you may expect.

You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.

jQuery - Dynamically Create Button and Attach Event Handler

Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.

$("#myButton").click(function () {
    var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
        alert('hi');
    }).end();

    $("#nodeAttributeHeader").attr('style', 'display: table-row;');
    $("#addNodeTable tr:last").before(test);
});

Swift: declare an empty dictionary

var parking = [Dictionary < String, Double >()]

^ this adds a dictionary for a [string:double] input

check the null terminating character in char*

The null character is '\0', not '/0'.

while (*(forward++) != '\0')

How do I generate random number for each row in a TSQL Select?

When called multiple times in a single batch, rand() returns the same number.

I'd suggest using convert(varbinary,newid()) as the seed argument:

SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number 
FROM information_schema.tables

newid() is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.

Edited to get a random whole number from 1 to 14.

Convert an integer to an array of digits

You can do something like this:

public int[] convertDigitsToArray(int n) {

    int [] temp = new int[String.valueOf(n).length()]; // Calculate the length of digits
    int i = String.valueOf(n).length()-1 ;  // Initialize the value to the last index

    do {
        temp[i] = n % 10;
        n = n / 10;
        i--;
    } while(n>0);

    return temp;
}

This will also maintain the order.

Accessing a local website from another computer inside the local network in IIS 7

Control Panel >> Windows Firewall >> Turn windows firewall on or off >> Turn off.

Advanced settings >> Domain profile >> Windows firewall properties >> Firewall status >> Off.

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

What is the difference between a function expression vs declaration in JavaScript?

The first statement depends on the context in which it is declared.

If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.

If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"

EDIT:

I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.

END EDIT

Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore

var foo = function foo() { return 5; }

Is the same as

var foo = function fooYou() { return 5; }

Type List vs type ArrayList in Java

The only case that I am aware of where (2) can be better is when using GWT, because it reduces application footprint (not my idea, but the google web toolkit team says so). But for regular java running inside the JVM (1) is probably always better.

How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).

==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.

I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!

Hope this helps to make things even clearer!

enter image description here

Is embedding background image data into CSS as Base64 good or bad practice?

I disagree with the recommendation to create separate CSS files for non-editorial images.

Assuming the images are for UI purposes, it's presentation layer styling, and as mentioned above, if you're doing mobile UI's its definitely a good idea to keep all styling in a single file so it can be cached once.

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");
        onCreate(database);
    }
}

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

    /** 
     * 
     * @param context 
     */  
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  
    }


    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  
    }    

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
            mCursor.moveToFirst();  
        }  
        return mCursor; // iterate to get each value.
    }
}

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

PHP form - on submit stay on same page

Friend. Use this way, There will be no "Undefined variable message" and it will work fine.

<?php
    if(isset($_POST['SubmitButton'])){
        $price = $_POST["price"];
        $qty = $_POST["qty"];
        $message = $price*$qty;
    }

        ?>

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="#" method="post">
            <input type="number" name="price"> <br>
            <input type="number" name="qty"><br>
            <input type="submit" name="SubmitButton">
        </form>
        <?php echo "The Answer is" .$message; ?>

    </body>
    </html>

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

I have another even simpler solution, to be used without autolayout and with everything done through the XIB :

1/ Put your header in the tableview by drag and dropping it directly on the tableview.

2/ In the Size Inspector of the newly made header, just change its autosizing : you should only leave the top, left and right anchors, plus the fill horizontally.

That's how it should be set for the header

That should do the trick !

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

How do I download/extract font from chrome developers tools?

To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.

The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.

Java Replace Line In Text File

Since Java 7 this is very easy and intuitive to do.

List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));

for (int i = 0; i < fileContent.size(); i++) {
    if (fileContent.get(i).equals("old line")) {
        fileContent.set(i, "new line");
        break;
    }
}

Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);

Basically you read the whole file to a List, edit the list and finally write the list back to file.

FILE_PATH represents the Path of the file.

How to detect when WIFI Connection has been established in Android?

1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.

2) I also tried Firebase Dispatcher which works but not beyond app killed.

3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()

The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.

Also here

In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.

So far it works fine for us using Periodic WorkManager request.

Update: I ended up writing 2 series medium post about it.

How to add a new row to datagridview programmatically

Like this:

 dataGridView1.Columns[0].Name = "column2";
 dataGridView1.Columns[1].Name = "column6";

 string[] row1 = new string[] { "column2 value", "column6 value" };
 dataGridView1.Rows.Add(row1);

Or you need to set there values individually use the propery .Rows(), like this:

 dataGridView1.Rows[1].Cells[0].Value = "cell value";

diff to output only the file names

On my linux system to get just the filenames

diff -q /dir1 /dir2|cut -f2 -d' '

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

My application.properties looked something like this

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=root

The only thing worked for me is to maven clean and then maven install.

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

1) When to use include directive ?

To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used

  <%@ include file="abc.jsp" %>

when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page

Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page

2) When to use include action ?

include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response

include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming

include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page

Collections.emptyList() vs. new instance

Be carefully though. If you return Collections.emptyList() and then try to do some changes with it like add() or smth like that, u will have an UnsupportedOperationException() because Collections.emptyList() returns an immutable object.

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

JWT (JSON Web Token) automatic prolongation of expiration

I was tinkering around when moving our applications to HTML5 with RESTful apis in the backend. The solution that I came up with was:

  1. Client is issued with a token with a session time of 30 mins (or whatever the usual server side session time) upon successful login.
  2. A client-side timer is created to call a service to renew the token before its expiring time. The new token will replace the existing in future calls.

As you can see, this reduces the frequent refresh token requests. If user closes the browser/app before the renew token call is triggered, the previous token will expire in time and user will have to re-login.

A more complicated strategy can be implemented to cater for user inactivity (e.g. neglected an opened browser tab). In that case, the renew token call should include the expected expiring time which should not exceed the defined session time. The application will have to keep track of the last user interaction accordingly.

I don't like the idea of setting long expiration hence this approach may not work well with native applications requiring less frequent authentication.

Import SQL dump into PostgreSQL database

I believe that you want to run in psql:

\i C:/database/db-backup.sql

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

Convert InputStream to byte array in Java

If you happen to use google guava, it'll be as simple as :

byte[] bytes = ByteStreams.toByteArray(inputStream);

Add line break within tooltips

AngularJS with Bootstrap UI Tolltip (uib-tooltip), has three versions of tool-tip:

uib-tooltip, uib-tooltip-template and uib-tooltip-html

- uib-tooltip takes only text and will escape any HTML provided
- uib-tooltip-html takes an expression that evaluates to an HTML string
- uib-tooltip-template takes a text that specifies the location of the template

In my case, I opted for uib-tooltip-html and there are three parts to it:

  1. configuration
  2. controller
  3. HTML

Example:

(function(angular) {

//Step 1: configure $sceProvider - this allows the configuration of $sce service.

angular.module('myApp', ['uib.bootstrap'])
       .config(function($sceProvider) {
           $sceProvider.enabled(false);
       });

//Step 2: Set the tooltip content in the controller

angular.module('myApp')
       .controller('myController', myController);

myController.$inject = ['$sce'];

function myController($sce) {
    var vm = this;
    vm.tooltipContent = $sce.trustAsHtml('I am the first line <br /><br />' +
                                         'I am the second line-break');

    return vm;
}

 })(window.angular);

//Step 3: Use the tooltip in HTML (UI)

<div ng-controller="myController as get">
     <span uib-tooltip-html="get.tooltipContent">other Contents</span>
</div>

For more information, please check here

Https to http redirect using htaccess

You can use the following rule to redirect from https to http :

 RewriteEngine On


RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]

Explanation :

RewriteCond %{HTTPS} ^on$

Checks if the HTTPS is on (Request is made using https)

Then

RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]

Redirect any request (https://example.com/foo) to http://example.com/foo .

  • $1 is part of the regex in RewriteRule pattern, it contains whatever value was captured in (.+) , in this case ,it captures the full request_uri everything after the domain name.

  • [NC,L,R] are the flags, NC makes the uri case senstive, you can use both uppercase or lowercase letters in the request.

L flag tells the server to stop proccessing other rules if the currunt rule has matched, it is important to use the L flag to avoid rule confliction when you have more then on rules in a block.

R flag is used to make an external redirection.

Getting data-* attribute for onclick event for an html element

here is an example

 <a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>

    $('.facultySelecter').click(function() {        
    var unhide = $(this).data("faculty");
    });

this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get

How to connect to mysql with laravel?

I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me. I came to the conclusion, that after editing the .env file in Laravel 5, you have to exit the server, and run php artisan serve again.

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

Shell Script: Execute a python program from within a shell script

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv

Bootstrap 4 datapicker.js not included

Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

Simple check for SELECT query empty result

I agree with Ed B. You should use EXISTS method but a more efficient way to do this is:

IF EXISTS(SELECT 1 FROM service s WHERE s.service_id = ?)
BEGIN
   --DO STUFF HERE

END

HTH

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Add column to SQL query results

why dont you add a "source" column to each of the queries with a static value like

select 'source 1' as Source, column1, column2...
from table1

UNION ALL

select 'source 2' as Source, column1, column2...
from table2

JQuery .hasClass for multiple values in an if statement

For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

In short, using element.hasClass('class') is the fastest.

Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

The worst performance by far was using element.is('.class').

Also listed in the jsperf is CyberMonk's function, and Kolja's solution.