Programs & Examples On #Gemcutter

AngularJS access scope from outside js function

It's been a long time since I asked this question, but here's an answer that doesn't require jquery:

function change() {
    var scope = angular.element(document.querySelector('#outside')).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

How to use a WSDL

In visual studio.

  • Create or open a project.
  • Right-click project from solution explorer.
  • Select "Add service refernce"
  • Paste the address with WSDL you received.
  • Click OK.

If no errors, you should be able to see the service reference in the object browser and all related methods.

android EditText - finished typing event

I had the same problem when trying to implement 'now typing' on chat app. try to extend EditText as follows:

public class TypingEditText extends EditText implements TextWatcher {

private static final int TypingInterval = 2000;


public interface OnTypingChanged {
    public void onTyping(EditText view, boolean isTyping);
}
private OnTypingChanged t;
private Handler handler;
{
    handler = new Handler();
}
public TypingEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.addTextChangedListener(this);
}

public TypingEditText(Context context) {
    super(context);
    this.addTextChangedListener(this);
}

public void setOnTypingChanged(OnTypingChanged t) {
    this.t = t;
}

@Override
public void afterTextChanged(Editable s) {
    if(t != null){
        t.onTyping(this, true);
        handler.removeCallbacks(notifier);
        handler.postDelayed(notifier, TypingInterval);
    }

}

private Runnable notifier = new Runnable() {

    @Override
    public void run() {
        if(t != null)
            t.onTyping(TypingEditText.this, false);
    }
};

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }


@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { }

}

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Above solution didn't work for me.

First run brew doctor. if you see something like

Error: unknown or unsupported macOS version: :mountain_lion

then there are some outdated packages which needs to be removed, mine was
mongodb.

It could be python@2, node@6 or some other package.

uninstall those packages brew uninstall [name] then run brew doctor to verify if everything is ok. Then you can reinstall those packages again after brew update && brew upgrade.

How can I get the source code of a Python function?

to summarize :

import inspect
print( "".join(inspect.getsourcelines(foo)[0]))

Swap x and y axis without manually swapping values

Microsoft Excel for Mac 2011 v 14.5.9

  • Click on the chart
  • Press the "Switch Plot" button under the "Charts" tab

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

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

Menu File ? Preferences ? Settings

Add to user settings:

"editor.tabSize": 2,
"editor.detectIndentation": false

then right click your document if you have one opened already and click Format Document to have your existing document follow these new settings.

Is log(n!) = T(n·log(n))?

http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.

enter image description here

Execute a shell script in current shell with sudo permission

What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp ... runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

(It's actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell -- meaning that in a sense it's already too late for it to do anything in the "current shell", because that's not where it executes.)

How can I view the contents of an ElasticSearch index?

If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:

curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_replicas": 0
    },
    "mappings": {            
        "doc": {
            "properties": {
                "message": {"type": "string", "analyzer": "snowball"}
            }
        }
    }

}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
  "message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
    "query": {
        "match": {
            "_id": "1"
        }
    },
    "facets": {
        "tokens": {
            "terms": {
                "field": "message"
            }
        }
    }
}
'
echo

How do I use the lines of a file as arguments of a command?

I suggest using:

command $(echo $(tr '\n' ' ' < parameters.cfg))

Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.

Removing path and extension from filename in PowerShell

@Keith,

here another option:

PS II> $f="C:\Downloads\ReSharperSetup.7.0.97.60.msi"

PS II> $f.split('\')[-1] -replace '\.\w+$'

PS II> $f.Substring(0,$f.LastIndexOf('.')).split('\')[-1]

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Don't Use Any, Use Generics

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
    
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
    
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
      obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'

Alternative syntax

const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];

How can I check whether a variable is defined in Node.js?

If your variable is not declared nor defined:

if ( typeof query !== 'undefined' ) { ... }

If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false or "")

if ( query ) { ... }

If your variable is declared but can be undefined or null:

if ( query != null ) { ... } // undefined == null

How to replace spaces in file names using a bash script

I just make one for my own purpose. You may can use it as reference.

#!/bin/bash
cd /vzwhome/c0cheh1/dev_source/UB_14_8
for file in *
do
    echo $file
    cd "/vzwhome/c0cheh1/dev_source/UB_14_8/$file/Configuration/$file"
    echo "==> `pwd`"
    for subfile in *\ *; do [ -d "$subfile" ] && ( mv "$subfile" "$(echo $subfile | sed -e 's/ /_/g')" ); done
    ls
    cd /vzwhome/c0cheh1/dev_source/UB_14_8
done

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

In Perl, how can I read an entire file into a string?

