Programs & Examples On #Wcf http

"python" not recognized as a command

in PowerShell enter this:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

Close PowerShell and then start it again to make sure Python now runs. If it doesn’t, restart may be required.

enter image description here

Float a div in top right corner without overlapping sibling header

Another problem solved by the rubber duck:

The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/ enter image description here

Change your HTML code to have the div before the header:

<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>

And keep your CSS to the simple div { float: right; }.

How do I detect if a user is already logged in Firebase?

https://firebase.google.com/docs/auth/web/manage-users

You have to add an auth state change observer.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

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

Based on answers from the community, there appear to be several ways that might solve this:

  1. From the official FAQ and support forums and this answer, you may have have a firewall or proxy issue that is blocking RStudio from connecting to the internet:
  • Disable any firewalls
  • Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option and restart R (#1, #2, #3)
  • Flag R with --internet2
  • On CentOS it was suggested to try the following: install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')
  1. Several answers suggest using an alternate mirror (#1, #2, #3):
  • Preferences > General > Default working directory > Browse and switch your mirror from local/global (whichever is unchecked)
  1. On Windows you can start the application with http_proxy=http://host:port/:
  • "C:\Program Files\RStudio\bin\rstudio.exe" http_proxy=http://host:port/
  1. Shut down and restart. Needed after many of the above operations, and suggested standalone.

How can I hide/show a div when a button is clicked?

The following solution is:

  • briefest. Somewhat similar to here. It's also minimal: The table in the DIV is orthogonal to your question.
  • fastest: getElementById is called once at the outset. This may or may not suit your purposes.
  • It uses pure JavaScript (i.e. without JQuery).
  • It uses a button. Your taste may vary.
  • extensible: it's ready to add more DIVs, sharing the code.

_x000D_
_x000D_
mydiv = document.getElementById("showmehideme");_x000D_
_x000D_
function showhide(d) {_x000D_
    d.style.display = (d.style.display !== "none") ? "none" : "block";_x000D_
}
_x000D_
#mydiv { background-color: #ddd; }
_x000D_
<button id="button" onclick="showhide(mydiv)">Show/Hide</button>_x000D_
<div id="showmehideme">_x000D_
    This div will show and hide on button click._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

How do I set the time zone of MySQL?

First to figure out what the time_zone is you can query

SHOW VARIABLES LIKE '%time_zone%'; 

Your output should be something similar as follows

**Variable_name**     **Value**
system_time_zone      CDT
time_zone             SYSTEM

Then if you want to confirm that you are in say some time zone like CDT instead of something like EST you can check what time it thinks your machine is in by saying

SELECT NOW();

If this is not the time you want you need to change it... all you need to do is SET time_zone = timezone_name. Make sure it is one that is in Continent/City format.

If you are on a shared server because you have a hosting service please refer to these answers regarding changing the php.ini file or the .htaccess file.

How do I get the last character of a string?

Here is a method using String.charAt():

String str = "India";
System.out.println("last char = " + str.charAt(str.length() - 1));

The resulting output is last char = a.

CSS submit button weird rendering on iPad/iPhone

Add this code into the css file:

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

This will help.

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

android ellipsize multiline textview

This is late, but I found an Apache licensed class from Android, that's used in the stock mail app: https://android.googlesource.com/platform/packages/apps/UnifiedEmail/+/184ec73/src/com/android/mail/ui/EllipsizedMultilineTextView.java

/*
 * Copyright (C) 2013 Google Inc.
 * Licensed to The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.mail.ui;
import android.content.Context;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * A special MultiLine TextView that will apply ellipsize logic to only the last
 * line of text, such that the last line may be shorter than any previous lines.
 */
public class EllipsizedMultilineTextView extends TextView {
    public static final int ALL_AVAILABLE = -1;
    private int mMaxLines;
    public EllipsizedMultilineTextView(Context context) {
        this(context, null);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        mMaxLines = maxlines;
    }
    /**
     * Ellipsize just the last line of text in this view and set the text to the
     * new ellipsized value.
     * @param text Text to set and ellipsize
     * @param avail available width in pixels for the last line
     * @param paint Paint that has the proper properties set to measure the text
     *            for this view
     * @return the {@link CharSequence} that was set on the {@link TextView}
     */
    public CharSequence setText(final CharSequence text, int avail) {
        if (text == null || text.length() == 0) {
            return text;
        }
        setEllipsize(null);
        setText(text);
        if (avail == ALL_AVAILABLE) {
            return text;
        }
        Layout layout = getLayout();
        if (layout == null) {
            final int w = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
            layout = new StaticLayout(text, 0, text.length(), getPaint(), w, Alignment.ALIGN_NORMAL,
                    1.0f, 0f, false);
        }
        // find the last line of text and chop it according to available space
        final int lastLineStart = layout.getLineStart(mMaxLines - 1);
        final CharSequence remainder = TextUtils.ellipsize(text.subSequence(lastLineStart,
                text.length()), getPaint(), avail, TextUtils.TruncateAt.END);
        // assemble just the text portion, without spans
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(text.toString(), 0, lastLineStart);
        if (!TextUtils.isEmpty(remainder)) {
            builder.append(remainder.toString());
        }
        // Now copy the original spans into the assembled string, modified for any ellipsizing.
        //
        // Merely assembling the Spanned pieces together would result in duplicate CharacterStyle
        // spans in the assembled version if a CharacterStyle spanned across the lastLineStart
        // offset.
        if (text instanceof Spanned) {
            final Spanned s = (Spanned) text;
            final Object[] spans = s.getSpans(0, s.length(), Object.class);
            final int destLen = builder.length();
            for (int i = 0; i < spans.length; i++) {
                final Object span = spans[i];
                final int start = s.getSpanStart(span);
                final int end = s.getSpanEnd(span);
                final int flags = s.getSpanFlags(span);
                if (start <= destLen) {
                    builder.setSpan(span, start, Math.min(end, destLen), flags);
                }
            }
        }
        setText(builder);
        return builder;
    }
}

Opening a CHM file produces: "navigation to the webpage was canceled"

There are apparently different levels of authentication. Most articles I read tell you to set the MaxAllowedZone to '1' which means that local machine zone and intranet zone are allowed but '4' allows access for 'all' zones.

For more info, read this article: https://support.microsoft.com/en-us/kb/892675

This is how my registry looks (I wasn't sure it would work with the wild cards but it seems to work for me):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"UrlAllowList"="\\\\<network_path_root>;\\\\<network_path_root>\*;\\ies-inc.local;http://www.*;http://*;https://www.*;https://*;"

As an additional note, weirdly the "UrlAllowList" key was required to make this work on another PC but not my test one. It's probably not required at all but when I added it, it fixed the problem. The user may have not closed the original file or something like that. So just a consideration. I suggest try the least and test it, then add if needed. Once you confirm, you can deploy if needed. Good Luck!

Edit: P.S. Another method that worked was mapping the path to the network locally by using mklink /d (symbolic linking in Windows 7 or newer) but mapping a network drive letter (Z: for testing) did not work. Just food for thought and I did not have to 'Unblock' any files. Also the accepted 'Solution' did not resolve the issue for me.

Which characters are valid in CSS class names/selectors?

To my surprise most answers here are wrong. It turns out that:

Any character except NUL is allowed in CSS class names in CSS. (If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])

Mathias Bynens' answer links to explanation and demos showing how to use these names. Written down in CSS code, a class name may need escaping, but that doesn’t change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.

Most other (programming) languages don’t have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.

Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return) in a class name attribute, because they already separate classes from each other.

So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.

Removing index column in pandas when reading a csv

You can set one of the columns as an index in case it is an "id" for example. In this case the index column will be replaced by one of the columns you have chosen.

df.set_index('id', inplace=True)

SQL Server: Examples of PIVOTing String data

From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:

SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO

How to know if .keyup() is a character key (jQuery)

This helped for me:

$("#input").keyup(function(event) {
        //use keyup instead keypress because:
        //- keypress will not work on backspace and delete
        //- keypress is called before the character is added to the textfield (at least in google chrome) 
        var searchText = $.trim($("#input").val());

        var c= String.fromCharCode(event.keyCode);
        var isWordCharacter = c.match(/\w/);
        var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);

        // trigger only on word characters, backspace or delete and an entry size of at least 3 characters
        if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
        { ...

.Net: How do I find the .NET version?

My god, so much mess to find version of installed .net framework?

Windows > Search > Visual Studio Installer > for installed version of VS, tap on More > Modify > Individual Components and see it there:

enter image description here

Char array in a struct - incompatible assignment?

sara is the struct itself, not a pointer (i.e. the variable representing location on the stack where actual struct data is stored). Therefore, *sara is meaningless and won't compile.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Keep in mind that if you're doing a cross-domain Ajax call (by using JSONP) - you can't do it synchronously, the async flag will be ignored by jQuery.

$.ajax({
    url: "testserver.php",
    dataType: 'jsonp', // jsonp
    async: false //IGNORED!!
});

For JSONP-calls you could use:

  1. Ajax-call to your own domain - and do the cross-domain call server-side
  2. Change your code to work asynchronously
  3. Use a "function sequencer" library like Frame.js (this answer)
  4. Block the UI instead of blocking the execution (this answer) (my favourite way)

Python, Matplotlib, subplot: How to set the axis range?

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use the same y limits for all of them. It gets limits of y ax from first plot.

plt.setp(ax, ylim=ax[0,0].get_ylim())

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Extract a substring using PowerShell

The Substring method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.

PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >

link text

But this is easier...

 $s = 'Hello World is in here Hello World!'
 $p = 'Hello World'
 $s -match $p

And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":

dir -rec -filter *.txt | Select-String 'Hello World'

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

How to diff one file to an arbitrary version in Git?

To see what was changed in a file in the last commit:

git diff HEAD~1 path/to/file

You can change the number (~1) to the n-th commit which you want to diff with.

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

Android Studio Stuck at Gradle Download on create new project

Yes, There is.

  1. Create a new project and you should Shutdown The Android Studio Application.(Because it takes a long time for you).
  2. Goto C:\Users\{Logged in User}\.gradle folder
  3. There is a folder there that show you which version of gradle Android Studio requires (e.g. gradle-1.8-bin)
  4. Download this version from internet (e.g. gradle-1.8-bin.zip).
  5. Goto C:\Users\{Logged in User}\.gradle\wrapper\dists\gradle-1.8-bin
  6. There is a folder here that its name is like a GUID.
  7. You should just copy the zip file that you've already downloaded from internet into this folder.
  8. Execute Android Studio and create a new project.

How can I fix "Design editor is unavailable until a successful build" error?

None of the above worked for me. what worked for me is to go to File -> Invalidate Caches / Restart

Android Intent Cannot resolve constructor

Use

Intent myIntent = new Intent(v.getContext(), MyClass.class);

or

 Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);

to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.

Azure SQL Database "DTU percentage" metric

A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.

Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.

The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.

From down toward the bottom of this announcement:

For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.

As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.

How to remove a branch locally?

By your tags, I'm assuming your using Github. Why not create some branch protection rules for your master branch? That way even if you do try to push to master, it will reject it.

1) Go to the 'Settings' tab of your repo on Github.

2) Click on 'Branches' on the left side-menu.

