Programs & Examples On #Required field

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

JavaScript: Object Rename Key

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

I wish the syntax wasn't this complex but it is definitely nice having more control.

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

Can I use jQuery with Node.js?

The module jsdom is a great tool. But if you want to evaluate entire pages and do some funky stuff on them server side I suggest running them in their own context:

vm.runInContext

So things like require / CommonJS on site will not blow your Node process itself.

You can find documentation here. Cheers!

How to create a HTML Cancel button that redirects to a URL

There is no button type cancel https://www.w3schools.com/jsref/prop_pushbutton_type.asp

To achieve cancel functionality I used DOM history

_x000D_
_x000D_
<button type="button" class="btn btn-primary" onclick="window.history.back();">Cancel</button>
_x000D_
_x000D_
_x000D_

For more details : https://www.w3schools.com/jsref/met_his_back.asp

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For TFS 2013:

Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.

Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes

In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:

  • Ignore this item
  • Ignore by extension
  • Ignore by file name
  • Ignore by ffolder (yes ffolder, TFS 2013 Update 4/Visual Studio 2013 Premium Update 4)

Don't forget to Check In the changed .tfignore-File.

For VS 2015/2017:

The same procedure: In the "Excluded Changes Tab" in TeamExplorer\Pending Changes click on Detected: xxx add(s)

The Excluded Changes Tab in TeamExplorer\Pending Changes

The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

Reading entire html file to String?

You can use JSoup.
It's a very strong HTML parser for java

How to check if a variable is a dictionary in Python?

How would you check if a variable is a dictionary in Python?

This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict.

(Note that you should also not use dict as a variable name - it's the name of the builtin object.)

If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.

I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.

is is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.

So I will provide several options that do.

Supporting inheritance:

This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict, defaultdict, or Counter from the collections module:

if isinstance(any_object, dict):

But there are even more flexible options.

Supporting abstractions:

from collections.abc import Mapping

if isinstance(any_object, Mapping):

This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict, and still get the correct behavior.

Use the interface

You commonly hear the OOP advice, "program to an interface".

This strategy takes advantage of Python's polymorphism or duck-typing.

So just attempt to access the interface, catching the specific expected errors (AttributeError in case there is no .items and TypeError in case items is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems() is gone in Python 3):

try:
    items = any_object.items()
except (AttributeError, TypeError):
    non_items_behavior(any_object)
else: # no exception raised
    for item in items: ...

Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.

Conclusion

Don't use is to check types for standard control flow. Use isinstance, consider abstractions like Mapping or MutableMapping, and consider avoiding type-checking altogether, using the interface directly.

Make a dictionary in Python from input values

n = int(input("enter a n value:"))
d = {}

for i in range(n):
    keys = input() # here i have taken keys as strings
    values = int(input()) # here i have taken values as integers
    d[keys] = values
print(d)

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

This error may be occur when we are in wrong directory.so use cd command to change your directory. It's not very evident from the above comment that which specific command is giving this error so this answer is based on assumption that you are running ng serve outside the root folder/actual project folder. That's why it's giving error because cli commands require conf & build files to run the cli build.

These should be the steps:
npm install -g @angular/cli  //corrected from 'angular-cli'
ng new projectname
cd projectname
ng serve
open http://localhost:4200

Is there a better alternative than this to 'switch on type'?

With C# 7, which shipped with Visual Studio 2017 (Release 15.*), you are able to use Types in case statements (pattern matching):

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

With C# 6, you can use a switch statement with the nameof() operator (thanks @Joey Adams):

switch(o.GetType().Name) {
    case nameof(AType):
        break;
    case nameof(BType):
        break;
}

With C# 5 and earlier, you could use a switch statement, but you'll have to use a magic string containing the type name... which is not particularly refactor friendly (thanks @nukefusion)

switch(o.GetType().Name) {
  case "AType":
    break;
}

What is the syntax for adding an element to a scala.collection.mutable.Map?

Create a new immutable map:

scala> val m1 = Map("k0" -> "v0")   
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)

Add a new key/value pair to the above map (and create a new map, since they're both immutable):

scala> val m2 = m1 + ("k1" -> "v1")             
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)

What's the difference between Thread start() and Runnable run()

The difference is that Thread.start() starts a thread that calls the run() method, while Runnable.run() just calls the run() method on the current thread.

java.lang.IllegalArgumentException: contains a path separator

openFileInput() doesn't accept paths, only a file name if you want to access a path, use File file = new File(path) and corresponding FileInputStream

What is difference between sleep() method and yield() method of multi threading?

One way to request the current thread to relinquish CPU so that other threads can get a chance to execute is to use yield in Java.

yield is a static method. It doesn't say which other thread will get the CPU. It is possible for the same thread to get back the CPU and start its execution again.

public class Solution9  {

public static void main(String[] args) {
        yclass yy = new yclass ();
        Thread t1= new Thread(yy);
        t1.start();
        for (int i = 0; i <3; i++) {
            Thread.yield();
            System.out.println("during yield control => " + Thread.currentThread().getName());
        }
    }
}

class yclass implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("control => " + Thread.currentThread().getName());
        }
    }
}

Lost httpd.conf file located apache

See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf

Generically, you can determine the answer by running the command:

httpd -V

(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V

This will return various details about how httpd is built and configured, including the default location of the main configuration file.

One of the lines of output should look like:

-D SERVER_CONFIG_FILE="conf/httpd.conf"

which, combined with the line:

-D HTTPD_ROOT="/etc/httpd"

will give you a full path to the default location of the configuration file

How to change time in DateTime?

When you construct your DateTime object, use a constructor that allows you to specify time:

var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42);  // 2000-01-01 13:37:42

If you already have a DateTime object and wish to change the time, uou can add minutes, hours or seconds to your DateTime using simple methods:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13);                     // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37);                   // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42);                  // 2000-01-01 13:37:42

Notice how we have to "save" the result from each method call to the myDateTime variable. This is because the DateTime is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.

If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpan to the original DateTime instead:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42);                   // 2000-01-01 13:37:42

If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTime constructor, and reuse values for year/month/day from earlier:

myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
                          20, 33, 19)                     // 2000-01-01 20:33:19

How can I get input radio elements to horizontally align?

Here is updated Fiddle

Simply remove </br> between input radio's

<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>

What is the best or most commonly used JMX Console / Client

jminix is an embedded web based JMX console. Not sure if it's maintained any longer, but still.

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

How to write a PHP ternary operator

echo ($result ->vocation == 1) ? 'Sorcerer'
        : ($result->vocation == 2) ? 'Druid'
           :  ($result->vocation == 3) ? 'Paladin'
                    ....

;

It’s kind of ugly. You should stick with normal if statements.

What is the equivalent of Select Case in Access SQL?

Consider the Switch Function as an alternative to multiple IIf() expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE approach you referenced but which is not available in Access SQL.

If you want to display a calculated field as commission:

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

If you want to store that calculated value to a field named commission:

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

Either way, see whether you find Switch() easier to understand and manage. Multiple IIf()s can become mind-boggling as the number of conditions grows.

Converting a number with comma as decimal point to float

If you're using PHP5.3 or above, you can use numfmt_parse to do "a reversed number_format". If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.

Dart SDK is not configured

In my machine, flutter was installed in

C:\src\flutter

I set dart sdk path as

C:\src\flutter\bin\cache\dart-sdk

This solved my problem

Which keycode for escape key with jQuery

I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...

if (keyCode == 27)
{
    history.back();

    if (window.event)
    {
        // IE works fine anyways so this isn't really needed
        e.cancelBubble = true;
        e.returnValue = false;
    }
    else if (e.stopPropagation)
    {
        // In firefox, this is what keeps the escape key from canceling the history.back()
        e.stopPropagation();
        e.preventDefault();
    }

    return (false);
}