These are all good answers. BUT if you're feeling lazy, and the file isn't that big, and security is not an issue (you know you don't have a tainted filename), then you can shell out:

$x=`cat /tmp/foo`;    # note backticks, qw"cat ..." also works

Does not contain a static 'main' method suitable for an entry point

Try adding this method to a class and see if you still get the error:

[STAThread]
static void Main()
{
}

How do I view Android application specific cache?

Question: Where is application-specific cache located on Android?

Answer: /data/data

SQL to find the number of distinct values in a column

select count(*) from 
(
SELECT distinct column1,column2,column3,column4 FROM abcd
) T

This will give count of distinct group of columns.

Replace Both Double and Single Quotes in Javascript String

mystring = mystring.replace(/["']/g, "");

PPT to PNG with transparent background

Here is my preferred quickest and easiest solution. Works well if all slides have the same background color that you want to remove.

Step 1. In Powerpoint, "Save As" (shortcut F12) PNG, "All Slides".

Now you have a folder full of these PNG images of all your slides. The problem is that they still have a background. So now:

Step 2. Batch remove background color of all the PNG images, for example by following the steps in this SE answer.

"Sub or Function not defined" when trying to run a VBA script in Outlook

I think you need to update your libraries so that your VBA code works, your using ms outlook

Google API for location, based on user IP address

It looks like Google actively frowns on using IP-to-location mapping:

https://developers.google.com/maps/articles/geolocation?hl=en

That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:

http://caniuse.com/geolocation

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

Convert List to Pandas Dataframe Column

if your list looks like this: [1,2,3] you can do:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

to get this:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

to get this:

  col1
0   1
1   2
2   3

How to go from one page to another page using javascript?

You cannot sanely depend on client side JavaScript to determine if user credentials are correct. The browser (and all code that executes that) is under the control of the user, not you, so it is not trustworthy.

The username and password need to be entered using a form. The OK button will be a submit button. The action attribute must point to a URL which will be handled by a program that checks the credentials.

This program could be written in JavaScript, but how you go about that would depend on which server side JavaScript engine you were using. Note that SSJS is not a mainstream technology so if you really want to use it, you would have to use specialised hosting or admin your own server.

(Half a decade later and SSJS is much more common thanks to Node.js, it is still fairly specialised though).

If you want to redirect afterwards, then the program needs to emit an HTTP Location header.

Note that you need to check the credentials are OK (usually by storing a token, which isn't the actual password, in a cookie) before outputting any private page. Otherwise anyone could get to the private pages by knowing the URL (and thus bypassing the login system).

Generate fixed length Strings filled with whitespaces

String.format("%15s",s) // pads right
String.format("%-15s",s) // pads left

Great summary here

Google Play app description formatting

Experimentally, I've discovered that you can provide:

  • Single line breaks are ignored; double line breaks open a new paragraph.
  • Single line breaks can be enforced by ending a line with two spaces (similar to Markdown).
  • A limited set of HTML tags (optionally nested), specifically:
    • <b>…</b> for boldface,
    • <i>…</i> for italics,
    • <u>…</u> for underline,
    • <br /> to enforce a single line break,
    • I could not find any way to get strikethrough working (neither HTML or Markdown style).
  • A fully-formatted URL such as http://google.com; this appears as a hyperlink.
    (Beware that trying to use an HTML <a> tag for a custom description does not work and breaks the formatting.)
  • HTML character entities are supported, such as &rarr; (→), &trade; (™) and &reg; (®); consult this W3 reference for the exhaustive list.
  • UTF-8 encoded characters are supported, such as é, €, £, ‘, ’, ? and ?.
  • Indentation isn't strictly possible, but using a bullet and em space character looks reasonable (&#8226;&#8195; yields "• ").
  • Emoji are also supported (though on the website depends on the user's OS & browser).

Special notes concerning only Google Play app:

  • Some HTML tags only work in the app:
    • <blockquote>…</blockquote> to indent a paragraph of text,
    • <small>…</small> for slightly smaller text,
    • <big>…</big> for slightly larger text,
    • <sup>…</sup> and <sub>…</sub> for super- and subscripts.
    • <font color="#a32345">…</font> for setting font colors in HEX code.
  • Some symbols do not appear correctly, such as ‣.
  • All these notes also apply to the app's "What's New" section.

Special notes concerning only Google Play website:

  • All HTML formatting appears as plain text in the website's "What's New" section (i.e. users will see the HTML source).

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

MySQL: Get column name or alias from query

This is only an add-on to the accepted answer:

def get_results(db_cursor):
    desc = [d[0] for d in db_cursor.description]
    results = [dotdict(dict(zip(desc, res))) for res in db_cursor.fetchall()]
    return results

where dotdict is:

class dotdict(dict):
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

This will allow you to access much easier the values by column names.
Suppose you have a user table with columns name and email:

cursor.execute('select * from users')
results = get_results(cursor)
for res in results:
  print(res.name, res.email)

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Use of for_each on map elements

Will it work for you ?

class MyClass;
typedef std::pair<int,MyClass> MyPair;
class MyClass
{
  private:
  void foo() const{};
public:
static void Method(MyPair const& p) 
{
    //......
        p.second.foo();
};
}; 
// ...
std::map<int, MyClass> Map;
//.....
std::for_each(Map.begin(), Map.end(), (&MyClass::Method));

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Comparing two files in linux terminal

Try sdiff (man sdiff)

sdiff -s file1 file2

Lambda expression to convert array/List of String to array/List of Integers

EDIT: As pointed out in the comments, this is a much simpler version: Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray() This way we can skip the whole conversion to and from a list.


I found another one line solution, but it's still pretty slow (takes about 100 times longer than a for cycle - tested on an array of 6000 0's)

String[] stringArray = ...
int[] out= Arrays.asList(stringArray).stream().map(Integer::parseInt).mapToInt(i->i).toArray();

What this does:

  1. Arrays.asList() converts the array to a List
  2. .stream converts it to a Stream (needed to perform a map)
  3. .map(Integer::parseInt) converts all the elements in the stream to Integers
  4. .mapToInt(i->i) converts all the Integers to ints (you don't have to do this if you only want Integers)
  5. .toArray() converts the Stream back to an array

Object not found! The requested URL was not found on this server. localhost

I also had same error but with codeigniter application. I changed

  • my base URL in config.php to my localhost path

  • in htaccess I changed RewriteBase /"my folder name in htdocs"

    and I able to login to my application.

Hope it might help.

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

using OR and NOT in solr query

Instead of "NOT [condition]" use "(*:* NOT [condition])"

How to fix "unable to open stdio.h in Turbo C" error?

Since you did not mention which version of Turbo C this method below will cover both v2 and v3.

  • Click on 'Options', 'Directories', enter the proper location for the Include and Lib directories.

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How do I schedule jobs in Jenkins?

Jenkins uses Cron format on scheduling. You can refer this link for more detailhttps://en.wikipedia.org/wiki/Cron. One more thing, Jenkins provide us a very useful preview. Please take a look on the screenshot. enter image description here

I hope this help. Thanks

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

fatal: 'origin' does not appear to be a git repository

Try to create remote origin first, maybe is missing because you change name of the remote repo

git remote add origin URL_TO_YOUR_REPO

Default parameters with C++ constructors

I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).

That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:

class Vehicle {
public:
  Vehicle(int wheels, std::string name = "Mini");
};

Vehicle x = 5;  // this compiles just fine... did you really want it to?

Xcode 4 - "Archive" is greyed out?

I fixed this today...sort of. Although the archives still don't show up anywhere. But I got the Archive option back by going into Build Settings for the project and re-assigning my certs under "Code Signing Identity" for each build. They seemed to have gotten reset to something else when imported my 3.X project to 4.

I also used the instructions found here:

http://developer.apple.com/library/mac/#documentation/ToolsLanguages/Conceptual/Xcode4UserGuide/DistApps/DistApps.html#//apple_ref/doc/uid/TP40010215-CH11-DontLinkElementID_69

But I still can't get the actual archives to show up in Organizer (even though the files exist)

How to insert default values in SQL table?

You can write in this way

GO
ALTER TABLE Table_name  ADD
column_name decimal(18, 2) NOT NULL CONSTRAINT Constant_name DEFAULT 0
GO
ALTER TABLE Table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

Convert seconds to Hour:Minute:Second

This is a pretty way to do that:

function time_converter($sec_time, $format='h:m:s'){
      $hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
      $minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
      $sec = intval(($sec_time % 3600) % 60)  >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);

      $format = str_replace('h', $hour, $format);
      $format = str_replace('m', $minute, $format);
      $format = str_replace('s', $sec, $format);

      return $format;
    }

Installing mysql-python on Centos

mysql-python NOT support Python3, you may need:

sudo pip3 install mysqlclient

Also, check this post for more alternatives.

How to get UTC+0 date in Java 8?

tl;dr

Instant.now()

java.time

The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Instant instant = Instant.now();

The toString method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.

String output = instant.toString();  

2016-06-27T19:15:25.864Z

The Instant class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.

OffsetDateTime

But Instant has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant to OffsetDateTime. Specify an offset-from-UTC. In java.time that means a ZoneOffset object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

2016-06-27T19:15:25.864Z

Or skip the Instant class.

OffsetDateTime.now( ZoneOffset.UTC )

Now with an OffsetDateTime object in hand, you can use DateTimeFormatter to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter.

ZonedDateTime

When you want to display wall-clock time for some particular time zone, apply a ZoneId to get a ZonedDateTime.

In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00. So note how the time-of-day is four hours earlier in the output, 15 instead of 19 hours. Instant and the ZonedDateTime both represent the very same simultaneous moment, just viewed through two different lenses.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

2016-06-27T15:15:25.864-04:00[America/Montreal]

Converting

While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant ) and java.util.Date::toInstant.

java.util.Date utilDate = java.util.Date.from( instant );

And going the other direction.

Instant instant= utilDate.toInstant();

Similarly, look for new methods added to GregorianCalendar (subclass of Calendar) to convert to and from java.time.ZonedDateTime.

Table of types of date-time classes in modern java.time versus legacy.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

When to use DataContract and DataMember attributes?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts.

You can find the full article here.

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

An implementation of the fast Fourier transform (FFT) in C#

I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.

I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.

/**
 * Performs an in-place complex FFT.
 *
 * Released under the MIT License
 *
 * Copyright (c) 2010 Gerald T. Beauregard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
public class FFT2
{
    // Element for linked list in which we store the
    // input/output data. We use a linked list because
    // for sequential access it's faster than array index.
    class FFTElement
    {
        public double re = 0.0;     // Real component
        public double im = 0.0;     // Imaginary component
        public FFTElement next;     // Next element in linked list
        public uint revTgt;         // Target position post bit-reversal
    }

    private uint m_logN = 0;        // log2 of FFT size
    private uint m_N = 0;           // FFT size
    private FFTElement[] m_X;       // Vector of linked list elements

    /**
     *
     */
    public FFT2()
    {
    }

    /**
     * Initialize class to perform FFT of specified size.
     *
     * @param   logN    Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
     */
    public void init(
        uint logN )
    {
        m_logN = logN;
        m_N = (uint)(1 << (int)m_logN);

        // Allocate elements for linked list of complex numbers.
        m_X = new FFTElement[m_N];
        for (uint k = 0; k < m_N; k++)
            m_X[k] = new FFTElement();

        // Set up "next" pointers.
        for (uint k = 0; k < m_N-1; k++)
            m_X[k].next = m_X[k+1];

        // Specify target for bit reversal re-ordering.
        for (uint k = 0; k < m_N; k++ )
            m_X[k].revTgt = BitReverse(k,logN);
    }

    /**
     * Performs in-place complex FFT.
     *
     * @param   xRe     Real part of input/output
     * @param   xIm     Imaginary part of input/output
     * @param   inverse If true, do an inverse FFT
     */
    public void run(
        double[] xRe,
        double[] xIm,
        bool inverse = false )
    {
        uint numFlies = m_N >> 1;   // Number of butterflies per sub-FFT
        uint span = m_N >> 1;       // Width of the butterfly
        uint spacing = m_N;         // Distance between start of sub-FFTs
        uint wIndexStep = 1;        // Increment for twiddle table index

        // Copy data into linked complex number objects
        // If it's an IFFT, we divide by N while we're at it
        FFTElement x = m_X[0];
        uint k = 0;
        double scale = inverse ? 1.0/m_N : 1.0;
        while (x != null)
        {
            x.re = scale*xRe[k];
            x.im = scale*xIm[k];
            x = x.next;
            k++;
        }

        // For each stage of the FFT
        for (uint stage = 0; stage < m_logN; stage++)
        {
            // Compute a multiplier factor for the "twiddle factors".
            // The twiddle factors are complex unit vectors spaced at
            // regular angular intervals. The angle by which the twiddle
            // factor advances depends on the FFT stage. In many FFT
            // implementations the twiddle factors are cached, but because
            // array lookup is relatively slow in C#, it's just
            // as fast to compute them on the fly.
            double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
            if (inverse == false)
                wAngleInc *= -1;
            double wMulRe = Math.Cos(wAngleInc);
            double wMulIm = Math.Sin(wAngleInc);

            for (uint start = 0; start < m_N; start += spacing)
            {
                FFTElement xTop = m_X[start];
                FFTElement xBot = m_X[start+span];

                double wRe = 1.0;
                double wIm = 0.0;

                // For each butterfly in this stage
                for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
                {
                    // Get the top & bottom values
                    double xTopRe = xTop.re;
                    double xTopIm = xTop.im;
                    double xBotRe = xBot.re;
                    double xBotIm = xBot.im;

                    // Top branch of butterfly has addition
                    xTop.re = xTopRe + xBotRe;
                    xTop.im = xTopIm + xBotIm;

                    // Bottom branch of butterly has subtraction,
                    // followed by multiplication by twiddle factor
                    xBotRe = xTopRe - xBotRe;
                    xBotIm = xTopIm - xBotIm;
                    xBot.re = xBotRe*wRe - xBotIm*wIm;
                    xBot.im = xBotRe*wIm + xBotIm*wRe;

                    // Advance butterfly to next top & bottom positions
                    xTop = xTop.next;
                    xBot = xBot.next;

                    // Update the twiddle factor, via complex multiply
                    // by unit vector with the appropriate angle
                    // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
                    double tRe = wRe;
                    wRe = wRe*wMulRe - wIm*wMulIm;
                    wIm = tRe*wMulIm + wIm*wMulRe;
                }
            }

            numFlies >>= 1;     // Divide by 2 by right shift
            span >>= 1;
            spacing >>= 1;
            wIndexStep <<= 1;   // Multiply by 2 by left shift
        }

        // The algorithm leaves the result in a scrambled order.
        // Unscramble while copying values from the complex
        // linked list elements back to the input/output vectors.
        x = m_X[0];
        while (x != null)
        {
            uint target = x.revTgt;
            xRe[target] = x.re;
            xIm[target] = x.im;
            x = x.next;
        }
    }

    /**
     * Do bit reversal of specified number of places of an int
     * For example, 1101 bit-reversed is 1011
     *
     * @param   x       Number to be bit-reverse.
     * @param   numBits Number of bits in the number.
     */
    private uint BitReverse(
        uint x,
        uint numBits)
    {
        uint y = 0;
        for (uint i = 0; i < numBits; i++)
        {
            y <<= 1;
            y |= x & 0x0001;
            x >>= 1;
        }
        return y;
    }

}

Convert .pem to .crt and .key

If you asked this question because you're using mkcert then the trick is that the .pem file is the cert and the -key.pem file is the key.

(You don't need to convert, just run mkcert yourdomain.dev otherdomain.dev )

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

The answer to the question how to convert a .cer file into a .crt file (they are encoded differently!) is:

openssl pkcs7 -print_certs -in certificate.cer -out certificate.crt

How do I tell a Python script to use a particular version

put at the start of my programs its use full for work with python

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

This code will help full for the progress

Disable ScrollView Programmatically?

You can make a CustomScrollView, for which you can disable its interference with other views. Though this can be sometimes irritating for the end user. Use it with caution.

This is the code:

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewParent;

public class CustomScrollView extends android.widget.ScrollView {

    public CustomScrollView(Context context) {
        super(context);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        /* Prevent parent controls from stealing our events once we've gotten a touch down */
        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN)
        {
            ViewParent p = getParent();
            if (p != null)
                p.requestDisallowInterceptTouchEvent(true);
        }

        return false;
    }
}

How to use the CustomScrollView?

You can add CustomScrollView as a parent to the screen in which you want to add another Scrollview as a child view, and the whole screen is scrollable. I used this for a RelativeLayout.

<?xml version="1.0" encoding="utf-8"?>
<**package.**CustomScrollView 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/some_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:tools="http://schemas.android.com/tools">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    #**Inside this I had a TableLayout and TableRow. Inside the TableRow,**
    #**I had a TextView which I made scrollable from Java Code.**
    #**textView.setMovementMethod(new ScrollingMovementMethod());**
    </RelativeLayout>
</ankit.inventory.ankitarora.inventorymanagementsimple.CustomScrollView>

It worked for my case.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

How do I view executed queries within SQL Server Management Studio?

You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.

If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

CREATE PROCEDURE checkUser 
(
   brugernavn1 varchar(64),
   password varchar(64)
) 
BEGIN 
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 
END; 

@ points to a global var in mysql. The above syntax is correct.

Disable activity slide-in animation when launching new activity?

IMHO this answer here solve issue in the most elegant way..

Developer should create a style,

<style name="noAnimTheme" parent="android:Theme">
  <item name="android:windowAnimationStyle">@null</item>
</style>

then in manifest set it as theme for activity or whole application.

<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>

Voila! Nice and easy..

P.S. credits to original author please

Post form data using HttpWebRequest

Both the field name and the value should be url encoded. format of the post data and query string are the same

The .net way of doing is something like this

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();

This will take care of encoding the fields and the value names

Contains method for a slice

The go style:

func Contains(n int, match func(i int) bool) bool {
    for i := 0; i < n; i++ {
        if match(i) {
            return true
        }
    }
    return false
}


s := []string{"a", "b", "c", "o"}
// test if s contains "o"
ok := Contains(len(s), func(i int) bool {
    return s[i] == "o"
})

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

Format date and Subtract days using Moment.js

In angularjs moment="^1.3.0"

moment('15-01-1979', 'DD-MM-YYYY').subtract(1,'days').format(); //14-01-1979
or
moment('15-01-1979', 'DD-MM-YYYY').add(1,'days').format(); //16-01-1979
``



How to split a large text file into smaller files with equal number of lines?

you can also use awk

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

Convert or extract TTC font to TTF - how to?

You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

According to http://developer.android.com/guide/topics/ui/actionbar.html

The ActionBar APIs were first added in Android 3.0 (API level 11) but they are also available in the Support Library for compatibility with Android 2.1 (API level 7) and above.

In short, that auto-generated project you're seeing modularizes the process of adding the ActionBar to APIs 7-10.

Example of ActionBar on Froyo

See http://hmkcode.com/add-actionbar-to-android-2-3-x/ for a simplified explanation and tutorial on the topic.

Swift convert unix time to date and time

For managing dates in Swift 3 I ended up with this helper function:

extension Double {
    func getDateStringFromUTC() -> String {
        let date = Date(timeIntervalSince1970: self)

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateStyle = .medium

        return dateFormatter.string(from: date)
    }
}

This way it easy to use whenever you need it - in my case it was converting a string:

("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"

Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)

I found this article to be very helpful as well

How to analyze a JMeter summary report?

The JMeter docs say the following:

The summary report creates a table row for each differently named request in your test. This is similar to the Aggregate Report , except that it uses less memory. The thoughput is calculated from the point of view of the sampler target (e.g. the remote server in the case of HTTP samples). JMeter takes into account the total time over which the requests have been generated. If other samplers and timers are in the same thread, these will increase the total time, and therefore reduce the throughput value. So two identical samplers with different names will have half the throughput of two samplers with the same name. It is important to choose the sampler labels correctly to get the best results from the Report.

  • Label - The label of the sample. If "Include group name in label?" is selected, then the name of the thread group is added as a prefix. This allows identical labels from different thread groups to be collated separately if required.
  • # Samples - The number of samples with the same label
  • Average - The average elapsed time of a set of results
  • Min - The lowest elapsed time for the samples with the same label
  • Max - The longest elapsed time for the samples with the same label
  • Std. Dev. - the Standard Deviation of the sample elapsed time
  • Error % - Percent of requests with errors
  • Throughput - the Throughput is measured in requests per second/minute/hour. The time unit is chosen so that the displayed rate is at least 1.0. When the throughput is saved to a CSV file, it is expressed in requests/second, i.e. 30.0 requests/minute is saved as 0.5.
  • Kb/sec - The throughput measured in Kilobytes per second
  • Avg. Bytes - average size of the sample response in bytes. (in JMeter 2.2 it wrongly showed the value in kB)

Times are in milliseconds.

Determine the path of the executing BASH script

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Convert string to date then format the date

    String start_dt = "2011-01-01"; // Input String

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
    Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
    String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern

    System.out.println(formattedDate); //outputs: 01-01-2011

disable past dates on datepicker

this works for me,

$(function() { $('.datepicker').datepicker({ startDate: '-0m', autoclose: true }); });

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

If anyone is getting this error using Nginx, try adding the following to your server config:

server {
    listen 443 ssl;
    ...
}

The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl in the listen directive, you clear this up on the server side.

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

What are the best JVM settings for Eclipse?

You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.

It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.

-showsplash
org.eclipse.platform
-vm
 C:\jrmc-3.1.2-1.6.0\bin\javaw.exe 
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20

I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4

How to create .pfx file from certificate and private key?

I created .pfx file from .key and .pem files.

Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx

Count number of rows by group using dplyr

There's a special function n() in dplyr to count rows (potentially within groups):

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

But dplyr also offers a handy count function which does exactly the same with less typing:

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How to read until EOF from cin in C++

Using loops:

#include <iostream>
using namespace std;
...
// numbers
int n;
while (cin >> n)
{
   ...
}
// lines
string line;
while (getline(cin, line))
{
   ...
}
// characters
char c;
while (cin.get(c))
{
   ...
}

resource

preg_match in JavaScript?

var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);