3) Click 'Add rule'

4) Enter 'master' for a branch pattern.

5) Check off 'Require pull request reviews before merging'

I would also recommend doing the same for your dev branch.

PowerShell : retrieve JSON object by field value

$json = @"
{
"Stuffs": 
    [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },

        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}
"@

$x = $json | ConvertFrom-Json

$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts

Change div width live with jQuery

It is indeed possible to change a div elements' width in jQuery:

$("#div").css("width", "300px");

However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:

#div {
    width: 75%;
    /* You can also specify min/max widths */
    min-width: 300px;
    max-width: 960px;
}

This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

FirstOrDefault: Default value other than null

General case, not just for value types:

static class ExtensionsThatWillAppearOnEverything
{
    public static T IfDefaultGiveMe<T>(this T value, T alternate)
    {
        if (value.Equals(default(T))) return alternate;
        return value;
    }
}

var result = query.FirstOrDefault().IfDefaultGiveMe(otherDefaultValue);

Again, this can't really tell if there was anything in your sequence, or if the first value was the default.

If you care about this, you could do something like

static class ExtensionsThatWillAppearOnIEnumerables
{
    public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
    {
        foreach(T t in source)
            return t;
        return alternate;
    }
}

and use as

var result = query.FirstOr(otherDefaultValue);

although as Mr. Steak points out this could be done just as well by .DefaultIfEmpty(...).First().

How do I make a relative reference to another workbook in Excel?

easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")

however indirect() has performance drawbacks if lot of links in workbook

I miss construct like: ['../Data.ods']#Sheet1.A1 in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.

How do we count rows using older versions of Hibernate (~2009)?

You could try count(*)

Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();

Where Books is the name off the class - not the table in the database.

How to select the last record of a table in SQL?

I think this should do it.

declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;

jQuery find() method not working in AngularJS directive

Before the days of jQuery you would use:

   document.getElementById('findmebyid');

If this one line will save you an entire jQuery library, it might be worth while using it instead.

For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

http://learn.jquery.com/performance/optimize-selectors/

jsPerf http://jsperf.com/jquery-selector-benchmark/32

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

Converting JSONarray to ArrayList

Generic variant

public static <T> List<T> getList(JSONArray jsonArray) throws Exception {

    List<T> list = new ArrayList<>(jsonArray.length());

    for (int i = 0; i < jsonArray.length(); i++) {

        list.add((T)jsonArray.get(i));
    }

    return list;

}

//Usage

List<String> listKeyString = getList(dataJsonObject.getJSONArray("keyString"));

Refresh or force redraw the fragment

To solve the problem, I use this:

Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

How do I drop a foreign key in SQL Server?

This will work:

ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]

Fastest way to check if a string matches a regexp in ruby?

What about re === str (case compare)?

Since it evaluates to true or false and has no need for storing matches, returning match index and that stuff, I wonder if it would be an even faster way of matching than =~.


Ok, I tested this. =~ is still faster, even if you have multiple capture groups, however it is faster than the other options.

BTW, what good is freeze? I couldn't measure any performance boost from it.

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

How to add DOM element script to head section?

you could do:

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "script_source_here";
(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(scriptTag);

Are there any Open Source alternatives to Crystal Reports?

You can use jasper report.

iReport is a very effective tool to develop jasper reports.

It supports almost all the facilities provided by crystal report like formatting, grouping, creation of charts etc.

Refer the link for tutorial:

http://www.opentaps.org/docs/index.php/Tutorial_iReports

sort files by date in PHP

This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime

$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do

usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));

If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort instead.

With the resulting array, you would then iterate over the files like this:

foreach($files as $file){
    printf('<tr><td><input type="checkbox" name="box[]"></td>
            <td><a href="%1$s" target="_blank">%1$s</a></td>
            <td>%2$s</td></tr>', 
            $file, // or basename($file) for just the filename w\out path
            date('F d Y, H:i:s', filemtime($file)));
}

Note that because you already called filemtime when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.

What does "publicPath" in Webpack do?

When executed in the browser, webpack needs to know where you'll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively.

For example: If you configure your http server to host the generated bundle under /assets/ you should write: publicPath: "/assets/"

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Can Twitter Bootstrap alerts fade in as well as out?

None of the current answers worked for me. I'm using Bootstrap 3.

I liked what Rob Vermeer was doing and started from his response.

For a fade in and then fade out effect, I just used wrote the following function and used jQuery:

Html on my page to add the alert(s) to:

        <div class="alert-messages text-center">
        </div>

Javascript function to show and dismiss the alert.

function showAndDismissAlert(type, message) {
    var htmlAlert = '<div class="alert alert-' + type + '">' + message + '</div>';

    // Prepend so that alert is on top, could also append if we want new alerts to show below instead of on top.
    $(".alert-messages").prepend(htmlAlert);

    // Since we are prepending, take the first alert and tell it to fade in and then fade out.
    // Note: if we were appending, then should use last() instead of first()
    $(".alert-messages .alert").first().hide().fadeIn(200).delay(2000).fadeOut(1000, function () { $(this).remove(); });
}