How do I convert a Python program to a runnable .exe Windows program?

Understand that every 'freezing' application for Python will not really secure your code in any way. Every packaging system for a stand-alone executable Python 'program' will include a lot of the Python libraries and interpreter, which will make your program pretty large.

That said, PyInstaller has done a nearly flawless job with everything I've thrown at it. Currently it only supports up to Python 2.7 but Pyinstaller's support for a varied set of libraries large and small is unmatched in other 'freeze' type programs for Python.

How do you build a Singleton in Dart?

Here is a comparison of several different ways to create a singleton in Dart.

1. Factory constructor

class SingletonOne {

  SingletonOne._privateConstructor();

  static final SingletonOne _instance = SingletonOne._privateConstructor();

  factory SingletonOne() {
    return _instance;
  }

}

2. Static field with getter

class SingletonTwo {

  SingletonTwo._privateConstructor();

  static final SingletonTwo _instance = SingletonTwo._privateConstructor();

  static SingletonTwo get instance => _instance;
  
}

3. Static field

class SingletonThree {

  SingletonThree._privateConstructor();

  static final SingletonThree instance = SingletonThree._privateConstructor();
  
}

How to instantiate

The above singletons are instantiated like this:

SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;

Note:

I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.

Android Completely transparent Status Bar?

The following code will make your status bar along with the navigation bar transparent (note that this will make your layout a full screen layout like the layouts used in games):

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables sticky immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE_STICKY.
    // Or for regular immersive mode replace it with SYSTEM_UI_FLAG_IMMERSIVE
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

To learn more, visit this link.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

How to hide html source & disable right click and text copy?

<script>
$(document).ready(function() {
    document.onkeydown = function(e){
        if (e.ctrlKey &&
            (e.keyCode === 67 ||
                e.keyCode === 86 ||
                e.keyCode === 85 ||
                e.keyCode === 117)) {
            return false;
        } else {
            return true;
        }
    };
});
</script>

Retrieve column names from java.sql.ResultSet

ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery(); 
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1

String nameValuePair = "";
while (rsTst.next()) {
    for (int i = 1; i < columnCount + 1; i++ ) {
        String name = meta.getColumnName(i);
        // Do stuff with name

        String value = rsTst.getString(i); //.getObject(1);
        nameValuePair = nameValuePair + name + "=" +value + ",";
        //nameValuePair = nameValuePair + ", ";
    }
    nameValuePair = nameValuePair+"||" + "\t";
}

Floating point vs integer calculations on modern hardware

Addition is much faster than rand, so your program is (especially) useless.

You need to identify performance hotspots and incrementally modify your program. It sounds like you have problems with your development environment that will need to be solved first. Is it impossible to run your program on your PC for a small problem set?

Generally, attempting FP jobs with integer arithmetic is a recipe for slow.

Hiding the address bar of a browser (popup)

Its not possible to hide address bar of browser.

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Getting attribute using XPath

The standard formula to extract the values of attribute using XPath is

elementXPath/@attributeName

So here is the xpath to fetch the lang value of first attribute-

//title[text()='Harry Potter']/@lang

PS: indexes are never suggested to use in XPath as they can change if one more title tag comes in.

CORS header 'Access-Control-Allow-Origin' missing

Server side put this on top of .php:

 header('Access-Control-Allow-Origin: *');  

You can set specific domain restriction access:

header('Access-Control-Allow-Origin: https://www.example.com')

jquery $.each() for objects

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

How to enable DataGridView sorting when user clicks on the column header?

One more way to do this is using "System.Linq.Dynamic" library. You can get this library from Nuget. No need of any custom implementations or sortable List :)

using System.Linq.Dynamic;
private bool sortAscending = false;

private void dataGridView_ColumnHeaderMouseClick ( object sender, DataGridViewCellMouseEventArgs e )
{
    if ( sortAscending )
        dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).ToList ( );
    else
        dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).Reverse ( ).ToList ( );
    sortAscending = !sortAscending;
}

How can I remove specific rules from iptables?

First list all iptables rules with this command:

iptables -S

it lists like:

-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

Then copy the desired line, and just replace -A with -D to delete that:

iptables -D XYZ -p ...

VSCode regex find & replace submatch math?

Another simple example:

Search: style="(.+?)"
Replace: css={css`$1`}

Useful for converting HTML to JSX with emotion/css!

Check if a temporary table exists and delete if it exists before creating a temporary table

I usually hit this error when I have already created the temp table; the code that checks the SQL statement for errors sees the "old" temp table in place and returns a miscount on the number of columns in later statements, as if the temp table was never dropped.

After changing the number of columns in a temp table after already creating a version with less columns, drop the table and THEN run your query.

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Android 'Unable to add window -- token null is not for an application' exception

I got the same exception. what i do to fix this is to pass instance of the dialog as parameter into function and use it instead of pass only context then using getContext(). this solution solve my problem, hope it can help

Laravel where on relationship object

    return Deal::with(["redeem" => function($q){
        $q->where('user_id', '=', 1);
    }])->get();

this worked for me

Load dimension value from res/values/dimension.xml from source code

You can use getDimensionPixelOffset() instead of getDimension, so you didn't have to cast to int.

int valueInPixels = getResources().getDimensionPixelOffset(R.dimen.test)

Getting visitors country from their IP

I know this is old, but I tried a few other solutions on here and they seem to be outdated or just return null. So this is how I did it.

Using http://www.geoplugin.net/json.gp?ip= which doesn't require any type of sign up or paying for the service.

function get_client_ip_server() {
  $ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
  $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
  $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
  $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
  $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
  $ipaddress = $_SERVER['REMOTE_ADDR'];
else
  $ipaddress = 'UNKNOWN';

  return $ipaddress;
}

$ipaddress = get_client_ip_server();

function getCountry($ip){
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, 'http://www.geoplugin.net/json.gp?ip='.$ip);
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

    $jsonData = json_decode(curl_exec($curlSession));
    curl_close($curlSession);

    return $jsonData->geoplugin_countryCode;
}

echo "County: " .getCountry($ipaddress);

And if you want extra information about it, this is a full return of Json:

{
  "geoplugin_request":"IP_ADDRESS",
  "geoplugin_status":200,
  "geoplugin_delay":"2ms",
  "geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from <a href='http:\/\/www.maxmind.com'>http:\/\/www.maxmind.com<\/a>.",
  "geoplugin_city":"Current City",
  "geoplugin_region":"Region",
  "geoplugin_regionCode":"Region Code",
  "geoplugin_regionName":"Region Name",
  "geoplugin_areaCode":"",
  "geoplugin_dmaCode":"650",
  "geoplugin_countryCode":"US",
  "geoplugin_countryName":"United States",
  "geoplugin_inEU":0,
  "geoplugin_euVATrate":false,
  "geoplugin_continentCode":"NA",
  "geoplugin_continentName":"North America",
  "geoplugin_latitude":"37.5563",
  "geoplugin_longitude":"-99.9413",
  "geoplugin_locationAccuracyRadius":"5",
  "geoplugin_timezone":"America\/Chicago",
  "geoplugin_currencyCode":"USD",
  "geoplugin_currencySymbol":"$",
  "geoplugin_currencySymbol_UTF8":"$",
  "geoplugin_currencyConverter":1
}

plot.new has not been called yet

