Programs & Examples On #Com interface

Random / noise functions for GLSL

After the initial posting of this question in 2010, a lot has changed in the realm of good random functions and hardware support for them.

Looking at the accepted answer from today's perspective, this algorithm is very bad in uniformity of the random numbers drawn from it. And the uniformity suffers a lot depending on the magnitude of the input values and visible artifacts/patterns will become apparent when sampling from it for e.g. ray/path tracing applications.

There have been many different functions (most of them integer hashing) being devised for this task, for different input and output dimensionality, most of which are being evaluated in the 2020 JCGT paper Hash Functions for GPU Rendering. Depending on your needs you could select a function from the list of proposed functions in that paper and simply from the accompanying Shadertoy. One that isn't covered in this paper but that has served me very well without any noticeably patterns on any input magnitude values is also one that I want to highlight.

Other classes of algorithms use low-discrepancy sequences to draw pseudo-random numbers from, such as the Sobol squence with Owen-Nayar scrambling. Eric Heitz has done some amazing research in this area, as well with his A Low-Discrepancy Sampler that Distributes Monte Carlo Errors as a Blue Noise in Screen Space paper. Another example of this is the (so far latest) JCGT paper Practical Hash-based Owen Scrambling, which applies Owen scrambling to a different hash function (namely Laine-Karras).

Yet other classes use algorithms that produce noise patterns with desirable frequency spectrums, such as blue noise, that is particularly "pleasing" to the eyes.

(I realize that good StackOverflow answers should provide the algorithms as source code and not as links because those can break, but there are way too many different algorithms nowadays and I intend for this answer to be a summary of known-good algorithms today)

Java: using switch statement with enum under subclass

This is how I am using it. And it is working fantastically -

public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

And the switch-case as shown below

@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}

getString Outside of a Context or Activity

Somehow didn't like the hacky solutions of storing static values so came up with a bit longer but a clean version which can be tested as well.

Found 2 possible ways to do it-

  1. Pass context.resources as a parameter to your class where you want the string resource. Fairly simple. If passing as param is not possible, use the setter.

e.g.

data class MyModel(val resources: Resources) {
    fun getNameString(): String {
        resources.getString(R.string.someString)
    }
}
  1. Use the data-binding (requires fragment/activity though)

Before you read: This version uses Data binding

XML-

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="someStringFetchedFromRes"
        type="String" />
</data>

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@{someStringFetchedFromRes}" />
</layout>

Activity/Fragment-

val binding = NameOfYourBinding.inflate(inflater)
binding.someStringFetchedFromRes = resources.getString(R.string.someStringFetchedFromRes)

Sometimes, you need to change the text based on a field in a model. So you would data-bind that model as well and since your activity/fragment knows about the model, you can very well fetch the value and then data-bind the string based on that.

Javascript array search and remove string?

DEMO

You need to find the location of what you're looking for with .indexOf() then remove it with .splice()

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}

var array = new Array();
array.push("A");
array.push("B");
array.push("C");
 ?   
remove(array, 'B');
alert(array)????;

This will take care of all occurrences.

typeof !== "undefined" vs. != null

If you are really worried about undefined being redefined, you can protect against this with some helper method like this:

function is_undefined(value) {
   var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
   return value === undefined_check;
}

This works because when someone writes undefined = "foo" he only lets the name undefined reference to a new value, but he doesn't change the actual value of undefined.

Bitbucket git credentials if signed up with Google

It's March 2019, and I just did it this way:

  1. Access https://id.atlassian.com/login/resetpassword
  2. Fill your email and click "Send recovery link"
  3. You will receive an email, and this is where people mess it up. Don't click the Log in to my account button, instead, you want to click the small link bellow that says Alternatively, you can reset your password for your Atlassian account.
  4. Set a password as you normally would

Now try to run git commands on terminal.

It might ask you to do a two-step verification the first time, just follow the steps and you're done!

Slide a layout up from bottom of screen

Use this layout. If you want to animate the main view shrinking you'll need to add animation to the height of the hidden bar, buy it may be good enough to use the translate animation on the bar, and have the main view height jump instead of animate.

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

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="slideUpDown"
        android:text="Slide up / down" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="#fcc"
    android:visibility="visible" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</RelativeLayout>

</LinearLayout>

Resolving a Git conflict with binary files

You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this

git commit -a -m "Fix merge conflict in test.foo"

Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The Git Merge Man Page, the Git-SVN Crash Course or this blog entry might shed some light on how it's supposed to work.

Edit: See the post below, you don't actually have to copy the files yourself, but can use

git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt

to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.

Please mark mipadis answer as the correct one.

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

To solve this problem once and for all, you can verify that you have a pip.conf file.

This is where your pip.conf should be, according to the documentation:

On Unix the default configuration file is: $HOME/.config/pip/pip.conf which respects the XDG_CONFIG_HOME environment variable.

On macOS the configuration file is $HOME/Library/Application Support/pip/pip.conf if directory $HOME/Library/Application Support/pip exists else $HOME/.config/pip/pip.conf

On Windows the configuration file is %APPDATA%\pip\pip.ini.

Inside a virtualenv:

On Unix and macOS the file is $VIRTUAL_ENV/pip.conf

On Windows the file is: %VIRTUAL_ENV%\pip.ini

Your pip.conf should look like:

[global]
trusted-host = pypi.python.org

pip install linkchecker installed linkchecker without complains after I created the pip.conf file.

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I have a similar problem and as I'm newbie, here are some facts for somebody to comment:

I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):

fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))

Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Edge execution Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: Chrome execution The value in the second column is blocked:other and there is also an error in Console tab:

GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT

In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests: Incognito execution

My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

Subscripts in plots in R

As other users have pointed out, we use expression(). I'd like to answer the original question which involves a comma in the subscript:

How can I write v 1,2 with 1,2 as subscripts?

plot(1:10, 11:20 , main=expression(v["1,2"]))

Also, I'd like to add the reference for those looking to find the full expression syntax in R plotting: For more information see the ?plotmath help page. Running demo(plotmath) will showcase many expressions and relevant syntax.

Remember to use * to join different types of text within an expression.

Here is some of the sample output from demo(plotmath):

enter image description here

RESTful URL design for search

My advice would be this:

/garages
  Returns list of garages (think JSON array here)
/garages/yyy
  Returns specific garage
/garage/yyy/cars
  Returns list of cars in garage
/garages/cars
  Returns list of all cars in all garages (may not be practical of course)
/cars
  Returns list of all cars
/cars/xxx
  Returns specific car
/cars/colors
  Returns lists of all posible colors for cars
/cars/colors/red,blue,green
  Returns list of cars of the specific colors (yes commas are allowed :) )

Edit:

/cars/colors/red,blue,green/doors/2
  Returns list of all red,blue, and green cars with 2 doors.
/cars/type/hatchback,coupe/colors/red,blue,green/
  Same idea as the above but a lil more intuitive.
/cars/colors/red,blue,green/doors/two-door,four-door
  All cars that are red, blue, green and have either two or four doors.

Hopefully that gives you the idea. Essentially your Rest API should be easily discoverable and should enable you to browse through your data. Another advantage with using URLs and not query strings is that you are able to take advantage of the native caching mechanisms that exist on the web server for HTTP traffic.

Here's a link to a page describing the evils of query strings in REST: http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful

I used Google's cache because the normal page wasn't working for me here's that link as well: http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful

Swift Open Link in Safari

In Swift 2.0:

UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

Redirect to Action in another controller

Use this:

return RedirectToAction("LogIn", "Account", new { area = "" });

This will redirect to the LogIn action in the Account controller in the "global" area.

It's using this RedirectToAction overload:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

How to style the menu items on an Android action bar

You have to change

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">

to

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Menu">

as well. This works for me.

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

_x000D_
_x000D_
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  },_x000D_
  handleChange(e) {_x000D_
    this.setState({email: e.target.value})_x000D_
  },_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!this.state.email}>Button</button>_x000D_
    </div>_x000D_
  }_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
_x000D_
_x000D_

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