Then, to show and dismiss the alert, just call the function like this:

    showAndDismissAlert('success', 'Saved Successfully!');
    showAndDismissAlert('danger', 'Error Encountered');
    showAndDismissAlert('info', 'Message Received');

As a side note, I styled the div.alert-messages fixed on top:

    <style>
    div.alert-messages {
        position: fixed;
        top: 50px;
        left: 25%;
        right: 25%;
        z-index: 7000;
    }
    </style>

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.

Run function from the command line

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

Wait until flag=true

Javascript is single threaded, hence the page blocking behaviour. You can use the deferred/promise approach suggested by others, but the most basic way would be to use window.setTimeout. E.g.

function checkFlag() {
    if(flag == false) {
       window.setTimeout(checkFlag, 100); /* this checks the flag every 100 milliseconds*/
    } else {
      /* do something*/
    }
}
checkFlag();

Here is a good tutorial with further explanation: Tutorial

EDIT

As others pointed out, the best way would be to re-structure your code to use callbacks. However, this answer should give you an idea how you can 'simulate' an asynchronous behaviour with window.setTimeout.

PyLint "Unable to import" error - how to set PYTHONPATH?

I had the same problem and since i could not find a answer I hope this can help anyone with a similar problem.

I use flymake with epylint. Basically what i did was add a dired-mode-hook that check if the dired directory is a python package directory. If it is I add it to the PYTHONPATH. In my case I consider a directory to be a python package if it contains a file named "setup.py".

;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;