Some action, very possibly not represented in the visible code, has closed the interactive screen device. It could be done either by a "click" on a close-button. (Could also be done by an extra dev.off() when plotting to a file-graphics device. This may happen if you paste in a mult-line plotting command that has a dev,off() at the end of it but errors out at the opening of the external device but then has hte dev.off() on a separate line so it accidentally closes the interactive device).

Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it. On Windows that might be window(); on a Mac, quartz(); and on a linux box, x11(). You also may need to issue a plot.new() command. I just follow orders. When I get that error I issue plot.new() and if I don't see a plot window, I issue quartz() as well. I then start over from the beginning with a new plot(., ., ...) command and any further additions to that plot screen image.

Change app language programmatically in Android

I know it's late to answer but i found this article here . Which explains the whole process very well and provides you a well structured code.

Locale Helper class:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * This class is used to change your application locale and persist this change for the next time
 * that your app is going to be used.
 * <p/>
 * You can also change the locale of your application on the fly by using the setLocale method.
 * <p/>
 * Created by gunhansancar on 07/10/15.
 */
public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

You need to override attachBaseContext and call LocaleHelper.onAttach() to initialize the locale settings in your application.

import android.app.Application;
import android.content.Context;

import com.gunhansancar.changelanguageexample.helper.LocaleHelper;

public class MainApplication extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
    }
}

All you have to do is to add

LocaleHelper.onCreate(this, "en");

wherever you want to change the locale.

Should URL be case sensitive?

I think this and many of the answers around what the spec does or does not say is missing the point of the question.Should they be case sensitive? That's a loaded question really. From a user's point of view, case sensitivity is a pain point, not all know makes a difference. The question of whether URIs should or shouldn't be, depends on the context of the question. For technical flexibility, yes, they should be. For usability, no, they should not be.

Failed to resolve: com.google.firebase:firebase-core:16.0.1

From the docs:-

Your app gradle file now has to explicitly list com.google.firebase:firebase-core as a dependency for Firebase services to work as expected.

Add:

 implementation 'com.google.firebase:firebase-core:16.0.1'

and in top level gradle file use the latest version of google play services:

classpath 'com.google.gms:google-services:4.0.2'

https://firebase.google.com/support/release-notes/android

https://bintray.com/android/android-tools/com.google.gms.google-services

Note:

You need to add the google() repo in the top level gradle file, as specified in the firebase docs and also it should be before jcenter():

 buildscript {
  repositories {
          google()
          jcenter()
      }



dependencies {
  classpath 'com.android.tools.build:gradle:3.1.3'
  classpath 'com.google.gms:google-services:4.0.2'
   }
}