match[1] and match[2] will contain the numbers you're looking for.

How to execute Python scripts in Windows?

you should make the default application to handle python files be python.exe.

right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).

then your python files will always be run using python.exe

Stateless vs Stateful

A stateful app is one that stores information about what has happened or changed since it started running. Any public info about what "mode" it is in, or how many records is has processed, or whatever, makes it stateful.

Stateless apps don't expose any of that information. They give the same response to the same request, function or method call, every time. HTTP is stateless in its raw form - if you do a GET to a particular URL, you get (theoretically) the same response every time. The exception of course is when we start adding statefulness on top, e.g. with ASP.NET web apps :) But if you think of a static website with only HTML files and images, you'll know what I mean.

sending email via php mail function goes to spam

Try changing your headers to this:

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n" .
"Reply-To: [email protected]" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

For a few reasons.

  • One of which is the need of a Reply-To and,

  • The use of apostrophes instead of double-quotes. Those two things in my experience with forms, is usually what triggers a message ending up in the Spam box.

You could also try changing the $from to:

$from = "[email protected]";


EDIT:

See these links I found on the subject https://stackoverflow.com/a/9988544/1415724 and https://stackoverflow.com/a/16717647/1415724 and https://stackoverflow.com/a/9899837/1415724

https://stackoverflow.com/a/5944155/1415724 and https://stackoverflow.com/a/6532320/1415724

  • Try using the SMTP server of your ISP.

    Using this apparently worked for many: X-MSMail-Priority: High