(defun python-expand-path ()
  "Append a directory to the PYTHONPATH."
  (interactive
   (let ((string (read-directory-name 
          "Python package directory: " 
          nil 
          'my-history)))
     (setenv "PYTHONPATH" (concat (expand-file-name string)
                  (getenv ":PYTHONPATH"))))))

(defun pythonpath-dired-mode-hook ()
  (let ((setup_py (concat default-directory "setup.py"))
    (directory (expand-file-name default-directory)))
    ;;   (if (file-exists-p setup_py)
    (if (is-python-package-directory directory)
    (let ((pythonpath (concat (getenv "PYTHONPATH") ":" 
                  (expand-file-name directory))))
      (setenv "PYTHONPATH" pythonpath)
      (message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))

(defun is-python-package-directory (directory)
  (let ((setup_py (concat directory "setup.py")))
    (file-exists-p setup_py)))

(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)

Hope this helps.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

follow http://support.microsoft.com/kb/896456

To start a 32-bit command prompt, follow these steps:

* Click Start, click Run, type %windir%\SysWoW64\cmd.exe, and then click OK.

Then type

cscript vbscriptfile.vbs

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

Why is Thread.Sleep so harmful

I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():

In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.

Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

Multiple radio button groups in one form

Set equal name attributes to create a group;

_x000D_
_x000D_
<form>_x000D_
  <fieldset id="group1">_x000D_
    <input type="radio" value="value1" name="group1">_x000D_
    <input type="radio" value="value2" name="group1">_x000D_
  </fieldset>_x000D_
_x000D_
  <fieldset id="group2">_x000D_
    <input type="radio" value="value1" name="group2">_x000D_
    <input type="radio" value="value2" name="group2">_x000D_
    <input type="radio" value="value3" name="group2">_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to increment variable under DOS?

A little bit late for the party, but it's an interessting question.

You can write your own inc.bat for incrementing a number.
It can increment numbers from 0 to 9998.

@echo off
if "%1"==":inc" goto :increment

call %0 :inc %counter0%
set counter0=%_cnt%
if %_overflow%==0 goto :exit 

call %0 :inc %counter1%
set counter1=%_cnt%
if %_overflow%==0 goto :exit 

call %0 :inc %counter2%
set counter2=%_cnt%
if %_overflow%==0 goto :exit 

call %0 :inc %counter3%
set counter3=%_cnt%
goto :exit

:increment
set _overflow=0
set _cnt=%2

if "%_cnt%"=="" set _cnt=0

if %_cnt%==9 goto :overflow
if %_cnt%==8 set _cnt=9
if %_cnt%==7 set _cnt=8
if %_cnt%==6 set _cnt=7
if %_cnt%==5 set _cnt=6
if %_cnt%==4 set _cnt=5
if %_cnt%==3 set _cnt=4
if %_cnt%==2 set _cnt=3
if %_cnt%==1 set _cnt=2
if %_cnt%==0 set _cnt=1
goto :exit

:overflow
set _cnt=0
set _overflow=1
goto :exit

:exit
set count=%counter3%%counter2%%counter1%%counter0%

A sample for using it is here

@echo off
set counter0=0
set counter1=
set counter2=
set counter3=

:loop
call inc.bat
echo %count%
if not %count%==250 goto :loop

How to remove multiple indexes from a list at the same time?

Old question, but I have an answer.

First, peruse the elements of the list like so:

for x in range(len(yourlist)):
    print '%s: %s' % (x, yourlist[x])

Then, call this function with a list of the indexes of elements you want to pop. It's robust enough that the order of the list doesn't matter.

def multipop(yourlist, itemstopop):
    result = []
    itemstopop.sort()
    itemstopop = itemstopop[::-1]
    for x in itemstopop:
        result.append(yourlist.pop(x))
    return result

As a bonus, result should only contain elements you wanted to remove.

In [73]: mylist = ['a','b','c','d','charles']

In [76]: for x in range(len(mylist)):

      mylist[x])

....:

0: a

1: b

2: c

3: d

4: charles

...

In [77]: multipop(mylist, [0, 2, 4])

Out[77]: ['charles', 'c', 'a']

...

In [78]: mylist

Out[78]: ['b', 'd']

Could someone explain this for me - for (int i = 0; i < 8; i++)

The generic view of a loop is

for (initialization; condition; increment-decrement){}

The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

Standard SQL provides the MERGE statement for this task. Not all DBMS support the MERGE statement.

Maven command to determine which settings.xml file Maven is using

If you are debugging and wasting time like me, this will give exact details including passwords. :P

mvn help:effective-settings -DshowPasswords=true

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

Swift Set to Array

The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:

for item in myItemSet {
   ...
}

Or, to use the "sorted" method:

let itemsArray = myItemSet.sorted()

It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.

If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:

let itemsArray = myItemSet.map { $0 }

Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:

var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
 itemsArray = typedSet.map { $0 }
}

Java Class.cast() vs. cast operator

First, you are strongly discouraged to do almost any cast, so you should limit it as much as possible! You lose the benefits of Java's compile-time strongly-typed features.

In any case, Class.cast() should be used mainly when you retrieve the Class token via reflection. It's more idiomatic to write

MyObject myObject = (MyObject) object

rather than

MyObject myObject = MyObject.class.cast(object)

EDIT: Errors at compile time

Over all, Java performs cast checks at run time only. However, the compiler can issue an error if it can prove that such casts can never succeed (e.g. cast a class to another class that's not a supertype and cast a final class type to class/interface that's not in its type hierarchy). Here since Foo and Bar are classes that aren't in each other hierarchy, the cast can never succeed.

How to use a table type in a SELECT FROM statement?

You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

-- dummy ITEM table as we don't know what the real ones looks like
create table item(
    item_num number,
    currency varchar2(9)
)
/   

insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');

create package so_5165580 as
    type exch_row is record(
        exch_rt_eur number,
        exch_rt_usd number);
    type exch_tbl is table of exch_row index by varchar2(9);
    exch_rt exch_tbl;
    procedure show_items;
end so_5165580;
/

create package body so_5165580 as
    procedure populate_rates is
        rate exch_row;
    begin
        rate.exch_rt_eur := 0.614394;
        rate.exch_rt_usd := 0.8494;
        exch_rt('GBP') := rate;
        rate.exch_rt_eur := 0.9817;
        rate.exch_rt_usd := 1.3572;
        exch_rt('AUD') := rate;
    end;

    procedure show_items is
        cursor c0 is
            select i.*
            from item i;
    begin
        for r0 in c0 loop
            if exch_rt.exists(r0.currency) then
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                    || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
            else
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' ** no rates defined **');
            end if;
        end loop;
    end;
begin
    populate_rates;
end so_5165580;
/

So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

begin
    so_5165580.show_items;
end;
/

Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **

Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

insert into detail_items
with rt as (select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key)
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1   GBP          19.99             32.53611          23.53426
2   AUD          25                25.46041          18.41621

If you want the currency stuff to be more re-usable you could create a view:

create view rt as
select c.currency_cd as currency_cd,
    e.exch_rt as exch_rt_eur,
    (e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
    currency c,
    (select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;

And then insert using values from that:

insert into detail_items
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

If you are in a country such as Argentina, you should call your bank and verify that your card is authorized for international purchases. Certain credit cards in that country (such as pre-paid credit cards) are ONLY authorized for domestic purchases and purchases in bordering countries. They DO work online, but the purchase must be from a bordering country. What this means is that you may get this message because your card is valid but denied. I know, because this has happened to me today. Hopefully this helps someone else understand what their system is telling them.

Connecting to Postgresql in a docker container from outside

To connect from the localhost you need to add '--net host':

docker run --name some-postgres --net host -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

You can access the server directly without using exec from your localhost, by using:

psql -h localhost -p 5432 -U postgres

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

Check the items in forEach

    <c:forEach items="${pools}" var="pool"> 

        ${pool.name}

    </c:forEach>

Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Difference between 'cls' and 'self' in Python classes?

cls implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member and non-static members in java if you are from java background.

Fastest way to extract frames using ffmpeg?

Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:

time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp

1m36.029s

This takes long because ffmpeg parses the entire video file to get the desired frames.

time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4   -frames:v 1 period_down_$i.bmp ; done

0m4.689s

This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek is the default , and make sure you add -ss before the input video -i option.

Note that it's better to use -filter:v -fps=fps=... instead of -r as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.

How to add new item to hash

hash.store(key, value) - Stores a key-value pair in hash.

Example:

hash   #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash   #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}

Documentation

Shell - How to find directory of some command?

PATH is an environment variable, and can be displayed with the echo command:

echo $PATH

It's a list of paths separated by the colon character ':'

The which command tells you which file gets executed when you run a command:

which lshw

sometimes what you get is a path to a symlink; if you want to trace that link to where the actual executable lives, you can use readlink and feed it the output of which:

readlink -f $(which lshw)

The -f parameter instructs readlink to keep following the symlink recursively.

Here's an example from my machine:

$ which firefox
/usr/bin/firefox

$ readlink -f $(which firefox)
/usr/lib/firefox-3.6.3/firefox.sh

org.hibernate.MappingException: Could not determine type for: java.util.Set

My guess is you are using a Set<Role> in the User class annotated with @OneToMany. Which means one User has many Roles. But on the same field you use the @Column annotation which makes no sense. One-to-many relationships are managed using a separate join table or a join column on the many side, which in this case would be the Role class. Using @JoinColumn instead of @Column would probably fix the issue, but it seems semantically wrong. I guess the relationship between role and user should be many-to-many.

What is the Angular equivalent to an AngularJS $watch?

In Angular 2, change detection is automatic... $scope.$watch() and $scope.$digest() R.I.P.

Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").

Here's my understanding of how change detection works:

  • Zone.js "monkey patches the world" -- it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use setTimeout() inside our components rather than something like $timeout... because setTimeout() is monkey patched.
  • Angular builds and maintains a tree of "change detectors". There is one such change detector (class) per component/directive. (You can get access to this object by injecting ChangeDetectorRef.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches() that Angular 1 would set up for {{}} template bindings.
    Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).
  • When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to -- the shared application model/state and/or the component's view state.
  • After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
    • Lifecycle hooks are called as part of change detection.
      If the component data you want to watch is a primitive input property (String, boolean, number), you can implement ngOnChanges() to be notified of changes.
      If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement ngDoCheck() (see this SO answer for more on this).
      You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's a plunker that violates that. Stateful pipes can also trip you up here.
  • For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.
  • The browser notices the DOM changes and updates the screen.

Other references to learn more:

How to convert an object to JSON correctly in Angular 2 with TypeScript

If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:

<p> {{ product | json }} </p>

I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).

Python syntax for "if a or b or c but not all of them"

The English sentence:

“if a or b or c but not all of them”

Translates to this logic:

(a or b or c) and not (a and b and c)

The word "but" usually implies a conjunction, in other words "and". Furthermore, "all of them" translates to a conjunction of conditions: this condition, and that condition, and other condition. The "not" inverts that entire conjunction.

I do not agree that the accepted answer. The author neglected to apply the most straightforward interpretation to the specification, and neglected to apply De Morgan's Law to simplify the expression to fewer operators:

 not a or not b or not c  ->  not (a and b and c)

while claiming that the answer is a "minimal form".

powershell mouse move does not prevent idle mode

The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:

param($minutes = 60)

$myshell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 60
  $myshell.sendkeys(".")
}

and an alternative from the comments, which moves the mouse a single pixel:

$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)

How to check if div element is empty

if ($("#cartContent").children().length == 0) 
{
     // no child
}

Is it ok to run docker from inside docker?

I answered a similar question before on how to run a Docker container inside Docker.

To run docker inside docker is definitely possible. The main thing is that you run the outer container with extra privileges (starting with --privileged=true) and then install docker in that container.

Check this blog post for more info: Docker-in-Docker.

One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.

However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post

So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.

Which Android phones out there do have a gyroscope?

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

*** Phones:

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

*** Tablets:

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

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

How to get temporary folder for current user

System.IO.Path.GetTempPath() is just a wrapper for a native call to GetTempPath(..) in Kernel32.

Have a look at http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx

Copied from that page:

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  • The path specified by the TMP environment variable.
  • The path specified by the TEMP environment variable.
  • The path specified by the USERPROFILE environment variable.
  • The Windows directory.

It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows.

So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.

Align button to the right

<div class="container-fluid">
  <div class="row">
    <h3 class="one">Text</h3>
    <button class="btn btn-secondary ml-auto">Button</button>
  </div>
</div>

.ml-auto is Bootstraph 4's non-flexbox way of aligning things.

Right HTTP status code to wrong input

According to the below scenario ,

Let's say that someone makes a request to your server with data that is in the correct format, but is simply not "good" data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using "password" as their password). then the status code could be either 400 or 422 ?

Until now, I would have returned a "400 Bad Request", which, according to the w3.org, means:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

This description doesn't quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it's probably your best bet.

Recently, however, Someone from my Dev team pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code "422 Unprocessable Entity" as defined in the HTTP extension for WebDAV. HTTP status code 422 states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

Why does .NET foreach loop throw NullRefException when collection is null?

Another extension method to work around this:

public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
    if(items == null) return;
    foreach (var item in items) action(item);
}

Consume in several ways:

(1) with a method that accepts T:

returnArray.ForEach(Console.WriteLine);

(2) with an expression:

returnArray.ForEach(i => UpdateStatus(string.Format("{0}% complete", i)));

(3) with a multiline anonymous method

int toCompare = 10;
returnArray.ForEach(i =>
{
    var thisInt = i;
    var next = i++;
    if(next > 10) Console.WriteLine("Match: {0}", i);
});

When should you NOT use a Rules Engine?

I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules DRY will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.

I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.

I prefer a simpler, more data driven approach wherever possible.

Format date and time in a Windows batch script

REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).

IF "%time:~0,1%" LSS "1" (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)

ECHO %DATETIME%

Origin is not allowed by Access-Control-Allow-Origin

We also have same problem with phonegap application tested in chrome. One windows machine we use below batch file everyday before Opening Chrome. Remember before running this you need to clean all instance of chrome from task manager or you can select chrome to not to run in background.

BATCH: (use cmd)

cd D:\Program Files (x86)\Google\Chrome\Application\chrome.exe --disable-web-security

Changes in import statement python3

Relative import happens whenever you are importing a package relative to the current script/package.

Consider the following tree for example:

mypkg
+-- base.py
+-- derived.py

Now, your derived.py requires something from base.py. In Python 2, you could do it like this (in derived.py):

from base import BaseThing

Python 3 no longer supports that since it's not explicit whether you want the 'relative' or 'absolute' base. In other words, if there was a Python package named base installed in the system, you'd get the wrong one.

Instead it requires you to use explicit imports which explicitly specify location of a module on a path-alike basis. Your derived.py would look like:

from .base import BaseThing

The leading . says 'import base from module directory'; in other words, .base maps to ./base.py.

Similarly, there is .. prefix which goes up the directory hierarchy like ../ (with ..mod mapping to ../mod.py), and then ... which goes two levels up (../../mod.py) and so on.

Please however note that the relative paths listed above were relative to directory where current module (derived.py) resides in, not the current working directory.


@BrenBarn has already explained the star import case. For completeness, I will have to say the same ;).