How do I escape a single quote ( ' ) in JavaScript?

You can escape a ' in JavaScript like \'

On localhost, how do I pick a free port number?

For the sake of snippet of what the guys have explained above:

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

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

You can get a shorter version by using sys.path[0].

os.chdir(sys.path[0])

From http://docs.python.org/library/sys.html#sys.path

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter

HTML5 required attribute seems not working

Actually speaking, when I tried this, it worked only when I set the action and method value for the form. Funny how it works though!

What is difference between Errors and Exceptions?

Error is something that most of the time you cannot handle it.

Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.

try{
  //connect to database 1
}
catch(DatabaseConnctionException err){
  //connect to database 2
  //write the err to log
}

What are the differences between C, C# and C++ in terms of real-world applications?

My opinion is C# and ASP.NET would be the best of the three for development that is web biased.

I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.

I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.

The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).

Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.

So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.

How do I set default value of select box in angularjs

if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.

Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-

_x000D_
_x000D_
 <select id="uomList" ng-init="modelData.unitId"_x000D_
                         ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
_x000D_
_x000D_

Read SQL Table into C# DataTable

var table = new DataTable();    
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{      
    da.Fill(table);
}

How to check if internet connection is present in Java?

InetAddress.isReachable sometime return false if internet connection exist.

An alternative method to check internet availability in java is : This function make a real ICMP ECHO ping.

public static boolean isReachableByPing(String host) {
     try{
                String cmd = "";
                if(System.getProperty("os.name").startsWith("Windows")) {   
                        // For Windows
                        cmd = "ping -n 1 " + host;
                } else {
                        // For Linux and OSX
                        cmd = "ping -c 1 " + host;
                }

                Process myProcess = Runtime.getRuntime().exec(cmd);
                myProcess.waitFor();

                if(myProcess.exitValue() == 0) {

                        return true;
                } else {

                        return false;
                }

        } catch( Exception e ) {

                e.printStackTrace();
                return false;
        }
}

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

'Incomplete final line' warning when trying to read a .csv file into R

In various European locales, as the comma character serves as decimal point, the read.csv2 function should be used instead.

Java synchronized method lock on object, or method?

From "The Java™ Tutorials" on synchronized methods:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

From "The Java™ Tutorials" on synchronized blocks:

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

(Emphasis mine)

Suppose you have 2 non-interleaving variables. So you want to access to each one from a different threads at the same time. You need to define the lock not on the object class itself, but on the class Object like below (example from the second Oracle link):

public class MsLunch {

    private long c1 = 0;
    private long c2 = 0;

    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}

Actual meaning of 'shell=True' in subprocess

The other answers here adequately explain the security caveats which are also mentioned in the subprocess documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.

Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.

Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.

In the trivial case, to avoid shell=True, simply replace

subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)

with

subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])

Notice how the first argument is a list of strings to pass to execvp(), and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct). Maybe see also When to wrap quotes around a shell variable?

If you don't want to figure this out yourself, the shlex.split() function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.

As an aside, you very often want to avoid Popen if one of the simpler wrappers in the subprocess package does what you want. If you have a recent enough Python, you should probably use subprocess.run.

  • With check=True it will fail if the command you ran failed.
  • With stdout=subprocess.PIPE it will capture the command's output.
  • With text=True (or somewhat obscurely, with the synonym universal_newlines=True) it will decode output into a proper Unicode string (it's just bytes in the system encoding otherwise, on Python 3).

If not, for many tasks, you want check_output to obtain the output from a command, whilst checking that it succeeded, or check_call if there is no output to collect.

I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even subprocess.run('echo "$HOME"', shell=True) is not portable to Windows.

List attributes of an object

In addition to these answers, I'll include a function (python 3) for spewing out virtually the entire structure of any value. It uses dir to establish the full list of property names, then uses getattr with each name. It displays the type of every member of the value, and when possible also displays the entire member:

import json

def get_info(obj):

  type_name = type(obj).__name__
  print('Value is of type {}!'.format(type_name))
  prop_names = dir(obj)

  for prop_name in prop_names:
    prop_val = getattr(obj, prop_name)
    prop_val_type_name = type(prop_val).__name__
    print('{} has property "{}" of type "{}"'.format(type_name, prop_name, prop_val_type_name))

    try:
      val_as_str = json.dumps([ prop_val ], indent=2)[1:-1]
      print('  Here\'s the {} value: {}'.format(prop_name, val_as_str))
    except:
      pass

Now any of the following should give insight:

get_info(None)
get_info('hello')

import numpy
get_info(numpy)
# ... etc.

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

Is there a java setting for disabling certificate validation?

In Axis webservice and if you have to disable the certificate checking then use below code:

AxisProperties.setProperty("axis.socketSecureFactory","org.apache.axis.components.net.SunFakeTrustSocketFactory");

Pass data from Activity to Service using an Intent

Another posibility is using intent.getAction:

In Service:

public class SampleService inherits Service{
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        //System.out.println("ACTION: "+action);
        switch (action){
            case ACTION_START:
                startingService(intent.getIntExtra("valueStart",0));
                break;
            case ACTION_DO_SOMETHING_1:
                int value1,value2;
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething1(value1,value2);
                break;
            case ACTION_DO_SOMETHING_2:
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething2(value1,value2);
                break;
            case ACTION_STOP_SERVICE:
                stopService();
                break;
        }
        return START_STICKY;
    }

    public void startingService(int value){
        //calling when start
    }

    public void doSomething1(int value1, int value2){
        //...
    }

    public void doSomething2(int value1, int value2){
        //...
    }

    public void stopService(){
        //...destroy/release objects
        stopself();
    }
}

In Activity:

public void startService(int value){
    Intent myIntent = new Intent(SampleService.ACTION_START);
    myIntent.putExtra("valueStart",value);
    startService(myIntent);
}

public void serviceDoSomething1(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void serviceDoSomething2(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void endService(){
    Intent myIntent = new Intent(SampleService.STOP_SERVICE);
    startService(myIntent);
}

Finally, In Manifest file:

<service android:name=".SampleService">
    <intent-filter>
        <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
        <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
    </intent-filter>
</service>

How to update fields in a model without creating a new record in django?

If you get a model instance from the database, then calling the save method will always update that instance. For example:

t = TemperatureData.objects.get(id=1)
t.value = 999  # change field
t.save() # this will update only

If your goal is prevent any INSERTs, then you can override the save method, test if the primary key exists and raise an exception. See the following for more detail:

Line break in SSRS expression

You Can Use This One

="Line 1" & "<br>" & "Line 2"

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

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

In this post Scrollview vertical and horizontal in android they talk about a possible solution, quoting:

Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: http://blog.gorges.us/2010/06/android-two-dimensional-scrollview

Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:

Solution: Replace the statement on line 808 by the following:

final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

i solved this problem in a easy way, that worked for me. i had the seme problem "com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure". In my db.properties file i had this : url:jdbc:mysql://localhost:90/myDB, only removed the port url , resulting in this manner url:jdbc:mysql://localhost/myDB and that worked for me.

NotificationCenter issue on Swift 3

For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:

// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
    class MyReceivingClass {

    // ---------------------------------------------
    // INIT -> GOOD PLACE FOR REGISTERING
    // ---------------------------------------------
    init() {
        // WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)

        // Register without parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)

        // Register WITH parameter
        NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
    }

    // ---------------------------------------------
    // DE-INIT -> LAST OPTION FOR RE-REGISTERING
    // ---------------------------------------------
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITHOUT PARAMETER
    // ---------------------------------------------
    @objc func handleNotification() {
        print("RECEIVED ANY NOTIFICATION")
    }

    // ---------------------------------------------
    // HANDLE NOTIFICATION WITH PARAMETER
    // ---------------------------------------------
    @objc func handle(withNotification notification : NSNotification) {
        print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
    }
}

In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):

// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {

    print("POSTING")

    // Define identifiyer
    let notificationName = Notification.Name.UIApplicationWillResignActive

    // Post notification
    NotificationCenter.default.post(name: notificationName, object: nil)
}

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

Detecting locked tables (locked by LOCK TABLE)