http://www.webhostingtalk.com/showthread.php?t=931932

"My host helped me to enable DomainKeys and SPF Records on my domain and now when I send a test message to my Hotmail address it doesn't end up in Junk. It was actually really easy to enable these settings in cPanel under Email Authentication. I can't believe I never saw that before. It only works with sending through SMTP using phpmailer by the way. Any other way it still is marked as spam."

PHPmailer sending mail to spam in hotmail. how to fix http://pastebin.com/QdQUrfax

how to display variable value in alert box?

document.getElementById('one').innerText;
alert(content);

It does not print the value; But, if done this way

document.getElementById('one').value;
alert(content);

change text of button and disable button in iOS

In Swift 3, you can simply change the title of a button by:

button.setTitle("Title", for: .normal)

and you disable the button by:

button.isEnabled = false

.normal is the same as UIControlState.normal because the type is inferred.

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

Regular expression for extracting tag attributes

PHP (PCRE) and Python

Simple attribute extraction (See it working):

((?:(?!\s|=).)*)\s*?=\s*?["']?((?:(?<=")(?:(?<=\\)"|[^"])*|(?<=')(?:(?<=\\)'|[^'])*)|(?:(?!"|')(?:(?!\/>|>|\s).)+))

Or with tag opening / closure verification, tag name retrieval and comment escaping. This expression foresees unquoted / quoted, single / double quotes, escaped quotes inside attributes, spaces around equals signs, different number of attributes, check only for attributes inside tags, and manage different quotes within an attribute value. (See it working):