For example, you need to use a few math functions but you use them only in a single function. In Python 2 you were permitted to be semi-lazy:

def sin_degrees(x):
    from math import *
    return sin(degrees(x))

Note that it already triggers a warning in Python 2:

a.py:1: SyntaxWarning: import * only allowed at module level
  def sin_degrees(x):

In modern Python 2 code you should and in Python 3 you have to do either:

def sin_degrees(x):
    from math import sin, degrees
    return sin(degrees(x))

or:

from math import *

def sin_degrees(x):
    return sin(degrees(x))

A project with an Output Type of Class Library cannot be started directly

The project you downloaded is a class library. Which can't be started.

Add a new project which can be started (console app, win forms, what ever you want) and add a reference to the class library project to be able to "play with it".

And set this new project as "Startup project"

VSCode: How to Split Editor Vertically

In version 1.23.1, it is Ctrl+Shift+P and Split Editor This will divide the screens vertically and you can move through them using Ctrl+K+LeftArrow

Screenshot of the Split Editor

resize2fs: Bad magic number in super-block while trying to open

On Centos 7, in answer to the original question where resize2fs fails with "bad magic number" try using fsadm as follows:

fsadm resize /dev/the-device-name-returned-by-df

Then:

df 

... to confirm the size changes have worked.

Change jsp on button click

You have several options, I'll start from the easiest:

1- Change the input buttons to links, you can style them with css so they look like buttons:

<a href="CreateCourse.jsp">Creazione Nuovo Corso</a>

instead of

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />

2- Use javascript to change the action of the form depending on the button you click:

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" 
onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />

3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.

C# testing to see if a string is an integer?

For Wil P solution (see above) you can also use LINQ.

var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

When should you use 'friend' in C++?

At work we use friends for testing code, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.

Suffice to say I wouldn't use the friend keyword as an essential component of your design.

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

How to add a RequiredFieldValidator to DropDownList control?

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select");

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

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

How to resolve the "ADB server didn't ACK" error?

Try the following:

  • Close Eclipse.
  • Restart your phone.
  • End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
  • Issue kill and start command in \platform-tools\
    • C:\sdk\platform-tools>adb kill-server
    • C:\sdk\platform-tools>adb start-server
  • If it says something like 'started successfully', you are good.

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

Why should I use a container div in HTML?

The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.

But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto.

Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.

How to get process ID of background process?

An even simpler way to kill all child process of a bash script:

pkill -P $$

The -P flag works the same way with pkill and pgrep - it gets child processes, only with pkill the child processes get killed and with pgrep child PIDs are printed to stdout.

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

This might happen when you attempt to grant all privileges on all tables to another user, because the mysql.users table is considered off-limits for a user other than root.

The following however, should work:

GRANT ALL PRIVILEGES ON `%`.* TO '[user]'@'[hostname]' IDENTIFIED BY '[password]' WITH GRANT OPTION;

Note that we use `%`.* instead of *.*

DateDiff to output hours and minutes

If you want 08:30 ( HH:MM) format then try this,

SELECT EmplID
    , EmplName
    , InTime
    , [TimeOut]
    , [DateVisited]
    ,  RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60),2) + ':' +
      RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
      as TotalHours from times Order By EmplID, DateVisited

How to check if user input is not an int value

Taken from a related post:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Create a group object and call methods like below example:

grp = df.groupby(['col1',  'col2',  'col3']) 

grp.max() 
grp.mean() 
grp.describe() 

How to deal with the URISyntaxException

A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).

I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:

String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
  .withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);

Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.

Flattening a shallow list in Python

There seems to be a confusion with operator.add! When you add two lists together, the correct term for that is concat, not add. operator.concat is what you need to use.

If you're thinking functional, it is as easy as this::

>>> list2d = ((1,2,3),(4,5,6), (7,), (8,9))
>>> reduce(operator.concat, list2d)
(1, 2, 3, 4, 5, 6, 7, 8, 9)

You see reduce respects the sequence type, so when you supply a tuple, you get back a tuple. let's try with a list::

>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.concat, list2d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Aha, you get back a list.

How about performance::

>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> %timeit list(itertools.chain.from_iterable(list2d))
1000000 loops, best of 3: 1.36 µs per loop

from_iterable is pretty fast! But it's no comparison to reduce with concat.

>>> list2d = ((1,2,3),(4,5,6), (7,), (8,9))
>>> %timeit reduce(operator.concat, list2d)
1000000 loops, best of 3: 492 ns per loop

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

nodeJS - How to create and read session with express

I need to point out here that you're incorrectly adding middleware to the application. The app.use calls should not be done within the app.get request handler, but outside of it. Simply call them directly after createServer, or take a look at the other examples in the docs.

The secret you pass to express.session should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.

If you want to store the email address in the session, simply do something along the lines of:

req.session.email = req.param('email');

With that out of the way...


If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.

What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server is by hijacking the request event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.

I believe you can make this work, though, with some trickery.

You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session:

// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));

Every session store has a get(sid, callback) method. The sid parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid. (But you can give it any name by specifying a key option in your express.session call.)

Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.

Code on the server would then look something like the following:

var io      = require('socket.io'),
    express = require('express');

var app    = express.createServer(),
    socket = io.listen(app),
    store  = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));

app.get('/', function(req, res) {
  var old = req.session.email;
  req.session.email = req.param('email');

  res.header('Content-Type', 'text/plain');
  res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});

socket.on('connection', function(client) {
  // We declare that the first message contains the SID.
  // This is where we handle the first message.
  client.once('message', function(sid) {
    store.get(sid, function(err, session) {
      if (err || !session) {
        // Do some error handling, bail.
        return;
      }

      // Any messages following are your chat messages.
      client.on('message', function(message) {
        if (message.email === session.email) {
          socket.broadcast(message.text);
        }
      });
    });
  });
});

app.listen(4000);

This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie header in (think WebSockets).

If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie header, which it can't. But for other stores, you could try calling the set(sid, data, callback) method and see what happens.

Creating a daemon in Linux

If your app is one of:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee" : "coffee",
  ".php": "php",
  ".pl" : "perl",
  ".js" : "node"
}

and you don't mind a NodeJS dependency then install NodeJS and then:

npm install -g pm2

pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above

pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores

pm2 list

To keep all apps running on reboot (and daemonise pm2):

pm2 startup

pm2 save

Now you can:

service pm2 stop|restart|start|status

(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

how to open a jar file in Eclipse

The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.

Suppress output of a function

invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1:  " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2:  " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3:  " ,bin3interval, fill = TRUE))

produces output without NULL at the end of the line or on the next line

Dataset:  17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width:  15.33333

Bin1:   17 32.33333
Bin2:   32.33333 47.66667
Bin3:   47.66667 63

JSON Array iteration in Android/Java

I think this code is short and clear:

int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    id = row.getInt("id");
    name = row.getString("name");
}

Is that what you were looking for?

How to POST raw whole JSON in the body of a Retrofit request?

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Your Interface

public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

Activity

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

MySQL LIKE IN()?

This would be correct:

SELECT * FROM table WHERE field regexp concat_ws("|",(
"111",
"222",
"333"
));

How do I discover memory usage of my application in Android?

In android studio 3.0 they have introduced android-profiler to help you to understand how your app uses CPU, memory, network, and battery resources.