This article describes how to get information about locked MySQL resources. mysqladmin debug might also be of some use.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

In my case I was using the wrong MSBuild.exe, the one found in:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319

To resolve the error, I updated my PATH environment variable to start using the Visual Studio 2017 MSBuild.exe:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSbuild.exe

Please see this link for details: Error CS1056: Unexpected character '$' running the msbuild on a tfs continuous integration process

How to do URL decoding in Java?

This has been answered before (although this question was first!):

"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

As URL class documentation states:

The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

Basically:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());

will give you:

https://mywebsite/docs/english/site/mybook.do?request_type

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

What is the difference between Step Into and Step Over in a debugger

step into will dig into method calls
step over will just execute the line and go to the next one

How create table only using <div> tag and Css

A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS

.common_table{
    display:table;
    border-collapse:collapse;
    border:1px solid grey;
    }
.common_table DIV{
    display:table-row;
    border:1px solid grey;
    }
.common_table DIV DIV{
    display:table-cell;
    }

HTML

<DIV class="common_table">
   <DIV><DIV>this is a cell</DIV></DIV>
   <DIV><DIV>this is a cell</DIV></DIV>
</DIV>

Works on Chrome and Firefox

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Slightly unrelated to your problem, so here's one for Google.

If you didn't mysqldump the SQL, it might be that your SQL is broken.

I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.

That's a fantastic error message to get for a runaway string, thanks for that MySQL!

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

How can I Remove .DS_Store files from a Git repository?

In case you want to remove DS_Store files to every folder and subfolder:


In case of already committed DS_Store:

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

Ignore them by:

echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global

Remove Select arrow on IE

I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.

Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.

Anyway, let's start with the modern browsers and then we will see the solution for the older ones.

Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+

For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.

To do so, you have to reset the browser's default style for the select tag and set new background rules (like suggested before).

select {
    /* you should keep these firsts rules in place to maintain cross-browser behaviour */
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background-image: url('<custom_arrow_image_url_here>');
    background-position: 98% center;
    background-repeat: no-repeat;
    outline: none;
    ...
}

The appearance rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.

The background rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).

In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.

Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font

This is the harder part... Or maybe not.

There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select CSS rule for more details about the inline SVG used).

The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html tag to recognize the older IE browser.

After that, every select in the HTML have to be wrapped by a div (or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.

<div class="selectTagWrapper prefix-icon-arrow-down-fill">
    ...
</div>

In easy words, this wrapper is used to simulate the select tag.

To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select.

Notice that we cannot use the select border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden rule applied to the select itself.

The custom arrow icon-font is placed in the pseudo class :before where the rule content contains the reference for the arrow (in this case it is a right parenthesis).

We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).

.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
    content: ")";
    position: absolute;
    top: 43%;
    left: 93%;
    font-size: 6px;
    ...
}

You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image rule or making a new icon font file by yourself.

pyplot axes labels for subplots

The methods in the other answers will not work properly when the yticks are large. The ylabel will either overlap with ticks, be clipped on the left or completely invisible/outside of the figure.

I've modified Hagne's answer so it works with more than 1 column of subplots, for both xlabel and ylabel, and it shifts the plot to keep the ylabel visible in the figure.

def set_shared_ylabel(a, xlabel, ylabel, labelpad = 0.01, figleftpad=0.05):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0,0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0,0].get_position().y1
    bottom = a[-1,-1].get_position().y0

    # get the coordinates of the left side of the tick labels
    x0 = 1
    x1 = 1
    for at_row in a:
        at = at_row[0]
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
            x1 = bboxes.x1
    tick_label_left = x0

    # shrink plot on left to prevent ylabel clipping
    # (x1 - tick_label_left) is the x coordinate of right end of tick label,
    # basically how much padding is needed to fit tick labels in the figure
    # figleftpad is additional padding to fit the ylabel
    plt.subplots_adjust(left=(x1 - tick_label_left) + figleftpad)

    # set position of label, 
    # note that (figleftpad-labelpad) refers to the middle of the ylabel
    a[-1,-1].set_ylabel(ylabel)
    a[-1,-1].yaxis.set_label_coords(figleftpad-labelpad,(bottom + top)/2, transform=f.transFigure)

    # set xlabel
    y0 = 1
    for at in axes[-1]:
        at.set_xlabel('')  # just to make sure we don't and up with multiple labels
        bboxes, _ = at.xaxis.get_ticklabel_extents(fig.canvas.renderer)
        bboxes = bboxes.inverse_transformed(fig.transFigure)
        yt = bboxes.y0
        if yt < y0:
            y0 = yt
    tick_label_bottom = y0

    axes[-1, -1].set_xlabel(xlabel)
    axes[-1, -1].xaxis.set_label_coords((left + right) / 2, tick_label_bottom - labelpad, transform=fig.transFigure)

It works for the following example, while Hagne's answer won't draw ylabel (since it's outside of the canvas) and KYC's ylabel overlaps with the tick labels:

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
set_shared_ylabel(axes, 'common X', 'common Y')
plt.show()

Alternatively, if you are fine with colorless axis, I've modified Julian Chen's solution so ylabel won't overlap with tick labels.

Basically, we just have to set ylims of the colorless so it matches the largest ylims of the subplots so the colorless tick labels sets the correct location for the ylabel.

Again, we have to shrink the plot to prevent clipping. Here I've hard coded the amount to shrink, but you can play around to find a number that works for you or calculate it like in the method above.

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
miny = maxy = 0
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
    miny = min(miny, a.get_ylim()[0])
    maxy = max(maxy, a.get_ylim()[1])

# add a big axes, hide frame
# set ylim to match the largest range of any subplot
ax_invis = fig.add_subplot(111, frameon=False)
ax_invis.set_ylim([miny, maxy])

# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")

# shrink plot to prevent clipping
plt.subplots_adjust(left=0.15)
plt.show()

Python error message io.UnsupportedOperation: not readable

You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

file = open("File.txt","r")

Additionally, here are the other options:

"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing.  The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.

Convert HTML to NSAttributedString in iOS

Swift 3.0 Xcode 8 Version

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
    return html
}

How to create an email form that can send email using html

Short answer, you can't.

HTML is used for the page's structure and can't send e-mails, you will need a server side language (such as PHP) to send e-mails, you can also use a third party service and let them handle the e-mail sending for you.

Check if URL has certain string with PHP

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];


if (!strpos($url,'car')) {
    echo 'Car exists.';
} else {
    echo 'No cars.';
}

This seems to work.

How can I customize the tab-to-space conversion factor?

If this is for Angular 2, and the CLI is generating files which you would like differently formatted, you can edit these files to change what is generated:

npm_modules/@angular/cli/blueprints/component/files/__path__/*

Not massively recommended as an npm update will delete your work, but it has saved me a lot of time.

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

Numpy: Divide each row by a vector element

Adding to the answer of stackoverflowuser2010, in the general case you can just use

data = np.array([[1,1,1],[2,2,2],[3,3,3]])

vector = np.array([1,2,3])

data / vector.reshape(-1,1)

This will turn your vector into a column matrix/vector. Allowing you to do the elementwise operations as you wish. At least to me, this is the most intuitive way going about it and since (in most cases) numpy will just use a view of the same internal memory for the reshaping it's efficient too.

How to rollback just one step using rake db:migrate

If the version is 20150616132425, then use:

rails db:migrate:down VERSION=20150616132425

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Update MySQL using HTML Form and PHP

You have already executed your query here

$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");

So this line has the problem

$retval = mysql_query( $sql, $conn ); //$sql is not a query its a result set here

Try something like this:

$sql = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'";    
$retval = mysql_query( $sql, $conn ); //execute your query

As a sidenote: MySQL_* extension is deprecated use MySQLi_* or PDO instead.

How to remove package using Angular CLI?

npm uninstal @angular/material

and also clear file custom-theme.scss

What does 'git remote add upstream' help achieve?

This is useful when you have your own origin which is not upstream. In other words, you might have your own origin repo that you do development and local changes in and then occasionally merge upstream changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.

How to get document height and width without using jquery

Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):

Math.max(
    document.documentElement["clientWidth"],
    document.body["scrollWidth"],
    document.documentElement["scrollWidth"],
    document.body["offsetWidth"],
    document.documentElement["offsetWidth"]
);

just replace Width for "Height" to get Height.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

'Java' is not recognized as an internal or external command

Assume, Java/JDK is installed to the folder: C:\Program Files\Java:

Java/JDK installation path

Follow the steps:

  1. Goto Control Panel ? System ? Advanced system settings ? Advanced ? Environment variables (Win+Pause/Break for System in Control Panel)
  2. In the System variables section click on New…
  3. In Variable name write: JAVA_HOME
  4. In Variable value write: C:\Program Files\Java\bin, press OK: Add JAVA_HOME
  5. In the System variables section double click on Path
  6. Press New and write C:\Program Files\Java\bin, press OK: Add Java Path
  7. In Environment variables window press OK
  8. Restart/Run cmd.exe and write: java --version: Java version CMD

'profile name is not valid' error when executing the sp_send_dbmail command

In my case, I was moving a SProc between servers and the profile name in my TSQL code did not match the profile name on the new server.

Updating TSQL profile name == New server profile name fixed the error for me.

Why does pycharm propose to change method to static

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesn't use self.

If you're sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

Workaround #1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

Workaround #2 [Thanks @DavidPärsson]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didn't happen to do anything with the instance. If I made those static I'd get "TypeError: 'staticmethod' object is not callable".

In support of the OP's consternation, suggesting you add staticmethod whenever you can, goes against the principle that it's easier to make code less restrictive later, than to make it more -- making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

Guesses as to why this warning exists:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorrall's points out, it gets your attention when self was inadvertently left out of the function.
  • It's a cue to rethink the object model; maybe the function does not belong in this class at all.

Find and replace with sed in directory and sub directories

Your find should look like that to avoid sending directory names to sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

Is it possible to have different Git configuration for different projects?

Thanks @crea1

A small variant:

As it is written on https://git-scm.com/docs/git-config#_includes:

If the pattern ends with /, ** will be automatically added. For example, the pattern foo/ becomes foo/**. In other words, it matches foo and everything inside, recursively.

So I use in my case,
~/.gitconfig :

[user] # as default, personal needs
    email = [email protected]
    name = bcag2
[includeIf "gitdir:~/workspace/"] # job needs, like workspace/* so all included projects
    path = .gitconfig-job

# all others section: core, alias, log…

So If the project directory is in my ~/wokspace/, default user settings is replace with
~/.gitconfig-job :

[user]
name = John Smith
email = [email protected]

Build tree array from flat array in javascript

_x000D_
_x000D_
var data = [{"country":"india","gender":"male","type":"lower","class":"X"},_x000D_
   {"country":"china","gender":"female","type":"upper"},_x000D_
   {"country":"india","gender":"female","type":"lower"},_x000D_
   {"country":"india","gender":"female","type":"upper"}];_x000D_
var seq = ["country","type","gender","class"];_x000D_
var treeData = createHieArr(data,seq);_x000D_
console.log(treeData)_x000D_
function createHieArr(data,seq){_x000D_
 var hieObj = createHieobj(data,seq,0),_x000D_
  hieArr = convertToHieArr(hieObj,"Top Level");_x000D_
  return [{"name": "Top Level", "parent": "null",_x000D_
         "children" : hieArr}]_x000D_
 function convertToHieArr(eachObj,parent){_x000D_
  var arr = [];_x000D_
  for(var i in eachObj){_x000D_
   arr.push({"name":i,"parent":parent,"children":convertToHieArr(eachObj[i],i)})_x000D_
  }_x000D_
  return arr;_x000D_
 }_x000D_
 function createHieobj(data,seq,ind){_x000D_
  var s = seq[ind];_x000D_
  if(s == undefined){_x000D_
   return [];_x000D_
  }_x000D_
  var childObj = {};_x000D_
  for(var ele of data){_x000D_
   if(ele[s] != undefined){_x000D_
    if(childObj[ele[s]] == undefined){_x000D_
     childObj[ele[s]] = [];_x000D_
    }_x000D_
    childObj[ele[s]].push(ele);_x000D_
   }_x000D_
  }_x000D_
  ind = ind+1;_x000D_
  for(var ch in childObj){_x000D_
   childObj[ch] = createHieobj(childObj[ch],seq,ind)_x000D_
  }_x000D_
  return childObj;_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.

<style>
.hidden{
display:none
}
</style>

<textarea class="hidden" rows="4" cols="50">

</textarea>


$("#hiddentextarea").change(function() {

alert('Textarea changed');

})

Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

Make a UIButton programmatically in Swift

Swift 2.2 Xcode 7.3

Since Objective-C String Literals are deprecated now for button callback methods

let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)

func buttonClicked() {
     print("Button Clicked")
}

Swift 3 Xcode 8

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

func buttonClicked() {
    print("Button Clicked")
}

Swift 4 Xcode 9

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

@objc func buttonClicked() {
    print("Button Clicked")
}

Rounding float in Ruby

You can also provide a negative number as an argument to the round method to round to the nearest multiple of 10, 100 and so on.

# Round to the nearest multiple of 10. 
12.3453.round(-1)       # Output: 10

# Round to the nearest multiple of 100. 
124.3453.round(-2)      # Output: 100

How to add many functions in ONE ng-click?

Follow the below

ng-click="anyFunction()"

anyFunction() {
   // call another function here
   anotherFunction();
}

Append to the end of a Char array in C++

You should have enough space for array1 array and use something like strcat to contact array1 to array2:

char array1[BIG_ENOUGH];
char array2[X];
/* ......             */
/* check array bounds */
/* ......             */

strcat(array1, array2);

Passing command line arguments from Maven as properties in pom.xml

Inside pom.xml

<project>

.....

<profiles>
    <profile>
        <id>linux64</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build_os>linux</build_os>
            <build_ws>gtk</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>

    <profile>
        <id>win64</id>
        <activation>
            <property>
                <name>env</name>
                <value>win64</value>
            </property>
        </activation>
        <properties>
            <build_os>win32</build_os>
            <build_ws>win32</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>
</profiles>

.....

<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>${tycho.version}</version>
    <configuration>
        <environments>
            <environment>
                <os>${build_os}</os>
                <ws>${build_ws}</ws>
                <arch>${build_arch}</arch>
            </environment>
        </environments>
    </configuration>
</plugin>

.....

In this example when you run the pom without any argument mvn clean install default profile will execute.

When executed with mvn -Denv=win64 clean install

win64 profile will executed.

Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html

Fatal error: "No Target Architecture" in Visual Studio

Besides causes described already, I received this error because I'd include:

#include <fileapi.h>

Apparently it was not needed (despite of CreateDirectoryW call). After commenting out, compiler was happy. Very strange.

jQuery Mobile: Stick footer to bottom of page

Fixed basics

To enable this behavior on a header or footer, add the data-position="fixed" attribute to a jQuery Mobile header or footer element.

<div data-role="footer" data-position="fixed">
    <h1>Fixed Footer!</h1>
</div>

Find multiple files and rename them in Linux

If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

#on current folder
rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *

-dp -1 will make it recursive to all subdirectories.

-fo implies file only mode.

-ssf '_dbg' searches for files with _dbg in the filename.

-rs '/_dbg//' replaces _dbg with empty string.

You can run the above command with the path of the CURRENT_FOLDER too:

rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory

How to access the elements of a function's return array?

You can add array keys to your return values and then use these keys to print the array values, as shown here:

function data() {
    $out['a'] = "abc";
    $out['b'] = "def";
    $out['c'] = "ghi";
    return $out;
}

$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];

Python - 'ascii' codec can't decode byte

You use u"??".encode('utf8') to encode an unicode string. But if you want to represent "??", you should decode it. Just like:

"??".decode("utf8")

You will get what you want. Maybe you should learn more about encode & decode.

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

How to have Android Service communicate with Activity

You may also use LiveData that works like an EventBus.