(?:\<\!\-\-(?:(?!\-\-\>)\r\n?|\n|.)*?-\-\>)|(?:<(\S+)\s+(?=.*>)|(?<=[=\s])\G)(?:((?:(?!\s|=).)*)\s*?=\s*?[\"']?((?:(?<=\")(?:(?<=\\)\"|[^\"])*|(?<=')(?:(?<=\\)'|[^'])*)|(?:(?!\"|')(?:(?!\/>|>|\s).)+))[\"']?\s*)

(Works better with the "gisx" flags.)


Javascript

As Javascript regular expressions don't support look-behinds, it won't support most features of the previous expressions I propose. But in case it might fit someone's needs, you could try this version. (See it working).

(\S+)=[\'"]?((?:(?!\/>|>|"|\'|\s).)+)

Shorten string without cutting words in JavaScript

Everyone seems to forget that indexOf takes two arguments- the string to match, and the character index to start looking from. You can break the string at the first space after 10 characters.

function cutString(s, n){
    var cut= s.indexOf(' ', n);
    if(cut== -1) return s;
    return s.substring(0, cut)
}
var s= "this is a long string i cant display";
cutString(s, 10)

/*  returned value: (String)
this is a long
*/

Draw radius around a point in Google map

I've had this problem in the past, so I bookmarked this discussion.

To summarize it, you can:

  1. Take a look at this circle filter's source code and figure out how to incorporate it into your project.
  2. Draw a GPolygon with enough points to simulate a circle.
  3. Generate a KML file by modifying http://www.nearby.org.uk/google/circle.kml.php?radius=30miles&lat=40.173&long=-105.1024 and then importing it. In Google Maps, you can just paste the URI in the search box and it will display on the map. I'm not sure how you might do it using the API though.

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

Namespace for [DataContract]

[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .

System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.

Make JQuery UI Dialog automatically grow or shrink to fit its contents

If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.

How to download an entire directory and subdirectories using wget?

This works:

wget -m -np -c --no-check-certificate -R "index.html*" "https://the-eye.eu/public/AudioBooks/Edgar%20Allan%20Poe%20-%2"

EC2 instance has no public DNS

Here I will summarize the most common issues that occur:

When you create a custom VPC, if you want aws resources such as ec2 instances to acquire public IP addresses so that the internet can communicate with them, then you first must ensure that the ec2 instance is associated with a public subnet of the custom VPC. This means that subnet has an internet gateway associated with it. Also, you need to ensure that the security group of the VPC associated with ec2 instance has rules allowing inbound traffic to the desired ports, such as ssh, http and https. BUT here are some common oversights that still occur:

1) You must ensure that DNS hostnames is enabled for the VPC

2) You must ensure the public subnet linked to the EC2 instance has its 'auto-assignment of public ip' flag enabled

3) If the instance is already created, then you might need to terminate it and create a new instance for the public IP and public DNS fields to be populated.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

I have tried all the solutions and this one worked for me

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage

Proper way to set response status and JSON content in a REST API made with nodejs and express

The best way of sending an error response would be return res.status(400).send({ message: 'An error has occurred' }).

Then, in your frontend you can catch it using something like this:

        url: your_url,
        method: 'POST',
        headers: headers,
        data: JSON.stringify(body),
    })
        .then((res) => {
            console.log('success', res);
        })
        .catch((err) => {
            err.response && err.response.data && this.setState({ apiResponse: err.response.data })
        })

Just logging err won't work, as your sent message object resides in err.response.data.

Hope that helps!

How to make overlay control above all other controls?

<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
  <!-- YOUR XAML CODE -->
</Canvas>

How can I get the length of text entered in a textbox using jQuery?

If your textbox has an id attribute of "mytextbox", then you can get the length like this:

var myLength = $("#mytextbox").val().length;
  • $("#mytextbox") finds the textbox by its id.
  • .val() gets the value of the input element entered by the user, which is a string.
  • .length gets the number of characters in the string.

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

How to draw in JPanel? (Swing/graphics Java)

Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}

Git 'fatal: Unable to write new index file'

Closing Visual Studio Code (that in my case has an auto-uploader background job running on file-save) solved the issue for me.

Credit for the solution: my friend and colleague Arnel.

How to make a progress bar

You could recreate the progress bar using CSS3 animations to give it a better look.

JSFiddle Demo

HTML

<div class="outer_div">
    <div class="inner_div">
        <div id="percent_count">

    </div>
</div>

CSS/CSS3

.outer_div {
    width: 250px;
    height: 25px;
    background-color: #CCC;
}

.inner_div {
    width: 5px;
    height: 21px;
    position: relative; top: 2px; left: 5px;
    background-color: #81DB92;
    box-shadow: inset 0px 0px 20px #6CC47D;
    -webkit-animation-name: progressBar;
    -webkit-animation-duration: 3s;
    -webkit-animation-fill-mode: forwards;
}

#percent_count {
    font: normal 1em calibri;
    position: relative;
    left: 10px;
}

@-webkit-keyframes progressBar {
    from {
        width: 5px;
    }
    to {
        width: 200px;
    }
}

Correct way to focus an element in Selenium WebDriver using Java

The following code -

element.sendKeys("");

tries to find an input tag box to enter some information, while

new Actions(driver).moveToElement(element).perform();

is more appropriate as it will work for image elements, link elements, dropdown boxes etc.

Therefore using moveToElement() method makes more sense to focus on any generic WebElement on the web page.

For an input box you will have to click() on the element to focus.

new Actions(driver).moveToElement(element).click().perform();

while for links and images the mouse will be over that particular element,you can decide to click() on it depending on what you want to do.

If the click() on an input tag does not work -

Since you want this function to be generic, you first check if the webElement is an input tag or not by -