allprojects {
     repositories {
              google()
             jcenter()
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
 }

https://firebase.google.com/docs/android/setup

How can I convert a stack trace to a string?

Without java.io.* it can be done like this.

String trace = e.toString() + "\n";                     

for (StackTraceElement e1 : e.getStackTrace()) {
    trace += "\t at " + e1.toString() + "\n";
}   

And then the trace variable holds your stack trace. Output also holds the initial cause, the output is identical to printStackTrace()

Example, printStackTrace() yields:

java.io.FileNotFoundException: / (Is a directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at Test.main(Test.java:9)

The trace String holds, when printed to stdout

java.io.FileNotFoundException: / (Is a directory)
     at java.io.FileOutputStream.open0(Native Method)
     at java.io.FileOutputStream.open(FileOutputStream.java:270)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
     at Test.main(Test.java:9)

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Jump to function definition in vim

1- install exuberant ctags. If you're using osx, this article shows a little trick: http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html

2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:

ctags -R

This will create a "tags" file for you.

3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:

ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`

credit: https://coderwall.com/p/lv1qww (Note that I omitted the -e option which generates tags for emacs instead of vim)

4- Add the following line to your ~/.vimrc

set autochdir 
set tags+=./tags;

(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )

5- Go to the word you'd like to follow and hit ctrl + ] ; if you'd like to go back, use ctrl+o (source: https://stackoverflow.com/a/53929/226255)

How to insert multiple rows from array using CodeIgniter framework?

Assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

That said, it sounds like you might be running into string-handling problems in PHP, which is really an algorithm problem, not a language one. Basically, when working with large strings, you want to minimize unnecessary copying. Primarily, this means you want to avoid concatenation. The fastest and most memory efficient way to build a large string, such as for inserting hundreds of rows at one, is to take advantage of the implode() function and array assignment.

$sql = array(); 
foreach( $data as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));

The advantage of this approach is that you don't copy and re-copy the SQL statement you've so far assembled with each concatenation; instead, PHP does this once in the implode() statement. This is a big win.

If you have lots of columns to put together, and one or more are very long, you could also build an inner loop to do the same thing and use implode() to assign the values clause to the outer array.

how to delete default values in text field using selenium?

For page object model -

 @FindBy(xpath="//foo")
   public WebElement textBox;

now in your function

 public void clearExistingText(String newText){
    textBox.clear();
    textBox.sendKeys(newText);
  }

for general selenium architecture -

driver.findElement(By.xpath("//yourxpath")).clear();
driver.findElement(By.xpath("//yourxpath")).sendKeys("newText");

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

Unable to Cast from Parent Class to Child Class

The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.

More specifically:

Base derivedInstance = new Derived();
Base baseInstance = new Base();

Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException

For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.

Copying a rsa public key to clipboard

Another alternative solution:

cat  ~/.ssh/id_rsa.pub |  xsel -i -b

From man xsel :

-i, --input

read standard input into the selection.

-b, --clipboard

operate on the CLIPBOARD selection.

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

Actionbar notification count icon (badge) like Google has

I found a very good solution here, I'm using it with kotlin.

First, in the drawable folder you have to create item_count.xml:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f20000" />
<stroke
    android:width="2dip"
    android:color="#FFF" />
<padding
    android:bottom="5dp"
    android:left="5dp"
    android:right="5dp"
    android:top="5dp" />
</shape>

In your Activity_Main Layout some like:

<RelativeLayout
                    android:id="@+id/badgeLayout"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_toRightOf="@+id/badge_layout1"
                    android:layout_gravity="end|center_vertical"
                    android:layout_marginEnd="5dp">

                <RelativeLayout
                        android:id="@+id/relative_layout1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                    <Button
                            android:id="@+id/btnBadge"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@mipmap/ic_notification" />

                </RelativeLayout>

                <TextView
                        android:id="@+id/txtBadge"
                        android:layout_width="18dp"
                        android:layout_height="18dp"
                        android:layout_alignRight="@id/relative_layout1"
                        android:background="@drawable/item_count"
                        android:text="22"
                        android:textColor="#FFF"
                        android:textSize="7sp"
                        android:textStyle="bold"
                        android:gravity="center"/>

            </RelativeLayout>

And you can modify like:

btnBadge.setOnClickListener { view ->
        Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
        txtBadge.text = "0"
    }

Python urllib2: Receive JSON response from url

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

Get first element from a dictionary

For anyone coming to this that wants a linq-less way to get an element from a dictionary

var d = new Dictionary<string, string>();
d.Add("a", "b");
var e = d.GetEnumerator();
e.MoveNext();
var anElement = e.Current;
// anElement/e.Current is a KeyValuePair<string,string>
// where Key = "a", Value = "b"

I'm not sure if this is implementation specific, but if your Dictionary doesn't have any elements, Current will contain a KeyValuePair<string, string> where both the key and value are null.

(I looked at the logic behind linq's First method to come up with this, and tested it via LinqPad 4)

How can I disable HREF if onclick is executed?

<a href="http://www.google.com" class="ignore-click">Test</a>

with jQuery:

<script>
    $(".ignore-click").click(function(){
        return false;
    })
</script>

with JavaScript

<script>
        for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
            document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
                event.preventDefault();
                return false;
            });
        }
</script>

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored

How to make use of ng-if , ng-else in angularJS

You can write as:

<div class="case" ng-if="mydata.id === '5' ">
    <p> this will execute </p>
</div>
<div class="case" ng-if="mydata.id !== '5' ">
    <p> this will execute </p>
</div> 

PostgreSQL 'NOT IN' and subquery

You could also use a LEFT JOIN and IS NULL condition:

SELECT 
  mac, 
  creation_date 
FROM 
  logs
    LEFT JOIN consols ON logs.mac = consols.mac
WHERE 
  logs_type_id=11
AND
  consols.mac IS NULL;

An index on the "mac" columns might improve performance.

Should __init__() call the parent class's __init__()?

Yes, you should always call base class __init__ explicitly as a good coding practice. Forgetting to do this can cause subtle issues or run time errors. This is true even if __init__ doesn't take any parameters. This is unlike other languages where compiler would implicitly call base class constructor for you. Python doesn't do that!

The main reason for always calling base class _init__ is that base class may typically create member variable and initialize them to defaults. So if you don't call base class init, none of that code would be executed and you would end up with base class that has no member variables.

Example:

class Base:
  def __init__(self):
    print('base init')

class Derived1(Base):
  def __init__(self):
    print('derived1 init')

class Derived2(Base):
  def __init__(self):
    super(Derived2, self).__init__()
    print('derived2 init')

print('Creating Derived1...')
d1 = Derived1()
print('Creating Derived2...')
d2 = Derived2()

This prints..

Creating Derived1...
derived1 init
Creating Derived2...
base init
derived2 init

Run this code.

Content Type text/xml; charset=utf-8 was not supported by service

I was facing the similar issue when using the Channel Factory. it was actually due to wrong Contract specified in the endpoint.

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

simulate background-size:cover on <video> or <img>

Guys I have a better solution its short and works perfectly to me. I used it to video. And its perfectly emulates the cover option in css.

Javascript

    $(window).resize(function(){
            //use the aspect ration of your video or image instead 16/9
            if($(window).width()/$(window).height()>16/9){
                $("video").css("width","100%");
                $("video").css("height","auto");
            }
            else{
                $("video").css("width","auto");
                $("video").css("height","100%");
            }
    });

If you flip the if, else you will get contain.

And here is the css. (You don't need to use it if you don't want center positioning, the parent div must be "position:relative")

CSS

video {
position: absolute;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
top: 50%;
left: 50%;}

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

How to download the latest artifact from Artifactory repository?

The role of Artifactory is to provide files for Maven (as well as other build tools such as Ivy, Gradle or sbt). You can just use Maven together with the maven-dependency-plugin to copy the artifacts out. Here's a pom outline to start you off...

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>A group id</groupId>
    <artifactId>An artifact id</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>The group id of your artifact</groupId>
                                    <artifactId>The artifact id</artifactId>
                                    <version>The snapshot version</version>
                                    <type>Whatever the type is, for example, JAR</type>
                                    <outputDirectory>Where you want the file to go</outputDirectory>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Just run mvn install to do the copy.

What's the use of ob_start() in php?

I prefer:

ob_start();
echo("Hello there!");
$output = ob_get_clean(); //Get current buffer contents and delete current output buffer

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

Using Environment Variables with Vue.js

A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.

Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.

So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Based on the above, in production, you would be able to get the NODE_ENV variable

mounted() {
  console.log(process.env.NODE_ENV)
}

Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"'
      }
    })
  ]);

} 

Now if you want to add other variables with would be as simple as:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);
}

I should also note that you seem to need the "''" double quotes for some reason.

So, in Development, I can now access these Environment Variables:

mounted() {
  console.log(process.env.ENDPOINT)
  console.log(process.env.FOO)
}

Here is the whole webpack.config.js just for some context:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);

}

7-Zip command to create and extract a password-protected ZIP file on Windows?

I'm maybe a little bit late but I'm currently trying to develop a program which can brute force a password protected zip archive. First I tried all commands I found in the internet to extract it through cmd... But it never worked....Every time I tried it, the cmd output said, that the key was wrong but it was right. I think they just disenabled this function in a current version.

What I've done to Solve the problem was to download an older 7zip version(4.?) and to use this for extracting through cmd.

This is the command: "C:/Program Files (86)/old7-zip/7z.exe" x -pKey "C:/YOURE_ZIP_PATH"

The first value("C:/Program Files (86)/old7-zip/7z.exe") has to be the path where you have installed the old 7zip to. The x is for extract and the -p For you're password. Make sure you put your password without any spaces behind the -p! The last value is your zip archive to extract. The destination where the zip is extracted to will be the current path of cmd. You can change it with: cd YOURE_PATH

Now I let execute this command through java with my password trys. Then I check the error output stream of cmd and if it is null-> then the password is right!

Android Debug Bridge (adb) device - no permissions

Same problem with Pipo S1S after upgrading to 4.2.2 stock rom Jun 4.

$ adb devices
List of devices attached  
????????????    no permissions

All of the above suggestions, while valid to get your usb device recognised, do not solve the problem for me. (Android Debug Bridge version 1.0.31 running on Mint 15.)

Updating android sdk tools etc resets ~/.android/adb_usb.ini.

To recognise Pipo VendorID 0x2207 do these steps

Add to line /etc/udev/rules.d/51-android.rules

SUBSYSTEM=="usb", ATTR{idVendor}=="0x2207", MODE="0666", GROUP="plugdev"

Add line to ~/.android/adb_usb.ini:

0x2207

Then remove the adbkey files

rm -f ~/.android/adbkey ~/.android/adbkey.pub

and reconnect your device to rebuild the key files with a correct adb connection. Some devices will ask to re-authorize.

sudo adb kill-server
sudo adb start-server   
adb devices

how to refresh page in angular 2

Updated

How to implement page refresh in Angular 2+ note this is done within your component:

location.reload();

Delete all nodes and relationships in neo4j 1.8

if the name of node is for example : abcd then below query will work :

MATCH (n:abcd)
DETACH DELETE n

This will only delete the node with label "abcd" and all its relation-ships.

Read input stream twice

If you are using RestTemplate to make http calls Simply add an interceptor. Response body is cached by the implementation of ClientHttpResponse. Now inputstream can be retrieved from respose as many times as we need

ClientHttpRequestInterceptor interceptor =  new ClientHttpRequestInterceptor() {

            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                    ClientHttpRequestExecution execution) throws IOException {
                ClientHttpResponse  response = execution.execute(request, body);

                  // additional work before returning response
                  return response 
            }
        };

    // Add the interceptor to RestTemplate Instance 

         restTemplate.getInterceptors().add(interceptor); 

How do I show/hide a UIBarButtonItem?

My answer is here for Swift 4!

if $0 {
    self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button1)]
} else {
    self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button2)]
}

How to get a list of properties with a given attribute?

There's always LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

Cannot find firefox binary in PATH. Make sure firefox is installed

I've just had this issue without changing PATH.

My PC is Win7, 64-bit system, If you are also using 64-bit system, you may want to try:

  1. uninstall your current Firefox.
  2. install new Firefox under "C:\Program Files (x86)\Mozilla Firefox\" path.

It must be under "Program Files (x86)" NOT "Program Files"

Hope it can help.

Angular 6 Material mat-select change method removed

I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange

I put here a little code for understanding :

<mat-form-field >
  <mat-label>Filter By</mat-label>
  <mat-select  panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->

    <mat-option >-- None --</mat-option>
      <mat-optgroup  *ngFor="let group of filterData" [label]="group.viewValue"
                    style = "background-color: #0c5460">
        <mat-option *ngFor="let option of group.options" [value]="option.value">
          {{option.viewValue}}
        </mat-option>
      </mat-optgroup>
  </mat-select>
</mat-form-field>

Mat Version:

"@angular/material": "^6.4.7",

Android Activity as a dialog

Use this code so that the dialog activity won't be closed when the user touches outside the dialog box:

this.setFinishOnTouchOutside(false);

requires API level 11

heroku - how to see all the logs

You need to use -t or --tail option and you need to define your heroku app name.

heroku logs -t --app app_name

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

How do I make HttpURLConnection use a proxy?

The approved answer will work ... if you know your proxy host and port =) . But in case you are looking for the proxy host and port the steps below should help

if auto configured proxy is given: then

1> open IE(or any browser)

2> get the url address from your browser through IE->Tools->internet option->connections->LAN Settings-> get address and give in url eg: as http://autocache.abc.com/ and enter, a file will be downloaded with .pac format, save to desktop

3> open .pac file in textpad, identify PROXY:

In your editor, it will come something like:

return "PROXY web-proxy.ind.abc.com:8080; PROXY proxy.sgp.abc.com:8080";

kudos to bekur from maven in 5 min not working

Once you have the host and port just pop in into this and your good to go

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("web-proxy.ind.abc.com", 8080));
        URLConnection connection = new URL(url).openConnection(proxy);

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

I see this topic, but in my case I was looking for a way to improve the format. Using UFormat and adding -1 day

(get-date (get-date).addDays(-1) -UFormat "%Y%m%d-%H%M")

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

Why can't Python find shared objects that are in directories in sys.path?

You can also set LD_RUN_PATH to /usr/local/lib in your user environment when you compile pycurl in the first place. This will embed /usr/local/lib in the RPATH attribute of the C extension module .so so that it automatically knows where to find the library at run time without having to have LD_LIBRARY_PATH set at run time.

Returning a boolean value in a JavaScript function

You could wrap your return value in the Boolean function

Boolean([return value])

That'll ensure all falsey values are false and truthy statements are true.

Blocks and yields in Ruby

There are two points I want to make about yield here. First, while a lot of answers here talk about different ways to pass a block to a method which uses yield, let's also talk about the control flow. This is especially relevant since you can yield MULTIPLE times to a block. Let's take a look at an example:

class Fruit
  attr_accessor :kinds

  def initialize 
    @kinds = %w(orange apple pear banana)
  end

  def each 
    puts 'inside each'
    3.times { yield (@kinds.tap {|kinds| puts "selecting from #{kinds}"} ).sample }
  end  
end

f = Fruit.new
f.each do |kind|
  puts 'inside block'
end    

=> inside each
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block

When the each method is invoked, it executes line by line. Now when we get to the 3.times block, this block will be invoked 3 times. Each time it invokes yield. That yield is linked to the block associated with the method that called the each method. It is important to notice that each time yield is invoked, it returns control back to the block of the each method in client code. Once the block is finished executing, it returns back to the 3.times block. And this happens 3 times. So that block in client code is invoked on 3 separate occasions since yield is explicitly called 3 separate times.

My second point is about enum_for and yield. enum_for instantiates the Enumerator class and this Enumerator object also responds to yield.

class Fruit
  def initialize
    @kinds = %w(orange apple)
  end

  def kinds
    yield @kinds.shift
    yield @kinds.shift
  end
end

f = Fruit.new
enum = f.to_enum(:kinds)
enum.next
 => "orange" 
enum.next
 => "apple" 

So notice every time we invoke kinds with the external iterator, it will invoke yield only once. The next time we call it, it will invoke the next yield and so on.

There's an interesting tidbit with regards to enum_for. The documentation online states the following:

enum_for(method = :each, *args) ? enum
Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }    
# => 120
# => 121
# => 122

If you do not specify a symbol as an argument to enum_for, ruby will hook the enumerator to the receiver's each method. Some classes do not have an each method, like the String class.

str = "I like fruit"
enum = str.to_enum
enum.next
=> NoMethodError: undefined method `each' for "I like fruit":String

Thus, in the case of some objects invoked with enum_for, you must be explicit as to what your enumerating method will be.

How do I measure request and response times at once using cURL?

I made a friendly formatter for sniffing curl requests to help with debugging ( see comments for usage ). It contains's every known output parameter you can write out in an easy to read format.

https://gist.github.com/manifestinteractive/ce8dec10dcb4725b8513

Changing three.js background to transparent or other color

A full answer: (Tested with r71)

To set a background color use:

renderer.setClearColor( 0xffffff ); // white background - replace ffffff with any hex color

If you want a transparent background you will have to enable alpha in your renderer first:

renderer = new THREE.WebGLRenderer( { alpha: true } ); // init like this
renderer.setClearColor( 0xffffff, 0 ); // second param is opacity, 0 => transparent

View the docs for more info.

Default property value in React component using TypeScript

Functional Component

Actually, for functional component the best practice is like below, I create a sample Spinner component:

import React from 'react';
import { ActivityIndicator } from 'react-native';
import { colors } from 'helpers/theme';
import type { FC } from 'types';

interface SpinnerProps {
  color?: string;
  size?: 'small' | 'large' | 1 | 0;
  animating?: boolean;
  hidesWhenStopped?: boolean;
}

const Spinner: FC<SpinnerProps> = ({
  color,
  size,
  animating,
  hidesWhenStopped,
}) => (
  <ActivityIndicator
    color={color}
    size={size}
    animating={animating}
    hidesWhenStopped={hidesWhenStopped}
  />
);

Spinner.defaultProps = {
  animating: true,
  color: colors.primary,
  hidesWhenStopped: true,
  size: 'small',
};

export default Spinner;

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

Java Compare Two Lists

You can try intersection() and subtract() methods from CollectionUtils.

intersection() method gives you a collection containing common elements and the subtract() method gives you all the uncommon ones.

They should also take care of similar elements

How to convert Blob to File in JavaScript

This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

Remove first 4 characters of a string with PHP

If you’re using a multi-byte character encoding and do not just want to remove the first four bytes like substr does, use the multi-byte counterpart mb_substr. This does of course will also work with single-byte strings.

Syntax for a for loop in ruby

Ruby's enumeration loop syntax is different:

collection.each do |item|
...
end

This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.

The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.

Magento: Set LIMIT on collection

There are several ways to do this:

$collection = Mage::getModel('...')
            ->getCollection()
            ->setPageSize(20)
            ->setCurPage(1);

Will get first 20 records.

Here is the alternative and maybe more readable way:

$collection = Mage::getModel('...')->getCollection();
$collection->getSelect()->limit(20);

This will call Zend Db limit. You can set offset as second parameter.

Getting list of parameter names inside python function

If you also want the values you can use the inspect module

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

Excel - Button to go to a certain sheet

You have to add Button to excel sheet(say sheet1) from which you can go to another sheet(say sheet2).

Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.

GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.

To Add button :-

Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.

To give name for button :-

Right click on button -> edit text.

To add code for going to sheet2 :-

Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code

Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate

Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.

How to read a Parquet file into Pandas DataFrame?

Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

The code is simple, just type:

import pyarrow.parquet as pq

df = pq.read_table(source=your_file_path).to_pandas()

For more information, see the document from Apache pyarrow Reading and Writing Single Files

How to include "zero" / "0" results in COUNT aggregate?

You must use LEFT JOIN instead of INNER JOIN

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

Copy/duplicate database without using mysqldump

The best way to clone database tables without mysqldump:

  1. Create a new database.
  2. Create clone-queries with query:

    SET @NewSchema = 'your_new_db';
    SET @OldSchema = 'your_exists_db';
    SELECT CONCAT('CREATE TABLE ',@NewSchema,'.',table_name, ' LIKE ', TABLE_SCHEMA ,'.',table_name,';INSERT INTO ',@NewSchema,'.',table_name,' SELECT * FROM ', TABLE_SCHEMA ,'.',table_name,';') 
    FROM information_schema.TABLES where TABLE_SCHEMA = @OldSchema AND TABLE_TYPE != 'VIEW';
    
  3. Run that output!

But note, script above just fast clone tables - not views, triggers and user-functions: you can fast get structure by mysqldump --no-data --triggers -uroot -ppassword , and then use to clone only insert statement .

Why it is actual question? Because uploading of mysqldumps is ugly slow if DB is over 2Gb. And you can't clone InnoDB tables just by copying DB files (like snapshot backuping).

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java?

No.

Would this be the culprit to the funky characters?

Quite likely.

Change header text of columns in a GridView

You can do it with gridview's datarow bound event. try the following sample of code:

protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}

For more details about the row databound event study Thsi....

Disable/Enable button in Excel/VBA

The following works for me (Excel 2010)

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")

b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call aLongAction
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault

Be aware that .enabled = False does not gray out a button.

The font color has to be set explicitely to get it grayed.

Filezilla FTP Server Fails to Retrieve Directory Listing

In my case, restarting my router which I used to connect to the internet worked. I think too much of connections were going from the same IP Address and when I restarted my router, possibly a new IP was assigned and now everything works fine, and passive mode gives good speed in directory listing.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

How to enumerate an enum

This question appears in Chapter 10 of "C# Step by Step 2013"

The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):