https://developer.android.com/studio/profile/android-profiler

enter image description here

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

Conditional operator in Python?

From Python 2.5 onwards you can do:

value = b if a > 10 else c

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

How to detect pressing Enter on keyboard using jQuery?

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is defined as such in a declaration block:

DECLARE 
CURSOR cur IS 
  SELECT columns FROM table WHERE condition;
BEGIN
...

an implicit cursor is implented directly in a code block:

...
BEGIN
   SELECT columns INTO variables FROM table where condition;
END;
...

Self-reference for cell, column and row in worksheet functions

For a non-volatile solution, how about for 2007+:

for cell    =INDEX($A$1:$XFC$1048576,ROW(),COLUMN())
for column  =INDEX($A$1:$XFC$1048576,0,COLUMN())
for row     =INDEX($A$1:$XFC$1048576,ROW(),0)

I have weird bug on Excel 2010 where it won't accept the very last row or column for these formula (row 1048576 & column XFD), so you may need to reference these one short. Not sure if that's the same for any other versions so appreciate feedback and edit.

and for 2003 (INDEX became non-volatile in '97):

for cell    =INDEX($A$1:$IV$65536,ROW(),COLUMN())
for column  =INDEX($A$1:$IV$65536,0,COLUMN())
for row     =INDEX($A$1:$IV$65536,ROW(),0)

Converting JSON to XML in Java

Transforming with XSLT 3.0 is the only proper way to do it, as far as I can tell. It is guaranteed to produce valid XML, and a nice structure at that. https://www.w3.org/TR/xslt/#json

How do you import a large MS SQL .sql file?

I had similar problem. My file with sql script was over 150MB of size (with almost 900k of very simple INSERTs). I used solution advised by Takuro (as the answer in this question) but I still got error with message saying that there was not enough memory ("There is insufficient system memory in resource pool 'internal' to run this query").

What helped me was that I put GO command after every 50k INSERTs.

(It's not directly addressing the question (file size) but I believe it resolves problem that is indirectly connected with large size of sql script itself. In my case many insert commands)

CSS rounded corners in IE8

PIE.htc worked for me great (http://css3pie.com/), but with one issue:

You should write absolute path to PIE.htc. It hasn't worked for me when I used relative path.

Passing data between view controllers

I have seen a lot of people over complicating this using the didSelectRowAtPath method. I am using Core Data in my example.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    // This solution is for using Core Data
    YourCDEntityName * value = (YourCDEntityName *)[[self fetchedResultsController] objectAtIndexPath: indexPath];

    YourSecondViewController * details = [self.storyboard instantiateViewControllerWithIdentifier:@"nameOfYourSecondVC"]; // Make sure in storyboards you give your second VC an identifier

    // Make sure you declare your value in the second view controller
    details.selectedValue = value;

    // Now that you have said to pass value all you need to do is change views
    [self.navigationController pushViewController: details animated:YES];

}

Four lines of code inside the method and you are done.

Is there a concurrent List in Java's JDK?

If you never plan to delete elements from the list (since this requires changing the index of all elements after the deleted element), then you can use ConcurrentSkipListMap<Integer, T> in place of ArrayList<T>, e.g.

NavigableMap<Integer, T> map = new ConcurrentSkipListMap<>();

This will allow you to add items to the end of the "list" as follows, as long as there is only one writer thread (otherwise there is a race condition between map.size() and map.put()):

// Add item to end of the "list":
map.put(map.size(), item);

You can also obviously modify the value of any item in the "list" (i.e. the map) by simply calling map.put(index, item).

The average cost for putting items into the map or retrieving them by index is O(log(n)), and ConcurrentSkipListMap is lock-free, which makes it significantly better than say Vector (the old synchronized version of ArrayList).

You can iterate back and forth through the "list" by using the methods of the NavigableMap interface.

You could wrap all the above into a class that implements the List interface, as long as you understand the race condition caveats (or you could synchronize just the writer methods) -- and you would need to throw an unsupported operation exception for the remove methods. There's quite a bit of boilerplate needed to implement all the required methods, but here's a quick attempt at an implementation.

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentAddOnlyList<V> implements List<V> {
    private NavigableMap<Integer, V> map = new ConcurrentSkipListMap<>();

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.values().contains(o);
    }

    @Override
    public Iterator<V> iterator() {
        return map.values().iterator();
    }

    @Override
    public Object[] toArray() {
        return map.values().toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return map.values().toArray(a);
    }

    @Override
    public V get(int index) {
        return map.get(index);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return map.values().containsAll(c);
    }

    @Override
    public int indexOf(Object o) {
        for (Entry<Integer, V> ent : map.entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public int lastIndexOf(Object o) {
        for (Entry<Integer, V> ent : map.descendingMap().entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public ListIterator<V> listIterator(int index) {
        return new ListIterator<V>() {
            private int currIdx = 0;

            @Override
            public boolean hasNext() {
                return currIdx < map.size();
            }

            @Override
            public V next() {
                if (currIdx >= map.size()) {
                    throw new IllegalArgumentException(
                            "next() called at end of list");
                }
                return map.get(currIdx++);
            }

            @Override
            public boolean hasPrevious() {
                return currIdx > 0;
            }

            @Override
            public V previous() {
                if (currIdx <= 0) {
                    throw new IllegalArgumentException(
                            "previous() called at beginning of list");
                }
                return map.get(--currIdx);
            }

            @Override
            public int nextIndex() {
                return currIdx + 1;
            }

            @Override
            public int previousIndex() {
                return currIdx - 1;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

            @Override
            public void set(V e) {
                // Might change size of map if currIdx == map.size(),
                // so need to synchronize 
                synchronized (map) {
                    map.put(currIdx, e);
                }
            }

            @Override
            public void add(V e) {
                synchronized (map) {
                    // Insertion is not supported except at end of list
                    if (currIdx < map.size()) {
                        throw new UnsupportedOperationException();
                    }
                    map.put(currIdx++, e);
                }
            }
        };
    }

    @Override
    public ListIterator<V> listIterator() {
        return listIterator(0);
    }

    @Override
    public List<V> subList(int fromIndex, int toIndex) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean add(V e) {
        synchronized (map) {
            map.put(map.size(), e);
            return true;
        }
    }

    @Override
    public boolean addAll(Collection<? extends V> c) {
        synchronized (map) {
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public V set(int index, V element) {
        synchronized (map) {
            if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            return map.put(index, element);
        }
    }

    @Override
    public void clear() {
        synchronized (map) {
            map.clear();
        }
    }

    @Override
    public synchronized void add(int index, V element) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            add(element);
        }
    }

    @Override
    public synchronized boolean addAll(
            int index, Collection<? extends V> c) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(int index) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }
}

Don't forget that even with the writer thread synchronization as shown above, you need to be careful not to run into race conditions that might cause you to drop items, if for example you try to iterate through a list in a reader thread while a writer thread is adding to the end of the list.

You can even use ConcurrentSkipListMap as a double-ended list, as long as you don't need the key of each item to represent the actual position within the list (i.e. adding to the beginning of the list will assign items negative keys). (The same race condition caveat applies here, i.e. there should be only one writer thread.)

// Add item after last item in the "list":
map.put(map.isEmpty() ? 0 : map.lastKey() + 1, item);

// Add item before first item in the "list":
map.put(map.isEmpty() ? 0 : map.firstKey() - 1, item);

Python: Select subset from list based on index set

Assuming you only have the list of items and a list of true/required indices, this should be the fastest:

property_asel = [ property_a[index] for index in good_indices ]

This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:

good_indices = [ index for index, item in enumerate(good_objects) if item ]

This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.


For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:

list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True

Check if an apt-get package is installed and then install it if it's not on Linux

I had a similar requirement when running test locally instead of in docker. Basically I only wanted to install any .deb files found if they weren't already installed.

# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
  for file in *.deb; do
    # Only install if not already installed (non-zero exit code)
    dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
    if [ $? != 0 ]; then
        dpkg -i ${file}
    fi;
  done;
else
  err "No .deb files found in '$PWD'"
fi

I guess they only problem I can see is that it doesn't check the version number of the package so if .deb file is a newer version, then this wouldn't overwrite the currently installed package.

Play audio with Python

It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

Tri-state Check box in HTML?

As I needed something like this -without any plug-in- for script-generated checkboxes in a table... I ended up with this solution:

<!DOCTYPE html>
<html>
<body>

Toto <input type="checkbox" id="myCheck1" onclick="updateChkBx(this)" /><br />
Tutu <input type="checkbox" id="myCheck2" onclick="updateChkBx(this)" /><br />
Tata <input type="checkbox" id="myCheck3" onclick="updateChkBx(this)" /><br />
Tete <input type="checkbox" id="myCheck4" onclick="updateChkBx(this)" /><br />

<script>
var chkBoxState = [];

function updateChkBx(src) {
  var idx = Number(src.id.substring(7)); // 7 to bypass the "myCheck" part in each checkbox id
  if(typeof chkBoxState[idx] == "undefined") chkBoxState[idx] = false; // make sure we can use stored state at first call
  
  // the problem comes from a click on a checkbox both toggles checked attribute and turns inderminate attribute to false
  if(chkBoxState[idx]) {
    src.indeterminate = false;
    src.checked = false;
    chkBoxState[idx] = false;
  }
  else if (!src.checked) { // passing from checked to unchecked
    src.indeterminate = true;
    src.checked = true; // force considering we are in a checked state
    chkBoxState[idx] = true;
  }
}
// to know box state, just test indeterminate, and if not indeterminate, test checked
</script>

</body>
</html>

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

Is mathematics necessary for programming?

In my experience the Math requirement for a Computer Science degree exists simply to weed out those who will fail. If you cannot pass Calculus I and II you will most definitely not pass an advanced course on compiler construction, database or operating systems theory.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

I know that there's already an accepted answer, but I don't see how it works for the OP because I don't think FLAG_ACTIVITY_CLEAR_TOP is meaningful in his particular case. That flag is relevant only with activities in the same task. Based on his description, each activity is in its own task: A, B, and the browser.

Something that is maybe throwing him off is that A is singleTop, when it should be singleTask. If A is singleTop, and B starts A, then a new A will be created because A is not in B's task. From the documentation for singleTop:

"If an instance of the activity already exists at the top of the current task, the system routes the intent to that instance..."

Since B starts A, the current task is B's task, which is for a singleInstance and therefore cannot include A. Use singleTask to achieve the desired result there because then the system will find the task that has A and bring that task to the foreground.

Lastly, after B has started A, and the user presses back from A, the OP does not want to see either B or the browser. To achieve this, calling finish() in B is correct; again, FLAG_ACTIVITY_CLEAR_TOP won't remove the other activities in A's task because his other activities are all in different tasks. The piece that he was missing, though is that B should also use FLAG_ACTIVITY_NO_HISTORY when firing the intent for the browser. Note: if the browser is already running prior to even starting the OP's application, then of course you will see the browser when pressing back from A. So to really test this, be sure to back out of the browser before starting the application.

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

int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}

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

Launch Developer command line "As an Administrator". This account has full access to Security log

Converting Integers to Roman Numerals - Java

After seeing some of the answers here I had to post this. I think that my algorithm is far the most easiest to understand and the bit of performance lost is not important even on a relatively large scale. I'm also obeying the standardized coding conventions as opposed to some of the users here.

Average conversion time: 0.05ms (based on converting all numbers 1-3999 and dividing by 3999)

public static String getRomanNumeral(int arabicNumber) {

    if (arabicNumber > 0 && arabicNumber < 4000) {

        final LinkedHashMap<Integer, String> numberLimits = 
            new LinkedHashMap<>();

        numberLimits.put(1, "I");
        numberLimits.put(4, "IV");
        numberLimits.put(5, "V");
        numberLimits.put(9, "IX");
        numberLimits.put(10, "X");
        numberLimits.put(40, "XL");
        numberLimits.put(50, "L");
        numberLimits.put(90, "XC");
        numberLimits.put(100, "C");
        numberLimits.put(400, "CD");
        numberLimits.put(500, "D");
        numberLimits.put(900, "CM");
        numberLimits.put(1000, "M");

        String romanNumeral = "";

        while (arabicNumber > 0) {
            int highestFound = 0;
            for (Map.Entry<Integer, String> current : numberLimits.entrySet()){
                if (current.getKey() <= arabicNumber) {
                    highestFound = current.getKey();
                }
            }
            romanNumeral += numberLimits.get(highestFound);
            arabicNumber -= highestFound;
        }

        return romanNumeral;

    } else {
        throw new UnsupportedOperationException(arabicNumber 
            + " is not a valid Roman numeral.");
    }
}

First you have to take into account that Roman numerals are only in the interval of <1-4000), but that can be solved by a simple if and a thrown exception. Then you can try to find the largest set roman numeral in a given integer and if found subtract it from the original number and add it to the result. Repeat with the newly acquired number until you hit zero.

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

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

Just use dictionary comprehension to copy the relevant items into a new dict

>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = { k : v for k,v in d.iteritems() if v}
>>> d
{'a': [1], 'b': [1, 2]}

For this in Python 3

>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = { k : v for k,v in d.items() if v}
>>> d
{'a': [1], 'b': [1, 2]}

What's the best way to get the current URL in Spring MVC?

in jsp file:

request.getAttribute("javax.servlet.forward.request_uri")

How to set the timezone in Django?

To get a set of all valid timezone names (ids) from the tz database, you could use pytz module in Python:

>>> import pytz # $ pip install pytz
>>> pytz.all_timezones_set
LazySet({'Africa/Abidjan',
         'Africa/Accra',
         'Africa/Addis_Ababa',
         'Africa/Algiers',
         'Africa/Asmara',
         'Africa/Asmera',
         ...
         'UTC',
         'Universal',
         'W-SU',
         'WET',
         'Zulu'})

Read a plain text file with php

Try something like this:

$filename = 'file.txt';

$data = file($filename);
foreach ($data as $line_num=>$line)
{
    echo 'Line # <b>'.$line_num.'</b>:'.$line.'<br/>';
}

Remove an item from a dictionary when its key is unknown

a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

Initializing IEnumerable<string> In C#

Ok, adding to the answers stated you might be also looking for

IEnumerable<string> m_oEnum = Enumerable.Empty<string>();

or

IEnumerable<string> m_oEnum = new string[]{};

How can I debug a Perl script?

Note that the Perldebugger can also be invoked from the scripts shebang line, which is how I mostly use the -x flag you refer to, to debug shell scripts.

#! /usr/bin/perl -d

Adding script tag to React/JSX

for multiple scripts, use this

var loadScript = function(src) {
  var tag = document.createElement('script');
  tag.async = false;
  tag.src = src;
  document.getElementsByTagName('body').appendChild(tag);
}
loadScript('//cdnjs.com/some/library.js')
loadScript('//cdnjs.com/some/other/library.js')

Press Enter to move to next control

Try to use:

SendKeys.Send("{TAB}")

How can I view live MySQL queries?

This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.

Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”

#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.

log = /var/log/mysql/mysql.log

Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:

sudo /etc/init.d/mysql restart

Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.

tail -f /var/log/mysql/mysql.log

Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)

FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

How do I find the width & height of a terminal window?

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

How to prevent XSS with HTML/PHP?

<?php
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');

// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);

do
{
    // Remove really unwanted tags
    $old_data = $data;
    $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);

// we are done...
return $data;
}

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

You can't, the only things you can do with html is open your default email application. You must use a server code to send an email, php, asp .net....

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

You can browse package folder below method.

  1. Use Sublime Text 2 menu : Preferences\Browse Packages
  2. In Windows 7 : C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages (equals %appdata%\Sublime Text 2\Packages)

Formula px to dp, dp to px android

Use these Kotlin extensions:

/**
 * Converts Pixel to DP.
 */
val Int.pxToDp: Int
    get() = (this / Resources.getSystem().displayMetrics.density).toInt()

/**
 * Converts DP to Pixel.
 */
val Int.dpToPx: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Convert string to symbol-able in ruby

intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist

"edition".intern # :edition

http://ruby-doc.org/core-2.1.0/String.html#method-i-intern

What's the meaning of exception code "EXC_I386_GPFLT"?

In my case EXC_I386_GPFLT was caused by missing return value in the property getter. Like this:

- (CppStructure)cppStructure
{
    CppStructure data;
    data.a = self.alpha;
    data.b = self.beta;

    return data; // this line was missing
}

Xcode 12.2

How to install a plugin in Jenkins manually

The accepted answer is accurate, but make sure that you also install all necessary dependencies as well. Installing using the CLI or web seems to take care of this, but my plugins were not showing up in the browser or using java -jar jenkins-cli.jar -s http://localhost:8080 list-plugins until I also installed the dependencies.

XAMPP Object not found error

I had recently the same issue, It might not be the same as your case, but if anyone has a similar situation as mine, somehow I deleted the .htaccess file in the root of my app, so I copied it back from a backup and it worked

JavaScript alert not working in Android WebView

if you wish to hide URL from the user, Show an AlertDialog as below.

myWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        mContext);
                builder.setMessage(message)
                        .setNeutralButton("OK", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                            }
                        }).show();
                result.cancel();
                return true;
            }
    }