if("input".equals(element.getTagName()){
   element.sendKeys("");
} 
else{
   new Actions(driver).moveToElement(element).perform();

}

You can make similar changes based on your preferences.

List of Stored Procedures/Functions Mysql Command Line

A variation on Praveenkumar_V's post:

SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'PROCEDURE';
SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'FUNCTION';

..and this because I needed to save time after some housekeeping:

SELECT CONCAT(
     "GRANT EXECUTE ON PROCEDURE `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'PROCEDURE';

SELECT CONCAT(
     "GRANT EXECUTE ON FUNCTION `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'FUNCTION';

"unary operator expected" error in Bash if condition

If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]], instead of the Posix-compatible single bracket version [ ... ]. Inside a [[ ... ]] compound, word-splitting and pathname expansion are not applied to words, so you can rely on

if [[ $aug1 == "and" ]];

to compare the value of $aug1 with the string and.

If you use [ ... ], you always need to remember to double quote variables like this:

if [ "$aug1" = "and" ];

If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only

if [ = "and" ]; 

which is not a valid syntax. (It would also fail with a different error message if $aug1 included white space or shell metacharacters.)

The modern [[ operator has lots of other nice features, including regular expression matching.

Command line tool to dump Windows DLL version?

This function returns the ntfs Windows file details for any file using Cygwin bash (actual r-click-properties-info) to the term

Pass the files path to finfo(), can be unix path, dos path, relative or absolute. The file is converted into an absolute nix path, then checked to see if it is in-fact a regular/existing file. Then converted into an absolute windows path and sent to "wmic". Then magic, you have windows file details right in the terminal. Uses: cygwin, cygpath, sed, and awk. Needs Windows WMI "wmic.exe" to be operational. The output is corrected for easy...

$ finfo notepad.exe
$ finfo "C:\windows\system32\notepad.exe" 
$ finfo /cygdrive/c/Windows/System32/notepad.exe 
$ finfo "/cygdrive/c/Program Files/notepad.exe"
$ finfo ../notepad.exe

finfo() {
    [[ -e "$(cygpath -wa "$@")" ]] || { echo "bad-file"; return 1; }
    echo "$(wmic datafile where name=\""$(echo "$(cygpath -wa "$@")" | sed 's/\\/\\\\/g')"\" get /value)" |\
    sed 's/\r//g;s/^M$//;/^$/d' | awk -F"=" '{print $1"=""\033[1m"$2"\033[0m" }'
}

Excel formula to get cell color

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let's say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index

How to remove files and directories quickly via terminal (bash shell)

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir.

The other two options you should know are -i and -f. -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you're absolutely sure you're deleting the right thing. You can specify these with -r or not; it's an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri, and rm -r -f is rm -rf.

Also note that what you're learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm's syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

How to use Bootstrap in an Angular project?

Procedure with Angular 6+ & Bootstrap 4+ :

  1. Open a shell on the folder of your project
  2. Install bootstrap with the command : npm install --save [email protected]
  3. Bootstrap need the dependency jquery, so if you don't have it, you can install it with the command : npm install --save jquery 1.9.1
  4. You may need to fix vulnerability with the command : npm audit fix
  5. In your main style.scss file, add the following line : @import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

OR

Add this line to your main index.html file : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Check if at least two out of three booleans are true

My first thought was

return (a||b)&&(b||c)

but for ease of reading I liked the proposed a+b+c>=2 solution that you guys suggested better

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

How to center canvas in html5

The above answers only work if your canvas is the same width as the container.

This works regardless:

_x000D_
_x000D_
#container {_x000D_
  width: 100px;_x000D_
  height:100px;_x000D_
  border: 1px solid red;_x000D_
  _x000D_
  _x000D_
  margin: 0px auto;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
#canvas {_x000D_
  border: 1px solid blue;_x000D_
  width: 50px;_x000D_
  height: 100px;_x000D_
  _x000D_
}
_x000D_
<div id="container">_x000D_
  <canvas id="canvas" width="100" height="100"></canvas>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is Persistence Context?

"A set of persist-able (entity) instances managed by an entity manager instance at a given time" is called persistence context.

JPA @Entity annotation indicates a persist-able entity.

Refer JPA Definition here

JSON Naming Convention (snake_case, camelCase or PascalCase)

Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.

This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.

In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like

var devTask = {
        task_id: 120,
        store_id: 2118,
        task_name: 'generalLedger'
    };

or

generalLedgerTask = new GeneralLedgerTask( devTask );

And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.

I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.

Adding a leading zero to some values in column in MySQL

Change the field back to numeric and use ZEROFILL to keep the zeros

or

use LPAD()

SELECT LPAD('1234567', 8, '0');

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

You can do this by using below code

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

text flowing out of div

If this helps. Add the following property with value to your selector:

white-space: pre-wrap;

Performance differences between ArrayList and LinkedList

Both remove() and insert() have a runtime efficiency of O(n) for both ArrayLists and LinkedLists. However the reason behind the linear processing time comes from two very different reasons:

In an ArrayList you get to the element in O(1), but actually removing or inserting something makes it O(n) because all the following elements need to be changed.

In a LinkedList it takes O(n) to actually get to the desired element, because we have to start at the very beginning until we reach the desired index. Removing or inserting is constant once we get there, because we only have to change 1 reference for remove() and 2 references for insert().

Which of the two is faster for inserting and removing depends on where it happens. If we are closer to the beginning the LinkedList will be faster, because we have to go through relatively few elements. If we are closer to the end an ArrayList will be faster, because we get there in constant time and only have to change the few remaining elements that follow it.

Bonus: While there is no way of making these two methods O(1) for an ArrayList, there actually is a way to do this in LinkedLists. Lets say we want to go through the entire List removing and inserting elements on our way. Usually you would start from the very beginning for each elements using the LinkedList, we could also "save" the current element we're working on with an Iterator. With the help of the Iterator we get a O(1) efficiency for remove() and insert() when working in a LinkedList. Making it the only performance benefit I'm aware of where a LinkedList is always better than an ArrayList.

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

"No such file or directory" but it exists

I got this error “No such file or directory” but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15\r where ever a new line was there. I just created a new file truncating unwanted stuff

sleep: invalid time interval ‘15\r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh 
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \r  \n   w   g   e   t       h   t   t   p   :   /

0000400   :   4   1   2   0   /  \r  \n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \\015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \n   w   g   e   t       h   t   t   p   :   /   /

0000400   /  \n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed 

call javascript function on hyperlink click

The simplest answer of all is...

_x000D_
_x000D_
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

Or to answer the question of calling a javascript function:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
    alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
_x000D_
_x000D_

How do I save a String to a text file using Java?

Use this, it is very readable:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Here the problem was the API link without the key param:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places&key=YOURKEY"></script>

That way works fine.

Docker is installed but Docker Compose is not ? why?

If you installed docker by adding their official repository to your repository list, like:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

Just do:

$ sudo apt-get install docker-compose

In case on RHEL based distro / Fedora:

$ sudo dnf install docker-compose

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

JavaScript - get the first day of the week from current date

var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));

This will work well.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

How to read one single line of csv data in Python?

The simple way to get any row in csv file

import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
    csvFileArray.append(row)
print(csvFileArray[0])

Comparing double values in C#

To compare floating point, double or float types, use the specific method of CSharp:

if (double1.CompareTo(double2) > 0)
{
    // double1 is greater than double2
}
if (double1.CompareTo(double2) < 0)
{
    // double1 is less than double2
}
if (double1.CompareTo(double2) == 0)
{
    // double1 equals double2
}

https://docs.microsoft.com/en-us/dotnet/api/system.double.compareto?view=netcore-3.1

Javascript loop through object array?

Iterations

Method 1: forEach method

messages.forEach(function(message) {
   console.log(message);
}

Method 2: for..of method

for(let message of messages){
   console.log(message);
}

Note: This method might not work with objects, such as:

let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }

Method 2: for..in method

for(let key in messages){
       console.log(messages[key]);
 }

How do I unbind "hover" in jQuery?

unbind() doesn't work with hardcoded inline events.

So, for example, if you want to unbind the mouseover event from <div id="some_div" onmouseover="do_something();">, I found that $('#some_div').attr('onmouseover','') is a quick and dirty way to achieve it.

Is it possible to Turn page programmatically in UIPageViewController?

I'm working on It since yesterday and I finally did It work. I couldn't use standard template totally, because I have three differents viewControllers as childviews:

1 - rootViewController;
2 - model;
3 - viewControllers
3.1 - VC1;
3.2 - VC2;
3.3 - VC3.
Note: all of VCs has Storyboard ID.

I needed a trigger button only in the first one VC, so I added one property for pageViewController and model:

#import <UIKit/UIKit.h>
#import "Model.h"

@interface VC1 : UIViewController

@property (nonatomic, strong) UIPageViewController *thePageViewController;
@property (nonatomic, strong) SeuTimePagesModel *theModel;

@end

I rewrote the model's init method to pass storyboard and pageViewController as parameters, so I could set those to my VC1:

- (id)initWithStoryboard:(UIStoryboard *)storyboard
   andPageViewController:(UIPageViewController *)controller
{
    if (self = [super init])
    {
        VC1 *vc1 = [storyboard instantiateViewControllerWithIdentifier:@"VC1"];
        vc1.pageViewController = controller;
        vc1.model = self;

        VC2 *vc2 = [storyboard instantiateViewControllerWithIdentifier:@"VC2"];
        VC3 *vc3 = [storyboard instantiateViewControllerWithIdentifier:@"VC3"];
        self.pageData = [[NSArray alloc] initWithObjects:vc1, vc2, vc3, nil];
    }

    return self;
}

Finally, I added an IBAction in my vc1 to trigger the pageViewController method setViewControllers:direction:animated:completion::