class MyService : LifecycleService() {
    companion object {
        val BUS = MutableLiveData<Any>()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        val testItem : Object

        // expose your data
        if (BUS.hasActiveObservers()) {
            BUS.postValue(testItem)
        }

        return START_NOT_STICKY
    }
}

Then add an observer from your Activity.

MyService.BUS.observe(this, Observer {
    it?.let {
        // Do what you need to do here
    }
})

You can read more from this blog.

Using css transform property in jQuery

I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Insert Data Into Tables Linked by Foreign Key

Use stored procedures.

And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

Sleep/Wait command in Batch

Ok, yup you use the timeout command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window. And here is the script:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing

Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"

matplotlib: how to draw a rectangle on image

From my understanding matplotlib is a plotting library.

If you want to change the image data (e.g. draw a rectangle on an image), you could use PIL's ImageDraw, OpenCV, or something similar.

Here is PIL's ImageDraw method to draw a rectangle.

Here is one of OpenCV's methods for drawing a rectangle.

Your question asked about Matplotlib, but probably should have just asked about drawing a rectangle on an image.

Here is another question which addresses what I think you wanted to know: Draw a rectangle and a text in it using PIL

Custom Date/Time formatting in SQL Server

in MS SQL Server you can do:

SET DATEFORMAT ymd

year, month, day,

SQL Server IF EXISTS THEN 1 ELSE 2

In SQL without SELECT you cannot result anything. Instead of IF-ELSE block I prefer to use CASE statement for this

SELECT CASE
         WHEN EXISTS (SELECT 1
                      FROM   tblGLUserAccess
                      WHERE  GLUserName = 'xxxxxxxx') THEN 1
         ELSE 2
       END 

How do I create a random alpha-numeric string in C++?

My 2p solution:

#include <random>
#include <string>

std::string random_string(std::string::size_type length)
{
    static auto& chrs = "0123456789"
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    thread_local static std::mt19937 rg{std::random_device{}()};
    thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);

    std::string s;

    s.reserve(length);

    while(length--)
        s += chrs[pick(rg)];

    return s;
}

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

Quickly reading very large tables as dataframes

Here is an example that utilizes fread from data.table 1.8.7

The examples come from the help page to fread, with the timings on my windows XP Core 2 duo E8400.

library(data.table)
# Demo speedup
n=1e6
DT = data.table( a=sample(1:1000,n,replace=TRUE),
                 b=sample(1:1000,n,replace=TRUE),
                 c=rnorm(n),
                 d=sample(c("foo","bar","baz","qux","quux"),n,replace=TRUE),
                 e=rnorm(n),
                 f=sample(1:1000,n,replace=TRUE) )
DT[2,b:=NA_integer_]
DT[4,c:=NA_real_]
DT[3,d:=NA_character_]
DT[5,d:=""]
DT[2,e:=+Inf]
DT[3,e:=-Inf]

standard read.table

write.table(DT,"test.csv",sep=",",row.names=FALSE,quote=FALSE)
cat("File size (MB):",round(file.info("test.csv")$size/1024^2),"\n")    
## File size (MB): 51 

system.time(DF1 <- read.csv("test.csv",stringsAsFactors=FALSE))        
##    user  system elapsed 
##   24.71    0.15   25.42
# second run will be faster
system.time(DF1 <- read.csv("test.csv",stringsAsFactors=FALSE))        
##    user  system elapsed 
##   17.85    0.07   17.98

optimized read.table

system.time(DF2 <- read.table("test.csv",header=TRUE,sep=",",quote="",  
                          stringsAsFactors=FALSE,comment.char="",nrows=n,                   
                          colClasses=c("integer","integer","numeric",                        
                                       "character","numeric","integer")))


##    user  system elapsed 
##   10.20    0.03   10.32

fread

require(data.table)
system.time(DT <- fread("test.csv"))                                  
 ##    user  system elapsed 
##    3.12    0.01    3.22

sqldf

require(sqldf)

system.time(SQLDF <- read.csv.sql("test.csv",dbname=NULL))             

##    user  system elapsed 
##   12.49    0.09   12.69

# sqldf as on SO

f <- file("test.csv")
system.time(SQLf <- sqldf("select * from f", dbname = tempfile(), file.format = list(header = T, row.names = F)))

##    user  system elapsed 
##   10.21    0.47   10.73

ff / ffdf

 require(ff)

 system.time(FFDF <- read.csv.ffdf(file="test.csv",nrows=n))   
 ##    user  system elapsed 
 ##   10.85    0.10   10.99

In summary:

##    user  system elapsed  Method
##   24.71    0.15   25.42  read.csv (first time)
##   17.85    0.07   17.98  read.csv (second time)
##   10.20    0.03   10.32  Optimized read.table
##    3.12    0.01    3.22  fread
##   12.49    0.09   12.69  sqldf
##   10.21    0.47   10.73  sqldf on SO
##   10.85    0.10   10.99  ffdf

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

How to change JAVA.HOME for Eclipse/ANT

Under Windows you need to follow:

Start -> Control Panel -> System -> Advanced -> Environment Variables.

... and you need to set JAVA_HOME (which is distinct from the PATH variable you mention) to reference the JDK home directory, not the bin sub-directory; e.g. "C:\program files\java\jdk".

How to catch and print the full exception traceback without halting/exiting the program?

To get the precise stack trace, as a string, that would have been raised if no try/except were there to step over it, simply place this in the except block that catches the offending exception.

desired_trace = traceback.format_exc(sys.exc_info())

Here's how to use it (assuming flaky_func is defined, and log calls your favorite logging system):

import traceback
import sys

try:
    flaky_func()
except KeyboardInterrupt:
    raise
except Exception:
    desired_trace = traceback.format_exc(sys.exc_info())
    log(desired_trace)

It's a good idea to catch and re-raise KeyboardInterrupts, so that you can still kill the program using Ctrl-C. Logging is outside the scope of the question, but a good option is logging. Documentation for the sys and traceback modules.

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
  • -dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.
  • -r300 sets the desired DPI to 300 (the default is 72)
  • -sDEVICE specifies the output format (See the Devices section of the manual for other choices.)
  • -o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
  • This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.

Unable to set variables in bash script

here's your amended script

#!/bin/bash    
folder="ABC" #no spaces between assignment    
useracct='test'    
day=$(date "+%d") # use $() to assign return value of date command to variable    
month=$(date "+%B")     
year=$(date "+%Y")    
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"    
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"    
ECHO "Network is $network" $network    
ECHO "day is $day"    
ECHO "Month is $month"    
ECHO "YEAR is $year"    
ECHO "source is $folderToBeMoved"    
ECHO "dest is $newfoldername"    

mkdir "$newfoldername"    
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
 rm "$folderToBeMoved";
fi

HTTP Error 500.30 - ANCM In-Process Start Failure

I looked at the Windows Logs under Application. It displayed the error message and stack trace. I found out I was missing a folder called node_modules. I created that folder and that fixed it.

I did not make any changes to web.config or the project file. My .NETCoreApp version was 3.1

Download a single folder or directory from a GitHub repo

I work with CentOS 7 servers on which I don't have root access, nor git, svn, etc (nor want to!) so made a python script to download any github folder: https://github.com/andrrrl/github-folder-downloader

Usage is simple, just copy the relevant part from a github project, let's say the project is https://github.com/MaxCDN/php-maxcdn/, and you want a folder where some source files are only, then you need to do something like:

$ python gdownload.py "/MaxCDN/php-maxcdn/tree/master/src" /my/target/dir/
(will create target folder if doesn't exist)

It requires lxml library, can be installed with easy_install lxml
If you don't have root access (like me) you can create a .pydistutils.py file into your $HOME dir with these contents: [install] user=1 And easy_install lxml will just work (ref: https://stackoverflow.com/a/33464597/591257).

Using "margin: 0 auto;" in Internet Explorer 8

"margin: 0 auto" only centers an element in IE if the parent element has a "text-align: center".

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

Render HTML to an image

You can use an HTML to PDF tool like wkhtmltopdf. And then you can use a PDF to image tool like imagemagick. Admittedly this is server side and a very convoluted process...

ExecutorService, how to wait for all tasks to finish

You could wait jobs to finish on a certain interval:

int maxSecondsPerComputeDTask = 20;
try {
    while (!es.awaitTermination(uniquePhrases.size() * maxSecondsPerComputeDTask, TimeUnit.SECONDS)) {
        // consider giving up with a 'break' statement under certain conditions
    }
} catch (InterruptedException e) {
    throw new RuntimeException(e);    
}

Or you could use ExecutorService.submit(Runnable) and collect the Future objects that it returns and call get() on each in turn to wait for them to finish.

ExecutorService es = Executors.newFixedThreadPool(2);
Collection<Future<?>> futures = new LinkedList<<Future<?>>();
for (DataTable singleTable : uniquePhrases) {
    futures.add(es.submit(new ComputeDTask(singleTable)));
}
for (Future<?> future : futures) {
   try {
       future.get();
   } catch (InterruptedException e) {
       throw new RuntimeException(e);
   } catch (ExecutionException e) {
       throw new RuntimeException(e);
   }
}

InterruptedException is extremely important to handle properly. It is what lets you or the users of your library terminate a long process safely.

How to create a String with carriage returns?

Do this: Step 1: Your String

String str = ";;;;;;\n" +
            "Name, number, address;;;;;;\n" + 
             "01.01.12-16.02.12;;;;;;\n" + 
             ";;;;;;\n" + 
             ";;;;;;";

Step 2: Just replace all "\n" with "%n" the result looks like this

String str = ";;;;;;%n" +
             "Name, number, address;;;;;;%n" + 
             "01.01.12-16.02.12;;;;;;%n" + 
            ";;;;;;%n" + 
            ";;;;;;";

Notice I've just put "%n" in place of "\n"

Step 3: Now simply call format()

str=String.format(str);

That's all you have to do.

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

How to retrieve element value of XML using Java?

There are various APIs available to read/write XML files through Java. I would refer using StaX

Also This can be useful - Java XML APIs

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

Should each and every table have a primary key?

If you are using Hibernate its not possible to create an Entity without a primary key. This issues can create problem if you are working with an existing database which was created with plain sql/ddl scripts, and no primary key was added

SQL grouping by all the columns

You can use Group by All but be careful as Group by All will be removed from future versions of SQL server.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

How do I auto-submit an upload form when a file is selected?

This is my image upload solution, when user selected the file.

HTML part:

<form enctype="multipart/form-data" id="img_form" method="post">
    <input id="img_input" type="file" name="image" accept="image/*">
</form>

JavaScript:

document.getElementById('img_input').onchange = function () {
upload();
};
function upload() {
    var upload = document.getElementById('img_input');
    var image = upload.files[0];
    $.ajax({
      url:"/foo/bar/uploadPic",
      type: "POST",
      data: new FormData($('#img_form')[0]),
      contentType:false,
      cache: false,
      processData:false,
      success:function (msg) {}
      });
};

onclick go full screen

so simple try this

_x000D_
_x000D_
<div dir="ltr" style="text-align: left;" trbidi="on">_x000D_
<!-- begin snippet: js hide: false console: true babel: null -->
_x000D_
_x000D_
_x000D_

How is "mvn clean install" different from "mvn install"?

You can call more than one target goal with maven. mvn clean install calls clean first, then install. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.

clean removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).

we call it target in ant and goal in maven

Font-awesome, input type 'submit'

Well, technically it's not possible to get :before and :after pseudo elements work on input elements

From W3C:

12.1 The :before and :after pseudo-elements

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.


So I had a project where I had submit buttons in the form of input tags and for some reason the other developers restricted me to use <button> tags instead of the usual input submit buttons, so I came up with another solution, of wrapping the buttons inside a span set to position: relative; and then absolutely positioning the icon using :after pseudo.

Note: The demo fiddle uses the content code for FontAwesome 3.2.1 so you may need to change the value of content property accordingly.

HTML

<span><input type="submit" value="Send" class="btn btn-default" /></span>

CSS

input[type="submit"] {
    margin: 10px;
    padding-right: 30px;
}

span {
    position: relative;
}

span:after {
    font-family: FontAwesome;
    content: "\f004"; /* Value may need to be changed in newer version of font awesome*/
    font-size: 13px;
    position: absolute;
    right: 20px;
    top: 1px;
    pointer-events: none;
}

Demo

Now here everything is self explanatory here, about one property i.e pointer-events: none;, I've used that because on hovering over the :after pseudo generated content, your button won't click, so using the value of none will force the click action to go pass through that content.

From Mozilla Developer Network :

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

Hover the heart font/icon Demo and see what happens if you DON'T use pointer-events: none;

How to kill a while loop with a keystroke?

There is always sys.exit().

The system library in Python's core library has an exit function which is super handy when prototyping. The code would be along the lines of:

import sys

while True:
    selection = raw_input("U: Create User\nQ: Quit")
    if selection is "Q" or selection is "q":
        print("Quitting")
        sys.exit()
    if selection is "U" or selection is "u":
        print("User")
        #do_something()

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
    System.out.println(d);
    System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

Why can't I see the "Report Data" window when creating reports?

Open report in Report designer

Go to View menu -> Report data

Multithreading in Bash

Bash job control involves multiple processes, not multiple threads.

You can execute a command in background with the & suffix.

You can wait for completion of a background command with the wait command.

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of | is connected to stdin of command at right.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Hive insert query like SQL

Enter the following command to insert data into the testlog table with some condition:

INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;

Disable browsers vertical and horizontal scrollbars

So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll="no" on the body element as well and/or place overflow:hidden on the html element as well.

You can take this further when you need to 'take control' of the view port you can do this:-

<style>
 body {width:100%; height:100%; overflow:hidden; margin:0; }
 html {width:100%; height:100%; overflow:hidden; }
</style>

An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.

Rails migration for change column

You can also use a block if you have multiple columns to change within a table.

Example:

change_table :table_name do |t|
  t.change :column_name, :column_type, {options}
end

See the API documentation on the Table class for more details.

How to convert hex strings to byte values in Java

A long way to go :). I am not aware of methods to get rid of long for statements

ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
    byte[] bArr = ss.getBytes();
    for(Byte b : bArr) {
        bList.add(b);
    }
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
    bArr[i] = bList.get(i);
}

Iterate through a C++ Vector using a 'for' loop

The cleanest way of iterating through a vector is via iterators:

for (auto it = begin (vector); it != end (vector); ++it) {
    it->doSomething ();
}

or (equivalent to the above)

for (auto & element : vector) {
    element.doSomething ();
}

Prior to C++0x, you have to replace auto by the iterator type and use member functions instead of global functions begin and end.

This probably is what you have seen. Compared to the approach you mention, the advantage is that you do not heavily depend on the type of vector. If you change vector to a different "collection-type" class, your code will probably still work. You can, however, do something similar in Java as well. There is not much difference conceptually; C++, however, uses templates to implement this (as compared to generics in Java); hence the approach will work for all types for which begin and end functions are defined, even for non-class types such as static arrays. See here: How does the range-based for work for plain arrays?

Remove plot axis values

Remove numbering on x-axis or y-axis:

plot(1:10, xaxt='n')
plot(1:10, yaxt='n')

If you want to remove the labels as well:

plot(1:10, xaxt='n', ann=FALSE)
plot(1:10, yaxt='n', ann=FALSE)

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

align 3 images in same row with equal spaces?

The modern approach: flexbox

Simply add the following CSS to the container element (here, the div):

div {
  display: flex;
  justify-content: space-between;
}

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The old way (for ancient browsers - prior to flexbox)

Use text-align: justify; on the container element.

Then stretch the content to take up 100% width

MARKUP

<div>
 <img src="http://placehold.it/100x100" alt=""  /> 
 <img src="http://placehold.it/100x100" alt=""  />
 <img src="http://placehold.it/100x100" alt="" />
</div>

CSS

div {
    text-align: justify;
}

div img {
    display: inline-block;
    width: 100px;
    height: 100px;
}

div:after {
    content: '';
    display: inline-block;
    width: 100%;
}