Currency formatting in Python

Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.

The example the OP gave would simply be:

>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18

Combine Date and Time columns using python pandas

You can use this to merge date and time into the same column of dataframe.

import pandas as pd    
data_file = 'data.csv' #path of your file

Reading .csv file with merged columns Date_Time:

data = pd.read_csv(data_file, parse_dates=[['Date', 'Time']]) 

You can use this line to keep both other columns also.

data.set_index(['Date', 'Time'], drop=False)

Find and kill a process in one line using bash and regex

I use this to kill Firefox when it's being script slammed and cpu bashing :) Replace 'Firefox' with the app you want to die. I'm on the Bash shell - OS X 10.9.3 Darwin.

kill -Hup $(ps ux | grep Firefox | awk 'NR == 1 {next} {print $2}' | uniq | sort)

How to list imported modules?

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

XAMPP Start automatically on Windows 7 startup

I am using XAMPP on Win 7 and 8.1 too...it start normally.

Did you try to check the services on Start > RUN > services.msc

Find the service: Apache 2.x. (right click) choose Properties. At form "Startup type" choose "Automatically" and Start the service on.

you should reset the PC and check out again.

Do the same with mySQL.

If you can not solve the problem, use XAMPP Panel to start it manually.

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

Using the Jersey client to do a POST operation

Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:

    WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
    formData.add("key1", "value1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Note that the form entity is sent in the format of "application/x-www-form-urlencoded".

Resetting Select2 value in dropdown with reset button

to remove all option value

$("#id").empty();

Shortcuts in Objective-C to concatenate NSStrings

Either of these formats work in XCode7 when I tested:

NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
  @"This"
  " and that"
  " and one more"
};