- (IBAction)go:(id)sender
{
    VC2 *vc2 = [_model.pages objectAtIndex:1];
    NSArray *viewControllers = @[vc2];
    [_pageViewController setViewControllers:viewControllers
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:YES
                                 completion:nil];
}

Note I don't need to find VCs indexes, my button takes me to my second VC, but Its not hard get all of indexes, and keep track of your childviews:

- (IBAction)selecionaSeuTime:(id)sender
{
    NSUInteger index = [_model.pages indexOfObject:self];
    index++;

    VC2 *vc2 = [_model.pages objectAtIndex:1];
    NSArray *viewControllers = @[vc2];
    [_pageViewController setViewControllers:viewControllers
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:YES
                                 completion:nil];
}

I hope It helps you!

SQL Server - Return value after INSERT

There are multiple ways to get the last inserted ID after insert command.

  1. @@IDENTITY : It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the value
  2. SCOPE_IDENTITY(): It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table.
  3. IDENT_CURRENT(‘TABLENAME’) : It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.

Now it seems more difficult to decide which one will be exact match for my requirement.

I mostly prefer SCOPE_IDENTITY().

If you use select SCOPE_IDENTITY() along with TableName in insert statement, you will get the exact result as per your expectation.

Source : CodoBee

Node.js Hostname/IP doesn't match certificate's altnames

For developers using the Fetch API in a Node.js app, this is how I got this to work using rejectUnauthorized.

Keep in mind that using rejectUnauthorized is dangerous as it opens you up to potential security risks, as it circumvents a problematic certificate.

const fetch = require("node-fetch");
const https = require('https');

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

async function getData() {
  const resp = await fetch(
    "https://myexampleapi.com/endpoint",
    {
      agent: httpsAgent,
    },
  )
  const data = await resp.json()
  return data
}

Any reason to prefer getClass() over instanceof when generating .equals()?

If you use instanceof, making your equals implementation final will preserve the symmetry contract of the method: x.equals(y) == y.equals(x). If final seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object class.

Using Google maps API v3 how do I get LatLng with a given address?

I don't think location.LatLng is working, however this works:

results[0].geometry.location.lat(), results[0].geometry.location.lng()

Found it while exploring Get Lat Lon source code.

Environment variables for java installation

In Windows inorder to set

Step 1 : Right Click on MyComputer and click on properties .

Step 2 : Click on Advanced tab

alt text

Step 3: Click on Environment Variables

alt text

Step 4: Create a new class path for JAVA_HOME

alt text

Step 5: Enter the Variable name as JAVA_HOME and the value to your jdk bin path ie c:\Programfiles\Java\jdk-1.6\bin and

NOTE Make sure u start with .; in the Value so that it doesn't corrupt the other environment variables which is already set.

alt text

Step 6 : Follow the Above step and edit the Path in System Variables add the following ;c:\Programfiles\Java\jdk-1.6\bin in the value column.

Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type

 java   

who will get a list of help doc

In order make sure whether compiler is setup Type in cmd

  javac

who will get a list related to javac

Hope this Helps !

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

How can I work with command line on synology?

You can use your favourite telnet (not recommended) or ssh (recommended) application to connect to your Synology box and use it as a terminal.

  1. Enable the command line interface (CLI) from the Network Services
  2. Define the protocol and the user and make sure the user has password set
  3. Access the CLI

If you need more detailed instruction read https://www.synology.com/en-global/knowledgebase/DSM/help/DSM/AdminCenter/system_terminal

Bundler: Command not found

On my Arch Linux install, gems were installed to the ~/.gem/ruby/2.6.0/bin directory if installed as user, or /root/.gem/ruby/2.6.0/bin if installed via sudo. Just append the appropriate one to your $PATH environment variable:

export PATH=$PATH:/home/your_username/.gem/ruby/2.6.0/bin

Testing if value is a function

I think the source of confusion is the distinction between a node's attribute and the corresponding property.

You're using:

$("a.button").parents("form").attr("onsubmit")

You're directly reading the onsubmit attribute's value (which must be a string). Instead, you should access the onsubmit property of the node:

$("a.button").parents("form").prop("onsubmit")

Here's a quick test:

<form id="form1" action="foo1.htm" onsubmit="return valid()"></form>
<script>
window.onload = function () {
    var form1 = document.getElementById("form1");

    function log(s) {
        document.write("<div>" + s + "</div>");
    }

    function info(v) {
        return "(" + typeof v + ") " + v;
    }

    log("form1 onsubmit property: " + info(form1.onsubmit));
    log("form1 onsubmit attribute: " + info(form1.getAttribute("onsubmit")));
};
</script> 

This yields:

form1 onsubmit property: (function) function onsubmit(event) { return valid(); }
form1 onsubmit attribute: (string) return valid()

Failed to run sdkmanager --list with Java 9

When having java 11 in the system, the solutions provided are not valid.

This -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee or--add-modules java.xml.bind do not work with Java 11 on Mac OS.

For that reason you have to downgrade java version to version 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

List Java versions installed

/usr/libexec/java_home -V

Java 11

export JAVA_HOME=$(/usr/libexec/java_home -v 11)

Java 1.8

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Then go to

cd ~/Library/Android/sdk/tools/bin

and

./sdkmanager --licenses

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:

"first_Name"

Values (string literals / constants) are enclosed in single quotes:

'xyz'

So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

Read the manual on identifiers here.

My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

Best way to check for null values in Java?

Your last proposal is the best.

if (foo != null && foo.bar()) {
    etc...
}

Because:

  1. It is easier to read.
  2. It is safe : foo.bar() will never be executed if foo == null.
  3. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
  4. It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

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

You need to get process id of program using tcp port 3000. To get process id

lsof -i tcp:3000 -t

And then using that process id, simply kill process using ubuntu kill command.

kill -9 pid

Or just run below mentioned combine command. It will first fetch pid and then kill that process.

kill -9 $(lsof -i tcp:3000 -t)

Javascript - sort array based on another array

Why not something like

//array1: array of elements to be sorted
//array2: array with the indexes

array1 = array2.map((object, i) => array1[object]);

The map function may not be available on all versions of Javascript

Adding an external directory to Tomcat classpath

You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there

export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR

The source was not found, but some or all event logs could not be searched

Inaccessible logs: Security

A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).

So your app will need admin privilege to create a source. But that's probably an overkill.

I wrote this powershell script to create the event source at will. Save it as *.ps1 and run it with any privilege and it will elevate itself.

# CHECK OR RUN AS ADMIN

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

# CHECK FOR EXISTENCE OR CREATE

$source = "My Service Event Source";
$logname = "Application";

if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
    Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
    Write-Host $source -f white -nonewline; Write-Host " already exists.";
}

# DONE

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Can you use @Autowired with static fields?

Create a bean which you can autowire which will initialize the static variable as a side effect.

Finding whether a point lies inside a rectangle or not

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

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

How to disable auto-play for local video in iframe

Try This Code for disable auto play video.

Its Working . Please Vote if your are done with this

<div class="embed-responsive embed-responsive-16by9">
    <video controls="true" class="embed-responsive-item">
      <source src="example.mp4" type="video/mp4" />
    </video>
</div>

SeekBar and media player in android

Given the answer hardartcore that worked for me with a small change and did not work before the change:

private Handler mHandler = new Handler();
MusicPlayer.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {
          if(player != null){
               int mCurrentPosition = player.getCurrentPosition();//clear ' /1000 '
               seekBar.setProgress(mCurrentPosition);
          }
          mHandler.postDelayed(this, 1000);
      }
});



seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
          if(player != null && fromUser){
              player.seekTo(progress); // clear ' * 1000  '
          }
     }
});

How to iterate through an ArrayList of Objects of ArrayList of Objects?