_x000D_
_x000D_
div {_x000D_
    text-align: justify;_x000D_
}_x000D_
_x000D_
div img {_x000D_
    display: inline-block;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
div:after {_x000D_
    content: '';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
}
_x000D_
<div>_x000D_
 <img src="http://placehold.it/100x100" alt=""  /> _x000D_
 <img src="http://placehold.it/100x100" alt=""  />_x000D_
 <img src="http://placehold.it/100x100" alt="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

SMTP connect() failed PHPmailer - PHP

This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL

Difference Between Cohesion and Coupling

The term cohesion is indeed a little counter intuitive for what it means in software design.

Cohesion common meaning is that something that sticks together well, is united, which are characterized by strong bond like molecular attraction. However in software design, it means striving for a class that ideally does only one thing, so multiple sub-modules are not even involved.

Perhaps we can think of it this way. A part has the most cohesion when it is the only part (does only one thing and can't be broken down further). This is what is desired in software design. Cohesion simply is another name for "single responsibility" or "separation of concerns".

The term coupling on the hand is quite intuitive which means when a module doesn't depend on too many other modules and those that it connects with can be easily replaced for example obeying liskov substitution principle .

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

port 8080 is already in use and no process using 8080 has been listed

If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.

If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.

Increasing Google Chrome's max-connections-per-server limit to more than 6

There doesn't appear to be an external way to hack the behaviour of the executables.

You could modify the Chrome(ium) executables as this information is obviously compiled in. That approach brings a lot of problems with support and automatic upgrades so you probably want to avoid doing that. You also need to understand how to make the changes to the binaries which is not something most people can pick up in a few days.

If you compile your own browser you are creating a support issue for yourself as you are stuck with a specific revision. If you want to get new features and bug fixes you will have to recompile. All of this involves tracking Chrome development for bugs and build breakages - not something that a web developer should have to do.

I'd follow @BenSwayne's advice for now, but it might be worth thinking about doing some of the work outside of the client (the web browser) and putting it in a background process running on the same or different machines. This process can handle many more connections and you are just responsible for getting the data back from it. Since it is local(ish) you'll get results back quickly even with minimal connections.

Unable to install packages in latest version of RStudio and R Version.3.1.1

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) : 
  unsupported URL scheme
Warning: unable to access index for repository https://rweb.crmda.ku.edu/cran/src/contrib
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)

Workaround (I am using CentOS)...

install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')

I hope this saves someone hours of frustration.

How to initialize private static members in C++?

You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...

class Foo
   {
   public:
     int GetMyStatic() const
     {
       return *MyStatic();
     }

   private:
     static int* MyStatic()
     {
       static int mStatic = 0;
       return &mStatic;
     }
   }

The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.

PHPExcel set border and format for all sheets in spreadsheet

To answer your extra question:

You can set which rows should be repeated on every page using:

$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);

Now, row 1, 2, 3, 4 and 5 will be repeated.

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

Excel - programm cells to change colour based on another cell

Use conditional formatting.

You can enter a condition using any cell you like and a format to apply if the formula is true.

How to execute Python code from within Visual Studio Code

In order to launch the current file with the respective venv, I added this to file launch.json:

 {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "pythonPath": "${workspaceFolder}/FOO/DIR/venv/bin/python3"
    },

In the bin folder resides the source .../venv/bin/activate script which is regularly sourced when running from a regular terminal.

Recursive file search using PowerShell

To add to @user3303020 answer and output the search results into a file, you can run

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat > path_to_results_filename.txt

It may be easier to search for the correct file that way.

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

Python - converting a string of numbers into a list of int

Try this :

import re
[int(s) for s in re.split('[\s,]+',example_string)]

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

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

AWS EFS vs EBS vs S3 (differences & when to use?)

One word answer: MONEY :D

1 GB to store in US-East-1: (Updated at 2016.dec.20)

  • Glacier: $0.004/Month (Note: Major price cut in 2016)
  • S3: $0.023/Month
  • S3-IA (announced in 2015.09): $0.0125/Month (+$0.01/gig retrieval charge)
  • EBS: $0.045-0.1/Month (depends on speed - SSD or not) + IOPS costs
  • EFS: $0.3/Month

Further storage options, which may be used for temporary storing data while/before processing it:

  • SNS
  • SQS
  • Kinesis stream
  • DynamoDB, SimpleDB

The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.

There are a lot more differences between these services:

EFS is:

  • Generally Available (out of preview), but may not yet be available in your region
  • Network filesystem (that means it may have bigger latency but it can be shared across several instances; even between regions)
  • It is expensive compared to EBS (~10x more) but it gives extra features.
  • It's a highly available service.
  • It's a managed service
  • You can attach the EFS storage to an EC2 Instance
  • Can be accessed by multiple EC2 instances simultaneously
  • Since 2016.dec.20 it's possible to attach your EFS storage directly to on-premise servers via Direct Connect. ()

EBS is:

  • A block storage (so you need to format it). This means you are able to choose which type of file system you want.
  • As it's a block storage, you can use Raid 1 (or 0 or 10) with multiple block storages
  • It is really fast
  • It is relatively cheap
  • With the new announcements from Amazon, you can store up to 16TB data per storage on SSD-s.
  • You can snapshot an EBS (while it's still running) for backup reasons
  • But it only exists in a particular region. Although you can migrate it to another region, you cannot just access it across regions (only if you share it via the EC2; but that means you have a file server)
  • You need an EC2 instance to attach it to
  • New feature (2017.Feb.15): You can now increase volume size, adjust performance, or change the volume type while the volume is in use. You can continue to use your application while the change takes effect.

S3 is:

  • An object store (not a file system).
  • You can store files and "folders" but can't have locks, permissions etc like you would with a traditional file system
  • This means, by default you can't just mount S3 and use it as your webserver
  • But it's perfect for storing your images and videos for your website
  • Great for short term archiving (e.g. a few weeks). It's good for long term archiving too, but Glacier is more cost efficient.
  • Great for storing logs
  • You can access the data from every region (extra costs may apply)
  • Highly Available, Redundant. Basically data loss is not possible (99.999999999% durability, 99.9 uptime SLA)
  • Much cheaper than EBS.
  • You can serve the content directly to the internet, you can even have a full (static) website working direct from S3, without an EC2 instance

Glacier is:

  • Long term archive storage
  • Extremely cheap to store
  • Potentially very expensive to retrieve
  • Takes up to 4 hours to "read back" your data (so only store items you know you won't need to retrieve for a long time)

As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)

Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction

Using R to list all files with a specified extension

Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf

filenames <- Sys.glob("*.dbf")

convert string to specific datetime format?

Use DATE_FORMAT from Date Conversions:

In your initializer:

DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"

In your view:

date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format) 

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

Python - IOError: [Errno 13] Permission denied:

Just Close the opened file where you are going to write.

c# foreach (property in object)... Is there a simple way of doing this?

You can loop through all non-indexed properties of an object like this:

var s = new MyObject();
foreach (var p in s.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) {
    Console.WriteLine(p.GetValue(s, null));
}

Since GetProperties() returns indexers as well as simple properties, you need an additional filter before calling GetValue to know that it is safe to pass null as the second parameter.

You may need to modify the filter further in order to weed out write-only and otherwise inaccessible properties.

What's a clean way to stop mongod on Mac OS X?

If you have installed mongodb community server via homebrew, then you can do:

brew services list

This will list the current services as below:

Name              Status  User          Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

redis             stopped

Then you can restart mongodb by first stopping and restart:

brew services stop mongodb
brew services start mongodb

What does "Error: object '<myvariable>' not found" mean?

The error means that R could not find the variable mentioned in the error message.

The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x already, use a different variable name.)

x
## Error: object 'x' not found

The more complex version of the error has the same cause: calling a function when x does not exist.

mean(x)
## Error in mean(x) : 
##   error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found

Once the variable has been defined, the error will not occur.

x <- 1:5
x
## [1] 1 2 3 4 5     
mean(x)
## [1] 3

You can check to see if a variable exists using ls or exists.

ls()        # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.

Errors like this can occur when you are using non-standard evaluation. For example, when using subset, the error will occur if a column name is not present in the data frame to subset.