class Pack
{
    public const int NumSuits = 4;
    public const int CardsPerSuit = 13;
    private PlayingCard[,] cardPack;

    public Pack()
    {
        this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
        for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
        {
            for (Value value = Value.Two; value <= Value.Ace; value++)
            {
                cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
            }
        }
    }
}

In this case, Suit and Value are both enumerations:

enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}

and PlayingCard is a card object with a defined Suit and Value:

class PlayingCard
{
    private readonly Suit suit;
    private readonly Value value;

    public PlayingCard(Suit s, Value v)
    {
        this.suit = s;
        this.value = v;
    }
}

How do I request and receive user input in a .bat and use it to run a certain program?

I don't know the platform you're doing this on but I assume Windows due to the .bat extension.

Also I don't have a way to check this but this seems like the batch processor skips the If lines due to some errors and then executes the one with -dev.

You could try this by chaning the two jump targets (:yes and :no) along with the code. If then the line without -dev is executed you know your If lines are erroneous.

If so, please check if == is really the right way to do a comparison in .bat files.

Also, judging from the way bash does this stuff, %foo=="y" might evaluate to true only if %foo includes the quotes. So maybe "%foo"=="y" is the way to go.

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

Simple insecure two-way data "obfuscation"?

I think this is the worlds simplest one !