When using Java8 it would be more easier and a single liner only.

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));

Setting a div's height in HTML with CSS

I can think of 2 options

  1. Use javascript to resize the smaller column on page load.
  2. Fake the equal heights by setting the background-color for the column on the container <div/> instead (<div class="separator"/>) with repeat-y

Python: How to get stdout after running os.system?

I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:

import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False) 
print r

...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...

import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False) 
print r

...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !

Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.

Went a step further...I thought this was cool...When I instead do this in Expts.py:

import subprocess
r = subprocess.call("cmd.exe dir",shell=False) 
print r

...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.

If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.

Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

Sending credentials with cross-domain posts?

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
    url: 'http://bar.other',
    data: { whatever:'cool' },
    type: 'GET',
    beforeSend: function(xhr){
       xhr.withCredentials = true;
    }
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

Counting the occurrences / frequency of array elements

Using Lodash

_x000D_
_x000D_
const values = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequency = _.map(_.groupBy(values), val => ({ value: val[0], frequency: val.length }));
console.log(frequency);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to get current date & time in MySQL?

Yes, you can use the CURRENT_TIMESTAMP() command.

See here: Date and Time Functions

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I have faced it on 04/2020. These are the options that I tried and the last solution get me through.

Problem:

Requests module works fine when I use in Spyder IDE but when I try to execute the script in windows it fails with SSL error. It works fine for HTTP requests but for HTTPS requests i got SSL error.

  1. I tired with Veify=True, False , also with Certs. Same error.
  2. Removed Certifi - conda remove certifi - Did not work Updated
  3. openssl , certifi - Still same error ( Refer : https://github.com/ContinuumIO/anaconda-issues/issues/494) Added
  4. the path variables - Same error
  5. Created new environment in Anaconda - same error

Solution that fixed it:

Solution from: https://github.com/conda/conda/issues/8273

I have copied the following files from Anaconda3\Library\bin to \Anaconda3\DLL

libcrypto-1_1-x64.* libssl-1_1-x64.*

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

Count the number of Occurrences of a Word in a String

public int occurrencesOf(String word) {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replaceAll(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
}

How can I add a hint text to WPF textbox?

Do it in the code-behind by setting the text color initially to gray and adding event handlers for gaining and losing keyboard focus.

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);

Then the event handlers:

private void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if(sender is TextBox)
    {
        //If nothing has been entered yet.
        if(((TextBox)sender).Foreground == Brushes.Gray)
        {
            ((TextBox)sender).Text = "";
            ((TextBox)sender).Foreground = Brushes.Black;
        }
    }
}


private void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    //Make sure sender is the correct Control.
    if(sender is TextBox)
    {
        //If nothing was entered, reset default text.
        if(((TextBox)sender).Text.Trim().Equals(""))
        {
            ((TextBox)sender).Foreground = Brushes.Gray;
            ((TextBox)sender).Text = "Text";
        }
    }
}

HTTP response header content disposition for attachments

This has nothing to do with the MIME type, but the Content-Disposition header, which should be something like:

Content-Disposition: attachment; filename=genome.jpeg;

Make sure it is actually correctly passed to the client (not filtered by the server, proxy or something). Also you could try to change the order of writing headers and set them before getting output stream.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

This is my function for the clients timezone, it's lite weight and simple

  function getCurrentDateTimeMySql() {        
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
      var mySqlDT = localISOTime;
      return mySqlDT;
  }

Changing default startup directory for command prompt in Windows 7

Open regedit and browse to this path

HKEY_CURRENT_USER\Software\Microsoft\Command Processor

Create new string vale named Autorun. Set its value to cd /d C:\.

Run cmd again. Voila!

Runtime vs. Compile time

Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).

Javascript - Get Image height

Try with JQuery:

<script type="text/javascript">
function jquery_get_width_height()
{
    var imgWidth = $("#img").width();
    var imgHeight = $("#img").height();
    alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

or

<script type="text/javascript">
function javascript_get_width_height()
{
    var img = document.getElementById('img');
    alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

I had the same problem today. Try it!

sudo chown -R  [yourgroup]  /home/[youruser]/.composer/cache/repo/https---packagist.org/


sudo chown -R  [yourgroup]   /home/[youruser]/.composer/cache/files/

Is having an 'OR' in an INNER JOIN condition a bad idea?

I use following code for get different result from condition That worked for me.


Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)

How to Solve Max Connection Pool Error

May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use

 using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
         }

Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

Returning an empty array

A different way to return an empty array is to use a constant as all empty arrays of a given type are the same.

private static final File[] NO_FILES = {};
private static File[] bar(){
    return NO_FILES;
}

Convert a character digit to the corresponding integer in C

When I need to do something like this I prebake an array with the values I want.

const static int lookup[256] = { -1, ..., 0,1,2,3,4,5,6,7,8,9, .... };

Then the conversion is easy

int digit_to_int( unsigned char c ) { return lookup[ static_cast<int>(c) ]; }

This is basically the approach taken by many implementations of the ctype library. You can trivially adapt this to work with hex digits too.

Transparent CSS background color

To achieve it, you have to modify the background-color of the element.

Ways to create a (semi-) transparent color:

  • The CSS color name transparent creates a completely transparent color.

    Usage:

      .transparent{
        background-color: transparent;
      }
    
  • Using rgba or hsla color functions, that allow you to add the alpha channel (opacity) to the rgb and hsl functions. Their alpha values range from 0 - 1.

    Usage:

      .semi-transparent-yellow{
        background-color: rgba(255, 255, 0, 0.5);
      }
      .transparent{
        background-color:  hsla(0, 0%, 0%, 0);
      }
    
  • Besides the already mentioned solutions, you can also use the HEX format with alpha value (#RRGGBBAA or #RGBA notation).

    That's pretty new (contained by CSS Color Module Level 4), but already implemented in larger browsers (sorry, no IE).

    This differs from the other solutions, as this treats the alpha channel (opacity) as a hexadecimal value as well, making it range from 0 - 255 (FF).

    Usage:

      .semi-transparent-yellow{
        background-color: #FFFF0080;
      }
      .transparent{
        background-color: #0000;
      }
    

You can try them out as well:

  • transparent:

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: transparent;
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `transparent`
</div>
_x000D_
_x000D_
_x000D_

  • rgba():

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: rgba(0, 255, 0, 0.3);
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `rgba()`
</div>
_x000D_
_x000D_
_x000D_

  • #RRGGBBAA:

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: #FF000060
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `#RRGGBBAA`
</div>
_x000D_
_x000D_
_x000D_

Can a html button perform a POST request?

This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.

<form action="" method="post">
    <input type="submit" name="upvote" value="Upvote" />
</form>

Unexpected character encountered while parsing value

I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.

The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.

Is there a difference between x++ and ++x in java?

When considering what the computer actually does...

++x: load x from memory, increment, use, store back to memory.

x++: load x from memory, use, increment, store back to memory.

Consider: a = 0 x = f(a++) y = f(++a)

where function f(p) returns p + 1

x will be 1 (or 2)

y will be 2 (or 1)

And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

Generally, just use x = x + 1. It's way simpler.

Android: ScrollView force to bottom

What worked best for me is

scroll_view.post(new Runnable() {
     @Override
     public void run() {
         // This method works but animates the scrolling 
         // which looks weird on first load
         // scroll_view.fullScroll(View.FOCUS_DOWN);

         // This method works even better because there are no animations.
         scroll_view.scrollTo(0, scroll_view.getBottom());
     }
});

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

PHP decoding and encoding json with unicode characters

A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.

$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
    if(is_string($item)) {
        $item = htmlentities($item);
    }
});
$json = json_encode($array);

// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);