NSLog(@"\n%@\n\n%@",sTest1,sTest2);

For some reason, you only need the @ operator character on the first string of the mix.

However, it doesn't work with variable insertion. For that, you can use this extremely simple solution with the exception of using a macro on "cat" instead of "and".

PuTTY scripting to log onto host

entering a command after you logged in can be done by going through SSH section at the bottom of putty and you should have an option Remote command (data to send to the server) separate the two commands with ;

When to use a View instead of a Table?

Views are acceptable when you need to ensure that complex logic is followed every time. For instance, we have a view that creates the raw data needed for all financial reporting. By having all reports use this view, everyone is working from the same data set, rather than one report using one set of joins and another forgetting to use one which gives different results.

Views are acceptable when you want to restrict users to a particular subset of data. For instance, if you do not delete records but only mark the current one as active and the older versions as inactive, you want a view to use to select only the active records. This prevents people from forgetting to put the where clause in the query and getting bad results.

Views can be used to ensure that users only have access to a set of records - for instance, a view of the tables for a particular client and no security rights on the tables can mean that the users for that client can only ever see the data for that client.

Views are very helpful when refactoring databases.

Views are not acceptable when you use views to call views which can result in horrible performance (at least in SQL Server). We almost lost a multimillion dollar client because someone chose to abstract the database that way and performance was horrendous and timeouts frequent. We had to pay for the fix too, not the client, as the performance issue was completely our fault. When views call views, they have to completely generate the underlying view. I have seen this where the view called a view which called a view and so many millions of records were generated in order to see the three the user ultimately needed. I remember one of these views took 8 minutes to do a simple count(*) of the records. Views calling views are an extremely poor idea.

Views are often a bad idea to use to update records as usually you can only update fields from the same table (again this is SQL Server, other databases may vary). If that's the case, it makes more sense to directly update the tables anyway so that you know which fields are available.

Get name of object or class

Try this:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];

What causes this error? "Runtime error 380: Invalid property value"

Could be you are locating in the screen a control (label, frame, text..) out of the screen borders. If the position of some control depends of any variable, and that variable is not correctly defined at start, you may have this error message.

May be you have different screen resolution in both computers. And that could be the reason.

in order to find the program bug, put this line in all subs: on error resume next

if this correct the problem, you must clear this line in every sub, one by one, and verifying if the problem returns. When the problem returns after removing this line in a concrete sub, you will know the subroutine that stores the bug. Search there and you will find it.

[email protected]

How to repeat last command in python interpreter shell?

In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys.

Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

np.isnan can be applied to NumPy arrays of native dtype (such as np.float64):

In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)

but raises TypeError when applied to object arrays:

In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Since you have Pandas, you could use pd.isnull instead -- it can accept NumPy arrays of object or native dtypes:

In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)

In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)

Note that None is also considered a null value in object arrays.

Submit form using a button outside the <form> tag

This work perfectly! ;)

This can be done using Ajax and with what I call: "a form mirror element". Instead to send a form with an element outside, you can create a fake form. The previous form is not needed.

<!-- This will do the trick -->
<div >
    <input id="mirror_element" type="text" name="your_input_name">
    <input type="button" value="Send Form">
</div>

Code ajax would be like:

    <script>
        ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");

        function ajax_form_mirror(form, file, element, method) {
            $(document).ready(function() {
                // Ajax
                $(form).change(function() { // catch the forms submit event
                    $.ajax({                // create an AJAX call...
                        data: $(this).serialize(),      // get the form data
                        type: method,                   // GET or POST
                        url: file,                      // the file to call
                        success: function (response) {   // on success..
                        $(element).html(response);  // update the DIV
                        }
                    });

                    return false; // cancel original event to prevent form submitting
                });
            });
        }
   </script>

This is very usefull if you want to send some data inside another form without submit the parent form.

This code probably can be adapted/optimized according to the need. It works perfectly!! ;) Also works if you want a select option box like this:

<div>
    <select id="mirror_element" name="your_input_name">
        <option id="1" value="1">A</option>
        <option id="2" value="2">B</option>
        <option id="3" value="3">C</option>
        <option id="4" value="4">D</option>
    </select>
</div>

I hope it helped someone like it helped me. ;)

System.Security.SecurityException when writing to Event Log

try below in web.config

 <system.web>

<trust level="Full"/>

</system.web>

How to generate a number of most distinctive colors in R?

You can use colorRampPalette from base or RColorBrewer package:

With colorRampPalette, you can specify colours as follows:

colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"

You can alternatively provide hex codes as well:

colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...

With RColorBrewer you could use colors from pre-existing palettes:

require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"

Look at RColorBrewer package for other available palettes. Hope this helps.

What are good message queue options for nodejs?

I used KUE with socketIO like you described. I stored the socketID with the job and could then retreive it in the Job Complete.. KUE is based on redis and has good examples on github

something like this....

jobs.process('YourQueuedJob',10, function(job, done){
    doTheJob(job, done);
});


function doTheJob(job, done){
    var socket = io.sockets.sockets[job.data.socketId];
    try {
        socket.emit('news', { status : 'completed' , task : job.data.task });
    } catch(err){
        io.sockets.emit('news', { status : 'fail' , task : job.data.task , socketId: job.data.socketId});
    }
    job.complete();
}