string encrypted = "Text".Aggregate("", (c, a) => c + (char) (a + 2));

Test

 Console.WriteLine(("Hello").Aggregate("", (c, a) => c + (char) (a + 1)));
            //Output is Ifmmp
 Console.WriteLine(("Ifmmp").Aggregate("", (c, a) => c + (char)(a - 1)));
            //Output is Hello

What does the DOCKER_HOST variable do?

It points to the docker host! I followed these steps:

$ boot2docker start

Waiting for VM and Docker daemon to start...
..............................
Started.

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_HOST=tcp://192.168.59.103:2375

$ export DOCKER_HOST=tcp://192.168.59.103:2375

$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete 
511136ea3c5a: Download complete 
97fd97495e49: Download complete 
2dcbbf65536c: Download complete 
6a459d727ebb: Download complete 
8f321fc43180: Download complete 
03db2b23cf03: Download complete 
Hello world

See:
http://docs.docker.com/userguide/dockerizing/

Bound method error

For this thing you can use @property as an decorator, so you could use instance methods as attributes. For example:

class Word_Parser:
    def __init__(self, sentences):
        self.sentences = sentences

    @property
    def parser(self):
        self.word_list = self.sentences.split()

    @property
    def sort_word_list(self):
        self.sorted_word_list = self.word_list.sort()

    @property
    def num_words(self):
        self.num_words = len(self.word_list)

test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words

so you can use access the attributes without calling (i.e., without the ()).

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

As explained before:

ALTER TABLE TABLEName
drop CONSTRAINT FK_CONSTRAINTNAME;

ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
    FOREIGN KEY (FId)
    REFERENCES OTHERTABLE
        (Id)
    ON DELETE CASCADE ON UPDATE NO ACTION;

As you can see those have to be separated commands, first dropping then adding.

Call two functions from same onclick

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

a workaround to this:

onclick="var temp = function1();function2(); return temp;"

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Sometimes by self-updating composer it solves the problem

php composer.phar self-update

Cheers

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $(".classname").hide();
  });
</script>

Disable double-tap "zoom" option in browser on touch devices

Note (as of 2020-08-04): this solution does not appear to work in iOS Safari v12+. I will update this answer and delete this note once I find a clear solution that covers iOS Safari.

CSS-only solution

Add touch-action: manipulation to any element on which you want to disable double tap zoom, like with the following disable-dbl-tap-zoom class:

.disable-dbl-tap-zoom {
  touch-action: manipulation;
}

From the touch-action docs (emphasis mine):

manipulation

Enable panning and pinch zoom gestures, but disable additional non-standard gestures such as double-tap to zoom.

This value works on Android and on iOS.

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

Android: upgrading DB version and adding new table

@jkschneider's answer is right. However there is a better approach.

Write the needed changes in an sql file for each update as described in the link https://riggaroo.co.za/android-sqlite-database-use-onupgrade-correctly/

from_1_to_2.sql

ALTER TABLE books ADD COLUMN book_rating INTEGER;

from_2_to_3.sql

ALTER TABLE books RENAME TO book_information;

from_3_to_4.sql

ALTER TABLE book_information ADD COLUMN calculated_pages_times_rating INTEGER;
UPDATE book_information SET calculated_pages_times_rating = (book_pages * book_rating) ;

These .sql files will be executed in onUpgrade() method according to the version of the database.

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 4;

    private static final String DATABASE_NAME = "database.db";
    private static final String TAG = DatabaseHelper.class.getName();

    private static DatabaseHelper mInstance = null;
    private final Context context;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public static synchronized DatabaseHelper getInstance(Context ctx) {
        if (mInstance == null) {
            mInstance = new DatabaseHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(BookEntry.SQL_CREATE_BOOK_ENTRY_TABLE);
        // The rest of your create scripts go here.

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.e(TAG, "Updating table from " + oldVersion + " to " + newVersion);
        // You will not need to modify this unless you need to do some android specific things.
        // When upgrading the database, all you need to do is add a file to the assets folder and name it:
        // from_1_to_2.sql with the version that you are upgrading to as the last version.
        try {
            for (int i = oldVersion; i < newVersion; ++i) {
                String migrationName = String.format("from_%d_to_%d.sql", i, (i + 1));
                Log.d(TAG, "Looking for migration file: " + migrationName);
                readAndExecuteSQLScript(db, context, migrationName);
            }
        } catch (Exception exception) {
            Log.e(TAG, "Exception running upgrade script:", exception);
        }

    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private void readAndExecuteSQLScript(SQLiteDatabase db, Context ctx, String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            Log.d(TAG, "SQL script file name is empty");
            return;
        }

        Log.d(TAG, "Script found. Executing...");
        AssetManager assetManager = ctx.getAssets();
        BufferedReader reader = null;

        try {
            InputStream is = assetManager.open(fileName);
            InputStreamReader isr = new InputStreamReader(is);
            reader = new BufferedReader(isr);
            executeSQLScript(db, reader);
        } catch (IOException e) {
            Log.e(TAG, "IOException:", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(TAG, "IOException:", e);
                }
            }
        }

    }

    private void executeSQLScript(SQLiteDatabase db, BufferedReader reader) throws IOException {
        String line;
        StringBuilder statement = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            statement.append(line);
            statement.append("\n");
            if (line.endsWith(";")) {
                db.execSQL(statement.toString());
                statement = new StringBuilder();
            }
        }
    }
}