d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found

The error can also occur if you use custom evaluation.

get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found

In the second case, the var function cannot be found when R looks in the utils package's environment because utils is further down the search list than stats.


In more advanced use cases, you may wish to read:

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

In my particular case I was rendering a Rails partial without render layout: false which was re-rendering the entire layout, including all of the scripts in the <head> tag. Adding render layout: false to the controller action fixed the problem.

Laravel Eloquent: How to get only certain columns from joined tables

If I good understood this what is returned is fine except you want to see only one column. If so this below should be much simpler:

return Response::eloquent(Theme::with('user')->get(['username']));

How to run Conda?

you might want to try this:

for anaconda 2 :

export PATH=~/anaconda2/bin:$PATH

for anaconda 3 :

export PATH=~/anaconda3/bin:$PATH

for anaconda 4 :

Use the Anaconda Prompt

and then

conda --version

to confirm that it worked. The export PATH=~/anaconda3/bin:$PATH works but stops when you exit the terminal in order change that you have to run sudo nano ~/.bashrc and then copy the path into the file and save it after that you activate the changes using source .bashrc.

check with conda install anaconda-navigator if not installed follow the anaconda install instructions again

follow along with this video https://youtu.be/Pr25JlaXhpc

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

Submit form after calling e.preventDefault()

$('form').submit(function(e){

    var submitAllow = true;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });

    return submitAllow;

});

Easy way of running the same junit test over and over?

This is essentially the answer that Yishai provided above, re-written in Kotlin :

@RunWith(Parameterized::class)
class MyTest {

    companion object {

        private const val numberOfTests = 200

        @JvmStatic
        @Parameterized.Parameters
        fun data(): Array<Array<Any?>> = Array(numberOfTests) { arrayOfNulls<Any?>(0) }
    }

    @Test
    fun testSomething() { }
}

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

mvc:annotation-driven is a tag added in Spring 3.0 which does the following:

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)

context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

Limit the size of a file upload (html input element)

You can't do it client-side. You'll have to do it on the server.

Edit: This answer is outdated!

As the time of this edit, HTML file API is now supported on all major browsers.

I'd provide an update with solution, but @mark.inman.winning already did it.

Keep in mind that even if it's now possible to validate on the client, you should still validate it on the server, though. All client side validations can be bypassed.

Stash just a single file

You can interactively stash single lines with git stash -p (analogous to git add -p).

It doesn't take a filename, but you could just skip other files with d until you reached the file you want stashed and the stash all changes in there with a.

What is compiler, linker, loader?

compiler changes checks your source code for errors and changes it into object code.this is the code that operating system runs.

You often don't write a whole program in single file so linker links all your object code files.

your program wont get executed unless it is in main memory

Difference between @Mock and @InjectMocks

@Mock annotation mocks the concerned object.

@InjectMocks annotation allows to inject into the underlying object the different (and relevant) mocks created by @Mock.

Both are complementary.

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

Where to place JavaScript in an HTML file?

The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.

Comments in Markdown

This small research proves and refines the answer by Magnus

The most platform-independent syntax is

(empty line)
[comment]: # (This actually is the most platform independent comment)

Both conditions are important:

  1. Using # (and not <>)
  2. With an empty line before the comment. Empty line after the comment has no impact on the result.

The strict Markdown specification CommonMark only works as intended with this syntax (and not with <> and/or an empty line)

To prove this we shall use the Babelmark2, written by John MacFarlane. This tool checks the rendering of particular source code in 28 Markdown implementations.

(+ — passed the test, - — didn't pass, ? — leaves some garbage which is not shown in rendered HTML).

This proves the statements above.

These implementations fail all 7 tests. There's no chance to use excluded-on-render comments with them.

  • cebe/markdown 1.1.0
  • cebe/markdown MarkdownExtra 1.1.0
  • cebe/markdown GFM 1.1.0
  • s9e\TextFormatter (Fatdown/PHP)

What is the correct way to read from NetworkStream in .NET

Setting the underlying socket ReceiveTimeout property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout. You can read the docs for more information.

Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.

I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  var bytes = 0;
  client.Client.ReceiveTimeout = 20;
  do
  {
      try
      {
          bytes = stm.Read(resp, 0, resp.Length);
          memStream.Write(resp, 0, bytes);
      }
      catch (IOException ex)
      {
          // if the ReceiveTimeout is reached an IOException will be raised...
          // with an InnerException of type SocketException and ErrorCode 10060
          var socketExept = ex.InnerException as SocketException;
          if (socketExept == null || socketExept.ErrorCode != 10060)
              // if it's not the "expected" exception, let's not hide the error
              throw ex;
          // if it is the receive timeout, then reading ended
          bytes = 0;
      }
  } while (bytes > 0);
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

How to get first and last element in an array in java?

// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};

// First position
double firstNum = array_doubles[0]; // 2.5

// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6

This is the same in any array.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.

add modify this line in

m2.conf

set maven.home C:\Users\me\.m2

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Extract and delete all .gz in a directory- Linux

If you want to extract a single file use:

gunzip file.gz

It will extract the file and remove .gz file.

IE8 issue with Twitter Bootstrap 3

Make sure you link the bootstrap source separately

If you use LESS or SASS don't be to greedy with compiling the styles. In my project I included bootstrap.min.css in my main style, on the top of the file - so there should be only one request for all styles.

And because of that, the boostrap classes did not work properly. When added separately, works as expected.

Android ADB devices unauthorized

Try deleting the adbkey file from C/.android folder

and then run the commands as mentioned above i.e.

adb kill-server, adb start-server and adb devices

.

How do I check if an element is really visible with JavaScript?

Interesting question.

This would be my approach.

  1. At first check that element.style.visibility !== 'hidden' && element.style.display !== 'none'
  2. Then test with document.elementFromPoint(element.offsetLeft, element.offsetTop) if the returned element is the element I expect, this is tricky to detect if an element is overlapping another completely.
  3. Finally test if offsetTop and offsetLeft are located in the viewport taking scroll offsets into account.

Hope it helps.

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

How to style CSS role

please use :

 #content[role=main]{
   your style here
}

Changing file permission in Python

os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

stat

The following flags can also be used in the mode argument of os.chmod():

stat.S_ISUID Set UID bit.

stat.S_ISGID Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).

stat.S_ISVTX Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.

stat.S_IRWXU Mask for file owner permissions.

stat.S_IRUSR Owner has read permission.

stat.S_IWUSR Owner has write permission.

stat.S_IXUSR Owner has execute permission.

stat.S_IRWXG Mask for group permissions.

stat.S_IRGRP Group has read permission.

stat.S_IWGRP Group has write permission.

stat.S_IXGRP Group has execute permission.

stat.S_IRWXO Mask for permissions for others (not in group).

stat.S_IROTH Others have read permission.

stat.S_IWOTH Others have write permission.

stat.S_IXOTH Others have execute permission.

stat.S_ENFMT System V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.

stat.S_IREAD Unix V7 synonym for S_IRUSR.

stat.S_IWRITE Unix V7 synonym for S_IWUSR.

stat.S_IEXEC Unix V7 synonym for S_IXUSR.

Private pages for a private Github repo

Many answers are outdated (pre-Microsoft acquisition/free private repos). This one was written after the announcement of free private repos.

Github pages are not available on free private repos for individuals, as shown in the repo settings:

enter image description here

2020 (most basic plan is now "Team"):

upgrade to github team or make this reposiory public to enable Pages

NOTICE

All pages are public, even if you upgrade. Upgrading only enables the Pages feature on private repos, just like it enables other features. The Pages feature is publicly available static web hosting.

How can I remove leading and trailing quotes in SQL Server?

you could replace the quotes with an empty string...

SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
       LeadingAndTrailingRemoved = CASE 
           WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
           ELSE MyTest
           END  
FROM   MyTable

Create a custom View by inflating a layout?

Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

http://developer.android.com/guide/topics/ui/custom-components.html

How to replace space with comma using sed?

I just confirmed that:

cat file.txt | sed "s/\s/,/g"

successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.