An example project is provided in the same link also : https://github.com/riggaroo/AndroidDatabaseUpgrades

Creating a new user and password with Ansible

The task definition for the user module should be different in the latest Ansible version.

tasks:
  - user: name=test password={{ password }} state=present

Delete file from internal storage

This is an old topic, but I will add my experience, maybe someone finds this helpful

>     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created

2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it

solution1:

              Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri

here I initialize Content resolver and delete it with a passed parameter of that URI

            ContentResolver contentResolver = getContentResolver ();
            contentResolver.delete (uriDelete,null ,null );

solution2(my first solution-from head in this time I do know that ): content resolver exists...

              String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                    adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);

            File file = new File (path);
            if (file != null) {
                file.delete ();
            }

Hope that this will be helpful to someone happy coding

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

It worked: Project Properties -> ProjectFacets -> Runtimes -> jdk1.8.0_45 -> Apply

Difference between OData and REST web services

UPDATE Warning, this answer is extremely out of date now that OData V4 is available.


I wrote a post on the subject a while ago here.

As Franci said, OData is based on Atom Pub. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process.

The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response. It is what REST people call out-of-band information and introduces hidden coupling between the client and server.

The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. This metadata can be discovered at a fixed endpoint called $metadata. Again, the client needs to know this in advance, it cannot be discovered.

Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

How I can delete in VIM all text from current line to end of file?

Go to the first line from which you would like to delete, and press the keys dG

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

Replace and overwrite instead of appending

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
    f.truncate()

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

Are string.Equals() and == operator really same?

An object is defined by an OBJECT_ID, which is unique. If A and B are objects and A == B is true, then they are the very same object, they have the same data and methods, but, this is also true:

A.OBJECT_ID == B.OBJECT_ID

if A.Equals(B) is true, that means that the two objects are in the same state, but this doesn't mean that A is the very same as B.

Strings are objects.

Note that the == and Equals operators are reflexive, simetric, tranzitive, so they are equivalentic relations (to use relational algebraic terms)

What this means: If A, B and C are objects, then:

(1) A == A is always true; A.Equals(A) is always true (reflexivity)

(2) if A == B then B == A; If A.Equals(B) then B.Equals(A) (simetry)

(3) if A == B and B == C, then A == C; if A.Equals(B) and B.Equals(C) then A.Equals(C) (tranzitivity)

Also, you can note that this is also true:

(A == B) => (A.Equals(B)), but the inverse is not true.

A B =>
0 0 1
0 1 1
1 0 0
1 1 1

Example of real life: Two Hamburgers of the same type have the same properties: they are objects of the Hamburger class, their properties are exactly the same, but they are different entities. If you buy these two Hamburgers and eat one, the other one won't be eaten. So, the difference between Equals and ==: You have hamburger1 and hamburger2. They are exactly in the same state (the same weight, the same temperature, the same taste), so hamburger1.Equals(hamburger2) is true. But hamburger1 == hamburger2 is false, because if the state of hamburger1 changes, the state of hamburger2 not necessarily change and vice versa.

If you and a friend get a Hamburger, which is yours and his in the same time, then you must decide to split the Hamburger into two parts, because you.getHamburger() == friend.getHamburger() is true and if this happens: friend.eatHamburger(), then your Hamburger will be eaten too.

I could write other nuances about Equals and ==, but I'm getting hungry, so I have to go.

Best regards, Lajos Arpad.

What is the $$hashKey added to my JSON.stringify result

If you are using Angular 1.3 or above, I recommend that you use "track by" in your ng-repeat. Angular doesn't add a "$$hashKey" property to the objects in your array if you use "track by". You also get performance benefits, if something in your array changes, angular doesn't recreate the entire DOM structure for your ng-repeat, it instead recreates the part of the DOM for the values in your array that have changed.

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

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

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

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

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

Solution to "subquery returns more than 1 row" error

You can use in():

select * 
from table
where id in (multiple row query)

or use a join:

select distinct t.* 
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>

The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.

Uninstall mongoDB from ubuntu

use sudo with the command:

sudo apt-get remove --purge mongodb  
apt-get autoremove --purge mongodb  

Get error message if ModelState.IsValid fails?

Try

ModelState.Values.First().Errors[0].ErrorMessage

htaccess - How to force the client's browser to clear the cache?

This worked for me.

look for this:

    DirectoryIndex index.php

replace with this:

    DirectoryIndex something.php index.php

Upload and refresh page. You will get a page error.

just change it back to:

    DirectoryIndex index.php

reupload and refresh page again.
I checked this on all of my devices and, it worked.

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

TypeError: got multiple values for argument

My issue was similar to Q---ten's, but in my case it was that I had forgotten to provide the self argument to a class function:

class A:
    def fn(a, b, c=True):
        pass

Should become

class A:
    def fn(self, a, b, c=True):
        pass

This faulty implementation is hard to see when calling the class method as:

a_obj = A()
a.fn(a_val, b_val, c=False)

Which will yield a TypeError: got multiple values for argument. Hopefully, the rest of the answers here are clear enough for anyone to be able to quickly understand and fix the error. If not, hope this answer helps you!

Display milliseconds in Excel

I did this in Excel 2000.

This statement should be: ms = Round(temp - Int(temp), 3) * 1000

You need to create a custom format for the result cell of [h]:mm:ss.000

How can you detect the version of a browser?

This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:

  • Maintains original answer's minimal code. (K)
  • Works with Microsoft Edge (K)
  • Extends the navigator object instead of creating a new variable/object. (K)
  • Separates browser version and name into independent child objects. (H)

 

navigator.browserSpecs = (function(){
    var ua = navigator.userAgent, tem, 
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return {name:'IE',version:(tem[1] || '')};
    }
    if(M[1]=== 'Chrome'){
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
    }
    M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i))!= null)
        M.splice(1, 1, tem[1]);
    return {name:M[0], version:M[1]};
})();

console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }

if (navigator.browserSpecs.name == 'Firefox') {
    // Do something for Firefox.
    if (navigator.browserSpecs.version > 42) {
        // Do something for Firefox versions greater than 42.
    }
}
else {
    // Do something for all other browsers.
}

How to debug ORA-01775: looping chain of synonyms?

If you are compiling a PROCEDURE, possibly this is referring to a table or view that does not exist as it is created in the same PROCEDURE. In this case the solution is to make the query declared as String eg v_query: = 'insert into table select * from table2 and then execute immediate on v_query;

This is because the compiler does not yet recognize the object and therefore does not find the reference. Greetings.

How to set the first option on a select box using jQuery?

You can try this:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
        $( this ).change();
    }
} );

ExecuteNonQuery doesn't return results

If what you want is to get just a single integer from the query, use:

myCmdObject.ExecuteScalar()

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

How to run only one task in ansible playbook?

This can be easily done using the tags

The example of tags is defined below:

---
hosts: localhost
tasks:
 - name: Creating s3Bucket
   s3_bucket:
        name: ansiblebucket1234567890
   tags: 
       - createbucket

 - name: Simple PUT operation
   aws_s3:
       bucket: ansiblebucket1234567890
       object: /my/desired/key.txt
       src: /etc/ansible/myfile.txt
       mode: put
   tags:
      - putfile

 - name: Create an empty bucket
   aws_s3:
       bucket: ansiblebucket12345678901234
       mode: create
       permission: private
   tags:
       - emptybucket

to execute the tags we use the command

ansible-playbook creates3bucket.yml --tags "createbucket,putfile"

How to take input in an array + PYTHON?

arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

MongoDB: Is it possible to make a case-insensitive query?

For any one using Golang and wishes to have case sensitive full text search with mongodb and the mgo godoc globalsign library.

collation := &mgo.Collation{
    Locale:   "en",
    Strength: 2, 
}


err := collection.Find(query).Collation(collation)

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

For SQL2008,

  • open Management Studio
  • Rt click on instance
  • go to properties
  • select Security
  • Under Server Authentication, check SQL Server and Windows Authentication Mode
  • hit OK

Restart the server using configuration manager.

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Laravel Migration Change to Make a Column Nullable

If you happens to change the columns and stumbled on

'Doctrine\DBAL\Driver\PDOMySql\Driver' not found

then just install

composer require doctrine/dbal

Numbering rows within groups in a data frame

Use ave, ddply, dplyr or data.table:

df$num <- ave(df$val, df$cat, FUN = seq_along)

or:

library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))

or:

library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())

or (the most memory efficient, as it assigns by reference within DT):

library(data.table)
DT <- data.table(df)

DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]

How do I solve this error, "error while trying to deserialize parameter"

This is happening because the web-service relies on using XmlSerializer to convert the wsdl among other things to XML, which doesn't support mixed-mode properties, like these:

public string strThing { get; private set; }

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

More information: http://www.geekscrapbook.com/2010/03/06/serializing-data-with-system-runtime-serialization-datacontractserializer/

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

Issue with background color and Google Chrome

Google Chrome and safari needs a tweak for body and background issues. We have use additional identifier as mentioned below.

<style>
body { background:#204960 url(../images/example.gif) repeat-x top; margin:0; padding:0; font-family:Tahoma; font-size:12px; }

#body{ background:#204960 url(../images/example.gif) repeat-x top; margin:0; padding:0; font-family:Tahoma; font-size:12px;}
</style>    
<body id="body">

Use both body and #body identifier and enter same styles in both. Make the body tag with id attribute of body.

This works for me.

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

Dynamically Add C# Properties at Runtime

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

    var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
    foreach (var property in properties) {
        dynamicObject.Add(property.Key,property.Value);
    }

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

The default XML namespace of the project must be the MSBuild XML namespace

The projects you are trying to open are in the new .NET Core csproj format. This means you need to use Visual Studio 2017 which supports this new format.

For a little bit of history, initially .NET Core used project.json instead of *.csproj. However, after some considerable internal deliberation at Microsoft, they decided to go back to csproj but with a much cleaner and updated format. However, this new format is only supported in VS2017.

If you want to open the projects but don't want to wait until March 7th for the official VS2017 release, you could use Visual Studio Code instead.

How do I get a background location update every n minutes in my iOS application?

I used xs2bush's method of getting an interval (using timeIntervalSinceDate) and expanded on it a little bit. I wanted to make sure that I was getting the required accuracy that I needed and also that I was not running down the battery by keeping the gps radio on more than necessary.

I keep location running continuously with the following settings:

locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locationManager.distanceFilter = 5;

this is a relatively low drain on the battery. When I'm ready to get my next periodic location reading, I first check to see if the location is within my desired accuracy, if it is, I then use the location. If it's not, then I increase the accuracy with this:

locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 0;

get my location and then once I have the location I turn the accuracy back down again to minimize the drain on the battery. I have written a full working sample of this and also I have written the source for the server side code to collect the location data, store it to a database and allow users to view gps data in real time or retrieve and view previously stored routes. I have clients for iOS, android, windows phone and java me. All clients are natively written and they all work properly in the background. The project is MIT licensed.

The iOS project is targeted for iOS 6 using a base SDK of iOS 7. You can get the code here.

Please file an issue on github if you see any problems with it. Thanks.

Generate random numbers with a given (numerical) distribution

(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)

pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
R = max(i for r in [random.random()] for i,c in cdf if c <= r)

I pseudo-confirmed that this works by eyeballing the output of this expression:

sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
       for _ in range(1000))

MySQL select one column DISTINCT, with corresponding other columns

Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.

So for example: select column1 from table group by column2 order by column3

That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases

select column1, column2, column3 from table group by column2 order by column3

Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.

Angularjs -> ng-click and ng-show to show a div

Just remove css from your js fiddle,use the myvaue === true.

<div ng-show="myvalue == true" class="ng-cloak">Here I am</div>

How to align entire html body to the center?

<style>
        body{
            max-width: 1180px;
            width: 98%;
            margin: 0px auto;
            text-align: left;
        }
</style>

Just apply this style before applying any CSS. You can change width as per your need.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I solved such a problem by replacing https part of my remote origin with http. It is also a workaround. I think it may help someone in the future.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I use href="#" for links that I want a dummy behaviour for. Then I use this code:

$(document).ready(function() {
    $("a[href='#']").click(function(event) {
        event.preventDefault();
    });
});

Meaning if the href equals to a hash (*="#") it prevents the default link behaviour, thus still allowing you to write functionality for it, and it doesn't affect anchor clicks.

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

CALL command vs. START with /WAIT option

This is what I found while running batch files in parallel (multiple instances of the same bat file at the same time with different input parameters) :

Lets say that you have an exe file that performs a long task called LongRunningTask.exe

If you call the exe directly from the bat file, only the first call to the LongRunningTask will succed, while the rest will get an OS error "File is already in use by the process"

If you use this command:

start /B /WAIT "" "LongRunningTask.exe" "parameters"

You will be able to run multiple instances of the bat and exe, while still waiting for the task to finish before the bat continues executing the remaining commands. The /B option is to avoid creating another window, the empty quotes are needed in order to the command to work, see the reference below.

Note that if you don´t use the /WAIT in the start, the LongRunningTask will be executed at the same time than the remaining commands in the batch file, so it might create problems if one of these commands requires the output of the LongRunningTask

Resuming :

This can´t run in parallel :

  • call LongRunningTask.exe

This will run in parallel and will be ok as far as there are no data dependencies between the output of the command and the rest of the bat file :

  • start /B "" "LongRunningTask.exe" "parameters"

This will run in parallel and wait for the task to finish, so you can use the output :

  • start /B /WAIT "" "LongRunningTask.exe" "parameters"

Reference for the start command : How can I run a program from a batch file without leaving the console open after the program start?

How to generate a random number in C++?

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ?0? and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand

How to get every first element in 2 dimensional list

You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a]
[4.0, 3.0, 3.5]

Also just to be pedantic, you don't have a list of list, you have a tuple of tuple.

Mean per group in a data.frame

You could also use the generic function cbind() and lm() without the intercept:

cbind(lm(d$Rate1~-1+d$Name)$coef,lm(d$Rate2~-1+d$Name)$coef)
>               [,1]     [,2]
>d$NameAira 16.33333 47.00000
>d$NameBen  31.33333 50.33333
>d$NameCat  44.66667 54.00000

CHECK constraint in MySQL is not working

CHECK constraints are ignored by MySQL as explained in a miniscule comment in the docs: CREATE TABLE

The CHECK clause is parsed but ignored by all storage engines.