Programs & Examples On #Form load

Android Completely transparent Status Bar?

All you need to do is set these properties in your theme:

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

Your activity / container layout you wish to have a transparent status bar needs this property set:

android:fitsSystemWindows="true"

It is generally not possible to perform this for sure on pre-kitkat, looks like you can do it but some strange code makes it so.

EDIT: I would recommend this lib: https://github.com/jgilfelt/SystemBarTint for lots of pre-lollipop status bar color control.

Well after much deliberation I've learned that the answer to totally disabling the translucency or any color placed on the status bar and navigation bar for lollipop is to set this flag on the window:

// In Activity's onCreate() for instance
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window w = getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}

No other theme-ing is necessary, it produces something like this:

enter image description here

Can I have onScrollListener for a ScrollView?

Beside accepted answer, you need to hold a reference of listener and remove when you don't need it. Otherwise you will get a null pointer exception for your ScrollView and memory leak (mentioned in comments of accepted answer).

  1. You can implement OnScrollChangedListener in your activity/fragment.

    MyFragment : ViewTreeObserver.OnScrollChangedListener
    
  2. Add it to scrollView when your view is ready.

    scrollView.viewTreeObserver.addOnScrollChangedListener(this)
    
  3. Remove listener when no longer need (ie. onPause())

    scrollView.viewTreeObserver.removeOnScrollChangedListener(this)
    

How do I make a column unique and index it in a Ruby on Rails migration?

If you have missed to add unique to DB column, just add this validation in model to check if the field is unique:

class Person < ActiveRecord::Base
  validates_uniqueness_of :user_name
end

refer here Above is for testing purpose only, please add index by changing DB column as suggested by @Nate

please refer this with index for more information

String split on new line, tab and some number of spaces

Just use .strip(), it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with data_string.splitlines():

[s.strip() for s in data_string.splitlines()]

Output:

>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Phone: 555-555-555', 'Other Home: Somewhere Else', 'Notes: Other data', 'Name: Jane Smith', 'Misc: Data with spaces']

You can even inline the splitting on : as well now:

>>> [s.strip().split(': ') for s in data_string.splitlines()]
[['Name', 'John Smith'], ['Home', 'Anytown USA'], ['Phone', '555-555-555'], ['Other Home', 'Somewhere Else'], ['Notes', 'Other data'], ['Name', 'Jane Smith'], ['Misc', 'Data with spaces']]

How do you set the document title in React?

In React 16.13, you can set it directly inside the render function:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

For function component:

function App() {
    document.title = 'wow'
    return <p>Hello</p>
}

Find multiple files and rename them in Linux

For renaming recursively I use the following commands:

find -iname \*.* | rename -v "s/ /-/g"

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

How to edit the size of the submit button on a form?

You can change height and width with css:

#search {
     height: 100px;
     width: 400px;
}

It's worth pointing out that safari on OSX ignores most input button styles, however.

How to read until EOF from cin in C++

You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.

#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>

int main()
{
// don't skip the whitespace while reading
  std::cin >> std::noskipws;

// use stream iterators to copy the stream to a string
  std::istream_iterator<char> it(std::cin);
  std::istream_iterator<char> end;
  std::string results(it, end);

  std::cout << results;
}

How can I uninstall Ruby on ubuntu?

At first find out where ruby is? then

rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem

Sort Array of object by object field in Angular 6

Try this

products.sort(function (a, b) {
  return a.title.rendered - b.title.rendered;
});

OR

You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.

Using underscore: (below one is just an example)

import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title'); 

R Markdown - changing font size and font type in html output

I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.

Add single element to array in numpy

If you want to add an element use append()

a = numpy.append(a, 1) in this case add the 1 at the end of the array

If you want to insert an element use insert()

a = numpy.insert(a, index, 1) in this case you can put the 1 where you desire, using index to set the position in the array.

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

There are different ways we can pass the Access-Control-Expose-Headers.

  • As jgauffin has explained we can create a new attribute.
  • As LaundroMatt has explained we can add in the web.config file.
  • Another way is we can add code as below in the webApiconfig.cs file.

    config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

Or we can add below code in the Global.Asax file.

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

I have written it for the options. Please modify the same as per your need.

Happy Coding !!

Bootstrap date time picker

Try This:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
  <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>_x000D_
  <script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
      <div class='col-sm-6'>_x000D_
        <div class="form-group">_x000D_
          <div class='input-group date' id='datetimepicker1'>_x000D_
            <input type='text' class="form-control" />_x000D_
            <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
            </span>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <script type="text/javascript">_x000D_
        $(function() {_x000D_
          $('#datetimepicker1').datetimepicker();_x000D_
        });_x000D_
      </script>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert row names into first column

Or by using DBIs sqlRownamesToColumn

library(DBI)
sqlRownamesToColumn(df)

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

Git pull - Please move or remove them before you can merge

Apparently the files were added in remote repository, no matter what was the content of .gitignore file in the origin.

As the files exist in the remote repository, git has to pull them to your local work tree as well and therefore complains that the files already exist.

.gitignore is used only for scanning for the newly added files, it doesn't have anything to do with the files which were already added.

So the solution is to remove the files in your work tree and pull the latest version. Or the long-term solution is to remove the files from the repository if they were added by mistake.

A simple example to remove files from the remote branch is to

$git checkout <brachWithFiles>
$git rm -r *.extension
$git commit -m "fixin...."
$git push

Then you can try the $git merge again

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

Disable PHP in directory (including all sub-directories) with .htaccess

If you use php-fpm, the php_admin_value will NOT work and gives an Internal Server Error.

Instead use this in your .htaccess. It disables the parser in that folder and all subfolders:

<FilesMatch ".+\.*$">
    SetHandler !
</FilesMatch>

Why is null an object and what's the difference between null and undefined?

  1. Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)

2.Undefined is a type itself while Null is an object.

3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.

How do I run a program with a different working directory from current, from Linux shell?

from the current directory provide the full path to the script directory to execute the command

/root/server/user/home/bin/script.sh

What is the best way to extract the first word from a string in Java?

import org.apache.commons.lang3.StringUtils;

...
StringUtils.substringBefore("Grigory Kislin", " ")

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

Vim clear last search highlighting

From http://twitter.com/jonbho/status/2194406821

" Clear highlighting on escape in normal mode
nnoremap <esc> :noh<return><esc>
nnoremap <esc>^[ <esc>^[

The second line is needed for mapping to the escape key since Vim internally uses escape to represent special keys.

Recyclerview and handling different type of row inflation

Handling the rows / sections logic similar to iOS's UITableView is not as simple in Android as it is in iOS, however, when you use RecyclerView - the flexibility of what you can do is far greater.

In the end, it's all about how you figure out what type of view you're displaying in the Adapter. Once you got that figured out, it should be easy sailing (not really, but at least you'll have that sorted).

The Adapter exposes two methods which you should override:

getItemViewType(int position)

This method's default implementation will always return 0, indicating that there is only 1 type of view. In your case, it is not so, and so you will need find a way to assert which row corresponds to which view type. Unlike iOS, which manages this for you with rows and sections, here you will have only one index to rely on, and you'll need to use your developer skills to know when a position correlates to a section header, and when it correlates to a normal row.

createViewHolder(ViewGroup parent, int viewType)

You need to override this method anyway, but usually people just ignore the viewType parameter. According to the view type, you'll need to inflate the correct layout resource and create your view holder accordingly. The RecyclerView will handle recycling different view types in a way which avoids clashing of different view types.

If you're planning on using a default LayoutManager, such as LinearLayoutManager, you should be good to go. If you're planning on making your own LayoutManager implementation, you'll need to work a bit harder. The only API you really have to work with is findViewByPosition(int position) which gives a given view at a certain position. Since you'll probably want to lay it out differently depending on what type this view is, you have a few options:

  1. Usually when using the ViewHolder pattern, you set the view's tag with the view holder. You could use this during runtime in the layout manager to find out what type the view is by adding a field in the view holder which expresses this.

  2. Since you'll need a function which determines which position correlates to which view type, you might as well make this method globally accessible somehow (maybe a singleton class which manages the data?), and then you can simply query the same method according to the position.

Here's a code sample:

// in this sample, I use an object array to simulate the data of the list. 
// I assume that if the object is a String, it means I should display a header with a basic title.
// If not, I assume it's a custom model object I created which I will use to bind my normal rows.
private Object[] myData;

public static final int ITEM_TYPE_NORMAL = 0;
public static final int ITEM_TYPE_HEADER = 1;

public class MyAdapter extends Adapter<ViewHolder> {

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == ITEM_TYPE_NORMAL) {
            View normalView = LayoutInflater.from(getContext()).inflate(R.layout.my_normal_row, null);
            return new MyNormalViewHolder(normalView); // view holder for normal items
        } else if (viewType == ITEM_TYPE_HEADER) {
            View headerRow = LayoutInflater.from(getContext()).inflate(R.layout.my_header_row, null);
            return new MyHeaderViewHolder(headerRow); // view holder for header items
        }
    }


    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        final int itemType = getItemViewType(position);

        if (itemType == ITEM_TYPE_NORMAL) {
            ((MyNormalViewHolder)holder).bindData((MyModel)myData[position]);
        } else if (itemType == ITEM_TYPE_HEADER) {
            ((MyHeaderViewHolder)holder).setHeaderText((String)myData[position]);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (myData[position] instanceof String) {
            return ITEM_TYPE_HEADER;
        } else {
            return ITEM_TYPE_NORMAL;
        }
    }

    @Override
    public int getItemCount() {
        return myData.length;
    }
}

Here's a sample of how these view holders should look like:

public MyHeaderViewHolder extends ViewHolder {

    private TextView headerLabel;    

    public MyHeaderViewHolder(View view) {
        super(view);

        headerLabel = (TextView)view.findViewById(R.id.headerLabel);
    }

    public void setHeaderText(String text) {
        headerLabel.setText(text);
    }    
}


public MyNormalViewHolder extends ViewHolder {

    private TextView titleLabel;
    private TextView descriptionLabel;    

    public MyNormalViewHolder(View view) {
        super(view);

        titleLabel = (TextView)view.findViewById(R.id.titleLabel);
        descriptionLabel = (TextView)view.findViewById(R.id.descriptionLabel);
    }

    public void bindData(MyModel model) {
        titleLabel.setText(model.getTitle());
        descriptionLabel.setText(model.getDescription());
    }    
}

Of course, this sample assumes you've constructed your data source (myData) in a way that makes it easy to implement an adapter in this way. As an example, I'll show you how I'd construct a data source which shows a list of names, and a header for every time the 1st letter of the name changes (assume the list is alphabetized) - similar to how a contacts list would look like:

// Assume names & descriptions are non-null and have the same length.
// Assume names are alphabetized
private void processDataSource(String[] names, String[] descriptions) {
    String nextFirstLetter = "";
    String currentFirstLetter;

    List<Object> data = new ArrayList<Object>();

    for (int i = 0; i < names.length; i++) {
        currentFirstLetter = names[i].substring(0, 1); // get the 1st letter of the name

        // if the first letter of this name is different from the last one, add a header row
        if (!currentFirstLetter.equals(nextFirstLetter)) {
            nextFirstLetter = currentFirstLetter;
            data.add(nextFirstLetter);
        }

        data.add(new MyModel(names[i], descriptions[i]));
    }

    myData = data.toArray();
}

This example comes to solve a fairly specific issue, but I hope this gives you a good overview on how to handle different row types in a recycler, and allows you make the necessary adaptations in your own code to fit your needs.

Why can't Python parse this JSON data?

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

Android Studio : unmappable character for encoding UTF-8

I had the same problem because there was files with windows-1251 encoding and Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it in two ways:

a) convert file encoding to UTF-8 or

b) set the right file encoding in your build.gradle script:

android {
    ...
    compileOptions.encoding = 'windows-1251' // write your encoding here
    ...

To convert file encoding use the menu at the bottom right corner of IDE. Select right file encoding first -> press Reload -> select UTF-8 -> press Convert.

Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

Align Div at bottom on main Div

I guess you'll need absolute position

.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}

CronJob not running

WTF?! My cronjob doesn't run?!

Here's a checklist guide to debug not running cronjobs:

  1. Is the Cron daemon running?
  • Run ps ax | grep cron and look for cron.
  • Debian: service cron start or service cron restart
  1. Is cron working?
  • * * * * * /bin/echo "cron works" >> /tmp/file
  • Syntax correct? See below.
  • You obviously need to have write access to the file you are redirecting the output to. A unique file name in /tmp which does not currently exist should always be writable.
  • Probably also add 2>&1 to include standard error as well as standard output, or separately output standard error to another file with 2>>/tmp/errors
  1. Is the command working standalone?
  • Check if the script has an error, by doing a dry run on the CLI
  • When testing your command, test as the user whose crontab you are editing, which might not be your login or root
  1. Can cron run your job?
  • Check /var/log/cron.log or /var/log/messages for errors.
  • Ubuntu: grep CRON /var/log/syslog
  • Redhat: /var/log/cron
  1. Check permissions
  • Set executable flag on the command: chmod +x /var/www/app/cron/do-stuff.php
  • If you redirect the output of your command to a file, verify you have permission to write to that file/directory
  1. Check paths
  • check she-bangs / hashbangs line
  • do not rely on environment variables like PATH, as their value will likely not be the same under cron as under an interactive session
  1. Don't suppress output while debugging
  • Commonly used is this suppression: 30 1 * * * command > /dev/null 2>&1
  • Re-enable the standard output or standard error message output by removing >/dev/null 2>&1 altogether; or perhaps redirect to a file in a location where you have write access: >>cron.out 2>&1 will append standard output and standard error to cron.out in the invoking user's home directory.
  • If you are trying to figure out why something failed, the error messages will be visible in this file. Read it and understand it.

Still not working? Yikes!

  1. Raise the cron debug level
  • Debian
    • in /etc/default/cron
    • set EXTRA_OPTS="-L 2"
    • service cron restart
    • tail -f /var/log/syslog to see the scripts executed
  • Ubuntu
    • in /etc/rsyslog.d/50-default.conf
    • add or comment out line cron.crit /var/log/cron.log
    • reload logger sudo /etc/init.d/rsyslog reload
    • re-run cron
    • open /var/log/cron.log and look for detailed error output
  • Reminder: deactivate log level, when you are done with debugging
  1. Run cron and check log files again

Cronjob Syntax

# Minute  Hour  Day of Month      Month         Day of Week    User Command    
# (0-59) (0-23)   (1-31)    (1-12 or Jan-Dec) (0-6 or Sun-Sat)  
         
    0       2       *             *                *          root /usr/bin/find

This syntax is only correct for the root user. Regular user crontab syntax doesn't have the User field (regular users aren't allowed to run code as any other user);

# Minute  Hour  Day of Month      Month         Day of Week    Command    
# (0-59) (0-23)   (1-31)    (1-12 or Jan-Dec) (0-6 or Sun-Sat)  
         
    0       2       *             *                *          /usr/bin/find

Crontab Commands

  1. crontab -l
    • Lists all the user's cron tasks.
  2. crontab -e, for a specific user: crontab -e -u agentsmith
    • Starts edit session of your crontab file.
    • When you exit the editor, the modified crontab is installed automatically.
  3. crontab -r
    • Removes your crontab entry from the cron spooler, but not from crontab file.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

var date=/^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{1,4}$/;

if(!date.test(form.date.value))

alert("Enter correct date");

else
alert(" working");

How can I dynamically add a directive in AngularJS?

Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

Important: Register the directives that you want to use with restrict: 'C'. Like this:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

You can use like this:

<stroman class="my-directive other-class" randomProperty="8"></stroman>

To get this:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. If you don't want to use directives based on classes then you can change '<div></div>' to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class.

Node.js on multi-core machines

Node Js is supporting clustering to take full advantages of your cpu. If you are not not running it with cluster, then probably you are wasting your hardware capabilities.

Clustering in Node.js allows you to create separate processes which can share same server port. For example, if we run one HTTP server on Port 3000, it is one Server running on Single thread on single core of processor.

Code shown below allow you to cluster your application. This code is official code represented by Node.js.

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    Object.keys(cluster.workers).forEach(function(id) {
        console.log("I am running with ID : " + cluster.workers[id].process.pid);
    });

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {

    //Do further processing.
}

check this article for the full tutorial

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

Format the date using Ruby on Rails

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

Remove old Fragment from fragment manager

Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

ArrayList<Fragment> fragmentList = fragmentManager.getFragments();

The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);

You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

I usually use this code for working with fragmentManager

public void replaceFragment(Fragment fragment, Bundle bundle) {

    if (bundle != null)
        fragment.setArguments(bundle);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

    //if oldFragment already exits in fragmentManager use it
    if (oldFragment != null) {
        fragment = oldFragment;
    }

    fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

    fragmentTransaction.commit();
}

When use getOne and findOne methods Spring Data JPA

The getOne methods returns only the reference from DB (lazy loading). So basically you are outside the transaction (the Transactional you have been declare in service class is not considered), and the error occur.

What is the default Precision and Scale for a Number in Oracle?

The NUMBER type can be specified in different styles:

                Resulting  Resulting  Precision
Specification   Precision  Scale      Check      Comment
-------------------------------------------------------------------------------
NUMBER          NULL       NULL       NO         'maximum range and precision',
                                                 values are stored 'as given'
NUMBER(P, S)    P          S          YES        Error code: ORA-01438
NUMBER(P)       P          0          YES        Error code: ORA-01438
NUMBER(*, S)    38         S          NO

Where the precision is the total number of digits and scale is the number of digits right or left (negative scale) of the decimal point.

Oracle specifies ORA-01438 as

value larger than specified precision allowed for this column

As noted in the table, this integrity check is only active if the precision is explicitly specified. Otherwise Oracle silently rounds the inserted or updated value using some unspecified method.

Lambda function in list comprehensions

People gave good answers but forgot to mention the most important part in my opinion: In the second example the X of the list comprehension is NOT the same as the X of the lambda function, they are totally unrelated. So the second example is actually the same as:

[Lambda X: X*X for I in range(10)]

The internal iterations on range(10) are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).

On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]

HTTP 415 unsupported media type error when calling Web API 2 endpoint

In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto) to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto) and its working.

Writing a string to a cell in excel

I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:

Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"

Does this fail as well?

Looks like you tried something similar:

'Worksheets("Game").Range("A1") = "Asdf"

However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.

Bootstrap 3: Keep selected tab on page refresh

Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

and here is the code for bootstrap tabs:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

here are quick codes for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Now let's come to the explanation:

The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.

Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/

I wish my answer could help you all.. Cheerio! :)

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

How to detect the physical connected state of a network cable/connector?

Use 'ip monitor' to get REAL TIME link state changes.

Logging in Scala

After using slf4s and logula for a while, I wrote loglady, a simple logging trait wrapping slf4j.

It offers an API similar to that of Python's logging library, which makes the common cases (basic string, simple formatting) trivial and avoids formatting boilerplate.

http://github.com/dln/loglady/

how to call a variable in code behind to aspx page

You can access a public/protected property using the data binding expression <%# myproperty %> as given below:

    <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>

you should call DataBind method, otherwise it can't be evaluated.

    public partial class WebForm1 : System.Web.UI.Page
    {
     public string CodeBehindVarPublic { get; set; }
      protected void Page_Load(object sender, EventArgs e)
        {
          CodeBehindVarPublic ="xyz";
       //you should call the next line  in case of using <%#CodeBehindVarPublic %>

          DataBind();
        }

}

How to serve up images in Angular2?

I am using the Asp.Net Core angular template project with an Angular 4 front end and webpack. I had to use '/dist/assets/images/' in front of the image name, and store the image in the assets/images directory in the dist directory. eg:

 <img  class="img-responsive" src="/dist/assets/images/UnitBadge.jpg">

JDBC connection failed, error: TCP/IP connection to host failed

Easy Solution

Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box

Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.

enter image description here

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Try using TempData:

public ActionResult Create(FormCollection collection) {
  ...
  TempData["notice"] = "Successfully registered";
  return RedirectToAction("Index");
  ...
}

Then, in your Index view, or master page, etc., you can do this:

<% if (TempData["notice"] != null) { %>
  <p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>

Or, in a Razor view:

@if (TempData["notice"] != null) {
  <p>@TempData["notice"]</p>
}

Quote from MSDN (page no longer exists as of 2014, archived copy here):

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.

Mocking static methods with Mockito

To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.

You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

How do I separate an integer into separate digits in an array in JavaScript?

Suppose,

let a = 123456

First we will convert it into string and then apply split to convert it into array of characters and then map over it to convert the array to integer.

let b = a.toString().split('').map(val=>parseInt(val))
console.log(b)

Check whether a path is valid in Python without creating a file at the path's target

tl;dr

Call the is_path_exists_or_creatable() function defined below.

Strictly Python 3. That's just how we roll.

A Tale of Two Questions

The question of "How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?" is clearly two separate questions. Both are interesting, and neither have received a genuinely satisfactory answer here... or, well, anywhere that I could grep.

vikki's answer probably hews the closest, but has the remarkable disadvantages of:

  • Needlessly opening (...and then failing to reliably close) file handles.
  • Needlessly writing (...and then failing to reliable close or delete) 0-byte files.
  • Ignoring OS-specific errors differentiating between non-ignorable invalid pathnames and ignorable filesystem issues. Unsurprisingly, this is critical under Windows. (See below.)
  • Ignoring race conditions resulting from external processes concurrently (re)moving parent directories of the pathname to be tested. (See below.)
  • Ignoring connection timeouts resulting from this pathname residing on stale, slow, or otherwise temporarily inaccessible filesystems. This could expose public-facing services to potential DoS-driven attacks. (See below.)

We're gonna fix all that.

Question #0: What's Pathname Validity Again?

Before hurling our fragile meat suits into the python-riddled moshpits of pain, we should probably define what we mean by "pathname validity." What defines validity, exactly?

By "pathname validity," we mean the syntactic correctness of a pathname with respect to the root filesystem of the current system – regardless of whether that path or parent directories thereof physically exist. A pathname is syntactically correct under this definition if it complies with all syntactic requirements of the root filesystem.

By "root filesystem," we mean:

  • On POSIX-compatible systems, the filesystem mounted to the root directory (/).
  • On Windows, the filesystem mounted to %HOMEDRIVE%, the colon-suffixed drive letter containing the current Windows installation (typically but not necessarily C:).

The meaning of "syntactic correctness," in turn, depends on the type of root filesystem. For ext4 (and most but not all POSIX-compatible) filesystems, a pathname is syntactically correct if and only if that pathname:

  • Contains no null bytes (i.e., \x00 in Python). This is a hard requirement for all POSIX-compatible filesystems.
  • Contains no path components longer than 255 bytes (e.g., 'a'*256 in Python). A path component is a longest substring of a pathname containing no / character (e.g., bergtatt, ind, i, and fjeldkamrene in the pathname /bergtatt/ind/i/fjeldkamrene).

Syntactic correctness. Root filesystem. That's it.

Question #1: How Now Shall We Do Pathname Validity?

Validating pathnames in Python is surprisingly non-intuitive. I'm in firm agreement with Fake Name here: the official os.path package should provide an out-of-the-box solution for this. For unknown (and probably uncompelling) reasons, it doesn't. Fortunately, unrolling your own ad-hoc solution isn't that gut-wrenching...

O.K., it actually is. It's hairy; it's nasty; it probably chortles as it burbles and giggles as it glows. But what you gonna do? Nuthin'.

We'll soon descend into the radioactive abyss of low-level code. But first, let's talk high-level shop. The standard os.stat() and os.lstat() functions raise the following exceptions when passed invalid pathnames:

  • For pathnames residing in non-existing directories, instances of FileNotFoundError.
  • For pathnames residing in existing directories:
    • Under Windows, instances of WindowsError whose winerror attribute is 123 (i.e., ERROR_INVALID_NAME).
    • Under all other OSes:
    • For pathnames containing null bytes (i.e., '\x00'), instances of TypeError.
    • For pathnames containing path components longer than 255 bytes, instances of OSError whose errcode attribute is:
      • Under SunOS and the *BSD family of OSes, errno.ERANGE. (This appears to be an OS-level bug, otherwise referred to as "selective interpretation" of the POSIX standard.)
      • Under all other OSes, errno.ENAMETOOLONG.

Crucially, this implies that only pathnames residing in existing directories are validatable. The os.stat() and os.lstat() functions raise generic FileNotFoundError exceptions when passed pathnames residing in non-existing directories, regardless of whether those pathnames are invalid or not. Directory existence takes precedence over pathname invalidity.

Does this mean that pathnames residing in non-existing directories are not validatable? Yes – unless we modify those pathnames to reside in existing directories. Is that even safely feasible, however? Shouldn't modifying a pathname prevent us from validating the original pathname?

To answer this question, recall from above that syntactically correct pathnames on the ext4 filesystem contain no path components (A) containing null bytes or (B) over 255 bytes in length. Hence, an ext4 pathname is valid if and only if all path components in that pathname are valid. This is true of most real-world filesystems of interest.

Does that pedantic insight actually help us? Yes. It reduces the larger problem of validating the full pathname in one fell swoop to the smaller problem of only validating all path components in that pathname. Any arbitrary pathname is validatable (regardless of whether that pathname resides in an existing directory or not) in a cross-platform manner by following the following algorithm:

  1. Split that pathname into path components (e.g., the pathname /troldskog/faren/vild into the list ['', 'troldskog', 'faren', 'vild']).
  2. For each such component:
    1. Join the pathname of a directory guaranteed to exist with that component into a new temporary pathname (e.g., /troldskog) .
    2. Pass that pathname to os.stat() or os.lstat(). If that pathname and hence that component is invalid, this call is guaranteed to raise an exception exposing the type of invalidity rather than a generic FileNotFoundError exception. Why? Because that pathname resides in an existing directory. (Circular logic is circular.)

Is there a directory guaranteed to exist? Yes, but typically only one: the topmost directory of the root filesystem (as defined above).

Passing pathnames residing in any other directory (and hence not guaranteed to exist) to os.stat() or os.lstat() invites race conditions, even if that directory was previously tested to exist. Why? Because external processes cannot be prevented from concurrently removing that directory after that test has been performed but before that pathname is passed to os.stat() or os.lstat(). Unleash the dogs of mind-fellating insanity!

There exists a substantial side benefit to the above approach as well: security. (Isn't that nice?) Specifically:

Front-facing applications validating arbitrary pathnames from untrusted sources by simply passing such pathnames to os.stat() or os.lstat() are susceptible to Denial of Service (DoS) attacks and other black-hat shenanigans. Malicious users may attempt to repeatedly validate pathnames residing on filesystems known to be stale or otherwise slow (e.g., NFS Samba shares); in that case, blindly statting incoming pathnames is liable to either eventually fail with connection timeouts or consume more time and resources than your feeble capacity to withstand unemployment.

The above approach obviates this by only validating the path components of a pathname against the root directory of the root filesystem. (If even that's stale, slow, or inaccessible, you've got larger problems than pathname validation.)

Lost? Great. Let's begin. (Python 3 assumed. See "What Is Fragile Hope for 300, leycec?")

import errno, os

# Sadly, Python fails to provide the following magic number for us.
ERROR_INVALID_NAME = 123
'''
Windows-specific error code indicating an invalid pathname.

See Also
----------
https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
    Official listing of all such codes.
'''

def is_pathname_valid(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS;
    `False` otherwise.
    '''
    # If this pathname is either not a string or is but is empty, this pathname
    # is invalid.
    try:
        if not isinstance(pathname, str) or not pathname:
            return False

        # Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
        # if any. Since Windows prohibits path components from containing `:`
        # characters, failing to strip this `:`-suffixed prefix would
        # erroneously invalidate all valid absolute Windows pathnames.
        _, pathname = os.path.splitdrive(pathname)

        # Directory guaranteed to exist. If the current OS is Windows, this is
        # the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
        # environment variable); else, the typical root directory.
        root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
            if sys.platform == 'win32' else os.path.sep
        assert os.path.isdir(root_dirname)   # ...Murphy and her ironclad Law

        # Append a path separator to this directory if needed.
        root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep

        # Test whether each path component split from this pathname is valid or
        # not, ignoring non-existent and non-readable path components.
        for pathname_part in pathname.split(os.path.sep):
            try:
                os.lstat(root_dirname + pathname_part)
            # If an OS-specific exception is raised, its error code
            # indicates whether this pathname is valid or not. Unless this
            # is the case, this exception implies an ignorable kernel or
            # filesystem complaint (e.g., path not found or inaccessible).
            #
            # Only the following exceptions indicate invalid pathnames:
            #
            # * Instances of the Windows-specific "WindowsError" class
            #   defining the "winerror" attribute whose value is
            #   "ERROR_INVALID_NAME". Under Windows, "winerror" is more
            #   fine-grained and hence useful than the generic "errno"
            #   attribute. When a too-long pathname is passed, for example,
            #   "errno" is "ENOENT" (i.e., no such file or directory) rather
            #   than "ENAMETOOLONG" (i.e., file name too long).
            # * Instances of the cross-platform "OSError" class defining the
            #   generic "errno" attribute whose value is either:
            #   * Under most POSIX-compatible OSes, "ENAMETOOLONG".
            #   * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
            except OSError as exc:
                if hasattr(exc, 'winerror'):
                    if exc.winerror == ERROR_INVALID_NAME:
                        return False
                elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
                    return False
    # If a "TypeError" exception was raised, it almost certainly has the
    # error message "embedded NUL character" indicating an invalid pathname.
    except TypeError as exc:
        return False
    # If no exception was raised, all path components and hence this
    # pathname itself are valid. (Praise be to the curmudgeonly python.)
    else:
        return True
    # If any other exception was raised, this is an unrelated fatal issue
    # (e.g., a bug). Permit this exception to unwind the call stack.
    #
    # Did we mention this should be shipped with Python already?

Done. Don't squint at that code. (It bites.)

Question #2: Possibly Invalid Pathname Existence or Creatability, Eh?

Testing the existence or creatability of possibly invalid pathnames is, given the above solution, mostly trivial. The little key here is to call the previously defined function before testing the passed path:

def is_path_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create the passed
    pathname; `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()
    return os.access(dirname, os.W_OK)

def is_path_exists_or_creatable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS _and_
    either currently exists or is hypothetically creatable; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Done and done. Except not quite.

Question #3: Possibly Invalid Pathname Existence or Writability on Windows

There exists a caveat. Of course there does.

As the official os.access() documentation admits:

Note: I/O operations may fail even when os.access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

To no one's surprise, Windows is the usual suspect here. Thanks to extensive use of Access Control Lists (ACL) on NTFS filesystems, the simplistic POSIX permission-bit model maps poorly to the underlying Windows reality. While this (arguably) isn't Python's fault, it might nonetheless be of concern for Windows-compatible applications.

If this is you, a more robust alternative is wanted. If the passed path does not exist, we instead attempt to create a temporary file guaranteed to be immediately deleted in the parent directory of that path – a more portable (if expensive) test of creatability:

import os, tempfile

def is_path_sibling_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create **siblings**
    (i.e., arbitrary files in the parent directory) of the passed pathname;
    `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()

    try:
        # For safety, explicitly close and hence delete this temporary file
        # immediately after creating it in the passed path's parent directory.
        with tempfile.TemporaryFile(dir=dirname): pass
        return True
    # While the exact type of exception raised by the above function depends on
    # the current version of the Python interpreter, all such types subclass the
    # following exception superclass.
    except EnvironmentError:
        return False

def is_path_exists_or_creatable_portable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname on the current OS _and_
    either currently exists or is hypothetically creatable in a cross-platform
    manner optimized for POSIX-unfriendly filesystems; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_sibling_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Note, however, that even this may not be enough.

Thanks to User Access Control (UAC), the ever-inimicable Windows Vista and all subsequent iterations thereof blatantly lie about permissions pertaining to system directories. When non-Administrator users attempt to create files in either the canonical C:\Windows or C:\Windows\system32 directories, UAC superficially permits the user to do so while actually isolating all created files into a "Virtual Store" in that user's profile. (Who could have possibly imagined that deceiving users would have harmful long-term consequences?)

This is crazy. This is Windows.

Prove It

Dare we? It's time to test-drive the above tests.

Since NULL is the only character prohibited in pathnames on UNIX-oriented filesystems, let's leverage that to demonstrate the cold, hard truth – ignoring non-ignorable Windows shenanigans, which frankly bore and anger me in equal measure:

>>> print('"foo.bar" valid? ' + str(is_pathname_valid('foo.bar')))
"foo.bar" valid? True
>>> print('Null byte valid? ' + str(is_pathname_valid('\x00')))
Null byte valid? False
>>> print('Long path valid? ' + str(is_pathname_valid('a' * 256)))
Long path valid? False
>>> print('"/dev" exists or creatable? ' + str(is_path_exists_or_creatable('/dev')))
"/dev" exists or creatable? True
>>> print('"/dev/foo.bar" exists or creatable? ' + str(is_path_exists_or_creatable('/dev/foo.bar')))
"/dev/foo.bar" exists or creatable? False
>>> print('Null byte exists or creatable? ' + str(is_path_exists_or_creatable('\x00')))
Null byte exists or creatable? False

Beyond sanity. Beyond pain. You will find Python portability concerns.

How to fix Invalid AES key length?

You can verify the key length limit:

int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");

Change hover color on a button with Bootstrap customization

or can do this...
set all btn ( class name like : .btn- + $theme-colors: map-merge ) styles at one time :

@each $color, $value in $theme-colors {
  .btn-#{$color} {
    @include button-variant($value, $value,
    // modify
    $hover-background: lighten($value, 7.5%),
    $hover-border: lighten($value, 10%),
    $active-background: lighten($value, 10%),
    $active-border: lighten($value, 12.5%)
    // /modify
    );
  }
}

// code from "node_modules/bootstrap/scss/_buttons.scss"

should add into your customization scss file.

Rename Oracle Table or View

Past 10g the current answer no longer works for renaming views. The only method that still works is dropping and recreating the view. The best way I can think of to do this would be:

SELECT TEXT FROM ALL_VIEWS WHERE owner='some_schema' and VIEW_NAME='some_view';

Add this in front of the SQL returned

Create or replace view some_schema.new_view_name as ...

Drop the old view

Drop view some_schema.some_view;

Create a Date with a set timezone without using a string representation

The easiest way that I have found to get the correct date is using datejs.

http://www.datejs.com/

I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);

Console will read:

Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

https://jsfiddle.net/vp1ena7b/3/

The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

I thought that this might help someone...

Override element.style using CSS

you can override the style on your css by referencing the offending property of the element style. On my case these two codes are set as 15px and is causing my background image to go black. So, i override them with 0px and placed the !important so it will be priority

.content {
    border-bottom-left-radius: 0px !important;
     border-bottom-right-radius: 0px !important;
}

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

Python: Select subset from list based on index set

You could just use list comprehension:

property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]

or

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

The latter one is faster because there are fewer good_indices than the length of property_a, assuming good_indices are precomputed instead of generated on-the-fly.


Edit: The first option is equivalent to itertools.compress available since Python 2.7/3.1. See @Gary Kerr's answer.

property_asel = list(itertools.compress(property_a, good_objects))

Convert a character digit to the corresponding integer in C

Just use the atol()function:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    const char *c = "5";
    int d = atol(c);
    printf("%d\n", d);

}

no sqljdbc_auth in java.library.path

I've just encountered the same problem but within my own application. I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.

Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll to path.. which is easy to say:

PathHelper.appendToPath("C:\\sqljdbc_6.2\\enu\\auth\\x64");

once you know how to do it:

import java.lang.reflect.Field;

public class PathHelper {
    public static void appendToPath(String dir){

        String path = System.getProperty("java.library.path");
        path = dir + ";" + path;
        System.setProperty("java.library.path", path);

        try {

            final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
            sysPathsField.setAccessible(true);
            sysPathsField.set(null, null);

        }
        catch (Exception ex){
            throw new RuntimeException(ex);
        }

    }

}

Now integration authentication works like a charm :).

Credits to https://stackoverflow.com/a/21730111/1734640 for letting me figure this out.

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

Apache giving 403 forbidden errors

restorecon command works as below :

restorecon -v -R /var/www/html/

Can't create handler inside thread that has not called Looper.prepare()

Here is the solution for Kotlin using Coroutine:

Extend your class with CoroutineScope by MainScope():

class BootstrapActivity :  CoroutineScope by MainScope() {}

Then simply do this:

launch {
        // whatever you want to do in the main thread
    }

Don't forget to add the dependencies for coroutine:

org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutines}
org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlinCoroutines}

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

JQuery - Set Attribute value

"True" and "False" do not work, to disable, set to value disabled.

$('.someElement').attr('disabled', 'disabled');

To enable, remove.

$('.someElement').removeAttr('disabled');

Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.

You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.

Get docker container id from container name

Docker image inspect ImageName\ImageId --format={{'.ConatinerConfig.Hostname'}}

Iterate a list with indexes in Python

Here's another using the zip function.

>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]

TypeScript and field initializers

Here's a solution that:

  • doesn't force you to make all fields optional (unlike Partial<...>)
  • differentiates between class methods and fields of function type (unlike the OnlyData<...> solution)
  • provides a nice structure by defining a Params interface
  • doesn't need to repeat variable names & types more than once

The only drawback is that it looks more complicated at first.


// Define all fields here
interface PersonParams {
  id: string
  name?: string
  coolCallback: () => string
}

// extend the params interface with an interface that has
// the same class name as the target class
// (if you omit the Params interface, you will have to redeclare
// all variables in the Person class)
interface Person extends PersonParams { }

// merge the Person interface with Person class (no need to repeat params)
// person will have all fields of PersonParams
// (yes, this is valid TS)
class Person {
  constructor(params: PersonParams) {
    // could also do Object.assign(this, params);

    this.id = params.id;
    this.name = params.name;

    // intellisence will expect params
    // to have `coolCallback` but not `sayHello`
    this.coolCallback = params.coolCallback;
  }

  // compatible with functions
  sayHello() {
    console.log(`Hi ${this.name}!`);
  }
}

// you can only export on another line (not `export default class...`)
export default Person;

Java substring: 'string index out of range'

substring(0,38) means the String has to be 38 characters or longer. If not, the "String index is out of range".

T-SQL STOP or ABORT command in SQL Server

Here is a somewhat kludgy way to do it that works with GO-batches, by using a "global" variable.

if object_id('tempdb..#vars') is not null
begin
  drop table #vars
end

create table #vars (continueScript bit)
set nocount on
  insert #vars values (1)
set nocount off

-- Start of first batch
if ((select continueScript from #vars)=1) begin

  print '1'

  -- Conditionally terminate entire script
  if (1=1) begin
    set nocount on
      update #vars set continueScript=0
    set nocount off
    return
  end

end
go

-- Start of second batch
if ((select continueScript from #vars)=1) begin

  print '2'

end
go

And here is the same idea used with a transaction and a try/catch block for each GO-batch. You can try to change the various conditions and/or let it generate an error (divide by 0, see comments) to test how it behaves:

if object_id('tempdb..#vars') is not null
begin
  drop table #vars
end

create table #vars (continueScript bit)
set nocount on
  insert #vars values (1)
set nocount off

begin transaction;
  -- Batch 1 starts here
  if ((select continueScript from #vars)=1) begin
    begin try 
      print 'batch 1 starts'

      if (1=0) begin
        print 'Script is terminating because of special condition 1.'
        set nocount on
          update #vars set continueScript=0
        set nocount off
        return
      end

      print 'batch 1 in the middle of its progress'

      if (1=0) begin
        print 'Script is terminating because of special condition 2.'
        set nocount on
          update #vars set continueScript=0
        set nocount off
        return
      end

      set nocount on
        -- use 1/0 to generate an exception here
        select 1/1 as test
      set nocount off

    end try
    begin catch
      set nocount on
        select 
          error_number() as errornumber
          ,error_severity() as errorseverity
          ,error_state() as errorstate
          ,error_procedure() as errorprocedure
          ,error_line() as errorline
          ,error_message() as errormessage;
        print 'Script is terminating because of error.'
        update #vars set continueScript=0
      set nocount off
      return
    end catch;

  end
  go

  -- Batch 2 starts here
  if ((select continueScript from #vars)=1) begin

    begin try 
      print 'batch 2 starts'

      if (1=0) begin
        print 'Script is terminating because of special condition 1.'
        set nocount on
          update #vars set continueScript=0
        set nocount off
        return
      end

      print 'batch 2 in the middle of its progress'

      if (1=0) begin
        print 'Script is terminating because of special condition 2.'
        set nocount on
          update #vars set continueScript=0
        set nocount off
        return
      end

      set nocount on
        -- use 1/0 to generate an exception here
        select 1/1 as test
      set nocount off

    end try
    begin catch
      set nocount on
        select 
          error_number() as errornumber
          ,error_severity() as errorseverity
          ,error_state() as errorstate
          ,error_procedure() as errorprocedure
          ,error_line() as errorline
          ,error_message() as errormessage;
        print 'Script is terminating because of error.'
        update #vars set continueScript=0
      set nocount off
      return
    end catch;

  end
  go

if @@trancount > 0 begin
  if ((select continueScript from #vars)=1) begin
    commit transaction
    print 'transaction committed'
  end else begin
    rollback transaction;
    print 'transaction rolled back'
  end
end

What are these ^M's that keep showing up in my files in emacs?

Someone is not converting their line-ending characters correctly.

I assume it's the Windows folk as they love their CRLF. Unix loves LF and Mac loved CR until it was shown the Unix way.

What is so bad about singletons?

The problems with singletons is the issue of increased scope and therefore coupling. There is no denying that there are some of situations where you do need access to a single instance, and it can be accomplished other ways.

I now prefer to design around an inversion of control (IoC) container and allow the the lifetimes to be controlled by the container. This gives you the benefit of the classes that depend on the instance to be unaware of the fact that there is a single instance. The lifetime of the singleton can be changed in the future. Once such example I encountered recently was an easy adjustment from single threaded to multi-threaded.

FWIW, if it a PIA when you try to unit test it then it's going to PIA when you try to debug, bug fix or enhance it.

How do I use Assert to verify that an exception has been thrown?

Since you mention using other test classes, a better option than the ExpectedException attribute is to use Shoudly's Should.Throw.

Should.Throw<DivideByZeroException>(() => { MyDivideMethod(1, 0); });

Let's say we have a requirement that the customer must have an address to create an order. If not, the CreateOrderForCustomer method should result in an ArgumentException. Then we could write:

[TestMethod]
public void NullUserIdInConstructor()
{
  var customer = new Customer(name := "Justin", address := null};

  Should.Throw<ArgumentException>(() => {
    var order = CreateOrderForCustomer(customer) });
}

This is better than using an ExpectedException attribute because we are being specific about what should throw the error. This makes requirements in our tests clearer and also makes diagnosis easier when the test fails.

Note there is also a Should.ThrowAsync for asynchronous method testing.

get next sequence value from database using hibernate

Your idea with the SequenceGenerator fake entity is good.

@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
        @org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")

It is important to use the parameter with the key name "sequence_name". Run a debugging session on the hibernate class SequenceStyleGenerator, the configure(...) method at the line final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment ); to see more details about how the sequence name is computed by Hibernate. There are some defaults in there you could also use.

After the fake entity, I created a CrudRepository:

public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}

In the Junit, I call the save method of the SequenceRepository.

SequenceGenerator sequenceObject = new SequenceGenerator(); SequenceGenerator result = sequenceRepository.save(sequenceObject);

If there is a better way to do this (maybe support for a generator on any type of field instead of just Id), I would be more than happy to use it instead of this "trick".

Getting value of HTML text input

Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.

I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/

It has an alert which goes off on load and when you click the textbox itself.

How do you remove a specific revision in the git history?

Here is a way to remove non-interactively a specific <commit-id>, knowing only the <commit-id> you would like to remove:

git rebase --onto <commit-id>^ <commit-id> HEAD

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

HTML Agility pack - parsing tables

In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:

    List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
                                       from row in table?.SelectNodes(HtmlBody.TR)
                                       let rows = row.SelectSingleNode(HtmlBody.TR)
                                       where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
                                       select new TableRow
                                       {
                                           Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
                                           Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
                                       }  

TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:

_x000D_
_x000D_
<tr>_x000D_
    <td width="28%">&nbsp;</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

Executing Javascript from Python

quickjs should be the best option after quickjs come out. Just pip install quickjs and you are ready to go.

modify based on the example on README.

from quickjs import Function

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
escramble_758()
}
"""

escramble_758 = Function('escramble_758', js.replace("document.write", "return "))

print(escramble_758())

https://github.com/PetterS/quickjs

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

I have similar situation like you. I dont wannt sublime open editor for binary like jpg png files. Instead open system default application is more reasonable.

  1. create one Build. Just like the accepted answer. But it will both open default application and hex editor.
  2. Pulgin OpenDefaultApplication https://github.com/SublimeText/OpenDefaultApplication It will have context right click menu OpenInDefaultApplication. But It will both open default application and hex editor as well
  3. Pulgin: Non Text Files https://packagecontrol.io/packages/Non%20Text%20Files Add config in the user settting

    "binary_file_patterns": ["*.JPG","*.jpg", "*.jpeg", "*.png", "*.gif", "*.ttf", "*.tga", "*.dds", "*.ico", "*.eot", "*.pdf", "*.swf", "*.jar", "*.zip"],
    "prevent_bin_preview": true,
    "open_externally_patterns": [
       "*.JPG",
       "*.jpg",
       "*.jpeg",
       "*.JPEG",
       "*.png",
        "*.PGN",
       "*.gif",
        "*.GIF",
        "*.zip",
        "*.ZIP",
        "*.pdf",
        "*.PDF"
    ]
    

I choose the third way, it's quite sutiable for me. It will open jpg file in system default application and quickly close the edit mode automaically at the same time. As to the first two ways, you can set "preview_on_click": false, to stop openning automaticlly the hex editor compromisely.

AssertNull should be used or AssertNotNull

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Try Like this:

<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use DB;

    class UserController extends Controller
    {

    function  index(){

    $users = DB::table('users')->get();

    foreach ($users as $user)
    {
        var_dump($user->name);
    }

    }
  }

?>

How to click on hidden element in Selenium WebDriver?

I did it with jQuery:

page.execute_script %Q{ $('#some_id').prop('checked', true) }

How can I have Github on my own server?

There is GitHub Enterprise to satisfy your needs. And there is an open source "clone" of Github Enterprise.

PS: Now Github provides unlimited private repositories, bitbucket does the same. you can give a try to both. There are several other solutions as well.

Windows batch: formatted date into variable

If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:

FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C

I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.

SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%

While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.

CSS transition fade in

I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.

@mixin fade-in {
    opacity: 1;
    animation-name: fadeInOpacity;
    animation-iteration-count: 1;
    animation-timing-function: ease-in;
    animation-duration: 2s;
}

@keyframes fadeInOpacity {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

and if you don't want to use mixins, you can create a normal class .fade-in.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

Fixed Table Cell Width

table td 
{
  table-layout:fixed;
  width:20px;
  overflow:hidden;
  word-wrap:break-word;
}

Unable instantiate android.gms.maps.MapFragment

try this

http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject

I just added the project of google services and added a reference in my project property->Android

Getter and Setter?

Generally speaking, the first way is more popular overall because those with prior programming knowledge can easily transition to PHP and get work done in an object-oriented fashion. The first way is more universal. My advice would be to stick with what is tried and true across many languages. Then, when and if you use another language, you'll be ready to get something accomplished (instead of spending time reinventing the wheel).

How can I save an image with PIL?

The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as BMP.

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

Eclipse C++: Symbol 'std' could not be resolved

The problem you are reporting seems to me caused by the following:

  1. you are trying to compile C code and the source file has .cpp extension
  2. you are trying to compile C++ code and the source file has .c extension

In such situation Eclipse cannot recognize the proper compiler to use.

What is the best (idiomatic) way to check the type of a Python variable?

What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP.

def value_list(x):
    if isinstance(x, dict):
        return list(set(x.values()))
    elif isinstance(x, basestring):
        return [x]
    else:
        return None

How can I find the number of arguments of a Python function?

In:

import inspect 

class X:
    def xyz(self, a, b, c): 
        return 

print(len(inspect.getfullargspec(X.xyz).args))

Out:

4


Note: If xyz wasn't inside class X and had no "self" and just "a, b, c", then it would have printed 3.

For python below 3.5, you may want to replace inspect.getfullargspec by inspect.getargspec in the code above.

How to handle click event in Button Column in Datagridview?

In case someone is using C# (or see Note about VB.NET below) and has reached this point, but is still stuck, please read on.

Joshua's answer helped me, but not all the way. You will notice Peter asked "Where would you get the button from?", but was unanswered.

The only way it worked for me was to do one of the following to add my event hander (after setting my DataGridView's DataSource to my DataTable and after adding the DataGridViewButtonColumn to the DataGridView):

Either:

dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);

or:

dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);

And then add the handler method (either dataGridView1_CellClick or dataGridView1_CellContentClick) shown in the various answers above.

Note: VB.NET is different from C# in this respect, because we can simply add a Handles clause to our method's signature or issue an AddHandler statement as described in the Microsoft doc's "How to: Call an Event Handler in Visual Basic"

What is an .inc and why use it?

Generally means that its a file that needs to be included and does not make standalone script in itself.

This is a convention not a programming technique.

Although if your web server is not configured properly it could expose files with extensions like .inc.

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}

What is the meaning of "this" in Java?

this refers to the current object.

Each non-static method runs in the context of an object. So if you have a class like this:

public class MyThisTest {
  private int a;

  public MyThisTest() {
    this(42); // calls the other constructor
  }

  public MyThisTest(int a) {
    this.a = a; // assigns the value of the parameter a to the field of the same name
  }

  public void frobnicate() {
    int a = 1;

    System.out.println(a); // refers to the local variable a
    System.out.println(this.a); // refers to the field a
    System.out.println(this); // refers to this entire object
  }

  public String toString() {
    return "MyThisTest a=" + a; // refers to the field a
  }
}

Then calling frobnicate() on new MyThisTest() will print

1
42
MyThisTest a=42

So effectively you use it for multiple things:

  • clarify that you are talking about a field, when there's also something else with the same name as a field
  • refer to the current object as a whole
  • invoke other constructors of the current class in your constructor

How do I generate a SALT in Java for Salted-Hash?

Here's my solution, i would love anyone's opinion on this, it's simple for beginners

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Scanner;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Cryptography {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        byte[] bSalt = Salt();
        String strSalt = encoder.encodeToString(bSalt); // Byte to String
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

    private static byte[] Salt() {
        SecureRandom random = new SecureRandom();
        byte salt[] = new byte[6];
        random.nextBytes(salt);
        return salt;
    }

    private static byte[] Hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = factory.generateSecret(spec).getEncoded();
        return hash;
    }

}

You can validate by just decoding the strSalt and using the same hash method:

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        Decoder decoder = Base64.getUrlDecoder();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        String strSalt = "Your Salt String Here";
        byte[] bSalt = decoder.decode(strSalt); // String to Byte
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

Visual Studio Code cannot detect installed git

The only way I could get to work in my Windows 8.1 is the following: Add to system environment variables (not user variables):

c:\Users\USERNAME\AppData\Local\GitHub\PortableGit_YOURVERSION\bin\;c:\Users\USERNAME\AppData\Local\GitHub\PortableGit_YOURVERSION\libexec\git-core\;c:\Users\USERNAME\AppData\Local\GitHub\PortableGit_YOURVERSION\cmd\

This fixed the "it looks like git is not installed on your system" error on my Visual Studio Code.

How to concatenate two numbers in javascript?

You can now make use of ES6 template literals.

const numbersAsString = `${5}${6}`;
console.log(numbersAsString); // Outputs 56

Or, if you have variables:

const someNumber = 5;
const someOtherNumber = 6;
const numbersAsString = `${someNumber}${someOtherNumber}`;

console.log(numbersAsString); // Outputs 56

Personally I find the new syntax much clearer, albeit slightly more verbose.

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

Angular 4: How to include Bootstrap?

If you want to use bootstrap online and your application has access to the internet you can add

@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');

Into you'r main style.css file. and its the simplest way.

Reference : angular.io

Note. This solution loads bootstrap from unpkg website and it need to have internet access.

Moving up one directory in Python

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

Javascript Error Null is not an Object

I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.

This is what I would do

<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;

function setup() {
  myButton = document.getElementById("myButton");
  myTextfield = document.getElementById("myTextfield");
  myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);
    return false;
  }
}

function greetUser(userName) {
  var greeting = "Hello " + userName + "!";
  document.getElementsByTagName("h2")[0].innerHTML = greeting;
}

</script>
<body onload="setup()">
  <h2>Hello World!</h2>
  <p id="myParagraph">This is an example website</p>

  <form>
    <input type="text" id="myTextfield" placeholder="Type your name" />
    <input type="button" id="myButton" value="Go" />
  </form>
  </body>
</html>

have fun!

How to create JSON object using jQuery

How to get append input field value as json like

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

ALTER TABLE, set null in not null column, PostgreSQL 9.1

ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

jQuery - Fancybox: But I don't want scrollbars!

The answers here offer many ways to potentially fix this issue, but most will not work for devices with touchscreens. I think the source of the problem stems from these lines of code from the source:

if (type === 'iframe' && isTouch) {
    coming.scrolling = 'scroll';
}

This seems to override any options set by the fancybox initial configuration, and can only be changed after these lines of code have run, i.e. changing the css using the afterShow method. However, all such methods will cause a noticeable delay/lag and you will be able to see the scrollbars disappear as you open it.

My suggested fix is that you remove these lines from the main source file jquery.fancybox.js around line 880, because I don't see a reason to force scrollbars onto devices with touchscreens.

Note that this won't immediately make the scrollbars disappear, it simply stops it from overriding the scrolling configuration option. So you should also add scrolling: 'no' to your fancybox initial configuration.

Why does dividing two int not yield the right value when assigned to double?

The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.

How to lazy load images in ListView in Android

Picasso

Use Jake Wharton's Picasso Library. (A Perfect ImageLoading Library form the developer of ActionBarSherlock)

A powerful image downloading and caching library for Android.

Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Many common pitfalls of image loading on Android are handled automatically by Picasso:

Handling ImageView recycling and download cancellation in an adapter. Complex image transformations with minimal memory use. Automatic memory and disk caching.

Picasso Jake Wharton's Library

Glide

Glide is a fast and efficient open source media management framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.

Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. Glide includes a flexible api that allows developers to plug in to almost any network stack. By default Glide uses a custom HttpUrlConnection based stack, but also includes utility libraries plug in to Google's Volley project or Square's OkHttp library instead.

Glide.with(this).load("http://goo.gl/h8qOq7").into(imageView);

Glide's primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.

Glide Image Loading Library

Fresco by Facebook

Fresco is a powerful system for displaying images in Android applications.

Fresco takes care of image loading and display, so you don't have to. It will load images from the network, local storage, or local resources, and display a placeholder until the image has arrived. It has two levels of cache; one in memory and another in internal storage.

Fresco Github

In Android 4.x and lower, Fresco puts images in a special region of Android memory. This lets your application run faster - and suffer the dreaded OutOfMemoryError much less often.

Fresco Documentation

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

How to force reloading a page when using browser back button?

Since performance.navigation is now deprecated, you can try this:

var perfEntries = performance.getEntriesByType("navigation");

if (perfEntries[0].type === "back_forward") {
    location.reload(true);
}

Java/ JUnit - AssertTrue vs AssertFalse

Your first reaction to these methods is quite interesting to me. I will use it in future arguments that both assertTrue and assertFalse are not the most friendly tools. If you would use

assertThat(thisOrThat, is(false));

it is much more readable, and it prints a better error message too.

Prevent flicker on webkit-transition of webkit-transform

The solution is mentioned here: iPhone WebKit CSS animations cause flicker.

For your element, you need to set

-webkit-backface-visibility: hidden;

Docker compose, running containers in net:host

Just print

network_mode: "host"

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

For anyone who lands here and all the other solutions did not work give this a try. I am using typescript + react and my problem was that I was associating the files in vscode as javascriptreact not typescriptreact so check your settings for the following entries.

   "files.associations": {
    "*.tsx": "typescriptreact",
    "*.ts": "typescriptreact"
  },

SSIS Text was truncated with status value 4

If all other options have failed, trying recreating the data import task and/or the connection manager. If you've made any changes since the task was originally created, this can sometimes do the trick. I know it's the equivalent of rebooting, but, hey, if it works, it works.

How to parse the AndroidManifest.xml file inside an .apk package

This Java method, that runs on an Android, documents (what I've been able to interpret about) the binary format of the AndroidManifest.xml file in the .apk package. The second code box shows how to call decompressXML and how to load the byte[] from the app package file on the device. (There are fields whose purpose I don't understand, if you know what they mean, tell me, I'll update the info.)

// decompressXML -- Parse the 'compressed' binary form of Android XML docs 
// such as for AndroidManifest.xml in .apk files
public static int endDocTag = 0x00100101;
public static int startTag =  0x00100102;
public static int endTag =    0x00100103;
public void decompressXML(byte[] xml) {
// Compressed XML file/bytes starts with 24x bytes of data,
// 9 32 bit words in little endian order (LSB first):
//   0th word is 03 00 08 00
//   3rd word SEEMS TO BE:  Offset at then of StringTable
//   4th word is: Number of strings in string table
// WARNING: Sometime I indiscriminently display or refer to word in 
//   little endian storage format, or in integer format (ie MSB first).
int numbStrings = LEW(xml, 4*4);

// StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
// of the length/string data in the StringTable.
int sitOff = 0x24;  // Offset of start of StringIndexTable

// StringTable, each string is represented with a 16 bit little endian 
// character count, followed by that number of 16 bit (LE) (Unicode) chars.
int stOff = sitOff + numbStrings*4;  // StringTable follows StrIndexTable

// XMLTags, The XML tag tree starts after some unknown content after the
// StringTable.  There is some unknown data after the StringTable, scan
// forward from this point to the flag for the start of an XML start tag.
int xmlTagOff = LEW(xml, 3*4);  // Start from the offset in the 3rd word.
// Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
for (int ii=xmlTagOff; ii<xml.length-4; ii+=4) {
  if (LEW(xml, ii) == startTag) { 
    xmlTagOff = ii;  break;
  }
} // end of hack, scanning for start of first start tag

// XML tags and attributes:
// Every XML start and end tag consists of 6 32 bit words:
//   0th word: 02011000 for startTag and 03011000 for endTag 
//   1st word: a flag?, like 38000000
//   2nd word: Line of where this tag appeared in the original source file
//   3rd word: FFFFFFFF ??
//   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
//   5th word: StringIndex of Element Name
//   (Note: 01011000 in 0th word means end of XML document, endDocTag)

// Start tags (not end tags) contain 3 more words:
//   6th word: 14001400 meaning?? 
//   7th word: Number of Attributes that follow this tag(follow word 8th)
//   8th word: 00000000 meaning??

// Attributes consist of 5 words: 
//   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
//   1st word: StringIndex of Attribute Name
//   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
//   3rd word: Flags?
//   4th word: str ind of attr value again, or ResourceId of value

// TMP, dump string table to tr for debugging
//tr.addSelect("strings", null);
//for (int ii=0; ii<numbStrings; ii++) {
//  // Length of string starts at StringTable plus offset in StrIndTable
//  String str = compXmlString(xml, sitOff, stOff, ii);
//  tr.add(String.valueOf(ii), str);
//}
//tr.parent();

// Step through the XML tree element tags and attributes
int off = xmlTagOff;
int indent = 0;
int startTagLineNo = -2;
while (off < xml.length) {
  int tag0 = LEW(xml, off);
  //int tag1 = LEW(xml, off+1*4);
  int lineNo = LEW(xml, off+2*4);
  //int tag3 = LEW(xml, off+3*4);
  int nameNsSi = LEW(xml, off+4*4);
  int nameSi = LEW(xml, off+5*4);

  if (tag0 == startTag) { // XML START TAG
    int tag6 = LEW(xml, off+6*4);  // Expected to be 14001400
    int numbAttrs = LEW(xml, off+7*4);  // Number of Attributes to follow
    //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
    off += 9*4;  // Skip over 6+3 words of startTag data
    String name = compXmlString(xml, sitOff, stOff, nameSi);
    //tr.addSelect(name, null);
    startTagLineNo = lineNo;

    // Look for the Attributes
    StringBuffer sb = new StringBuffer();
    for (int ii=0; ii<numbAttrs; ii++) {
      int attrNameNsSi = LEW(xml, off);  // AttrName Namespace Str Ind, or FFFFFFFF
      int attrNameSi = LEW(xml, off+1*4);  // AttrName String Index
      int attrValueSi = LEW(xml, off+2*4); // AttrValue Str Ind, or FFFFFFFF
      int attrFlags = LEW(xml, off+3*4);  
      int attrResId = LEW(xml, off+4*4);  // AttrValue ResourceId or dup AttrValue StrInd
      off += 5*4;  // Skip over the 5 words of an attribute

      String attrName = compXmlString(xml, sitOff, stOff, attrNameSi);
      String attrValue = attrValueSi!=-1
        ? compXmlString(xml, sitOff, stOff, attrValueSi)
        : "resourceID 0x"+Integer.toHexString(attrResId);
      sb.append(" "+attrName+"=\""+attrValue+"\"");
      //tr.add(attrName, attrValue);
    }
    prtIndent(indent, "<"+name+sb+">");
    indent++;

  } else if (tag0 == endTag) { // XML END TAG
    indent--;
    off += 6*4;  // Skip over 6 words of endTag data
    String name = compXmlString(xml, sitOff, stOff, nameSi);
    prtIndent(indent, "</"+name+">  (line "+startTagLineNo+"-"+lineNo+")");
    //tr.parent();  // Step back up the NobTree

  } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
    break;

  } else {
    prt("  Unrecognized tag code '"+Integer.toHexString(tag0)
      +"' at offset "+off);
    break;
  }
} // end of while loop scanning tags and attributes of XML tree
prt("    end at offset "+off);
} // end of decompressXML


public String compXmlString(byte[] xml, int sitOff, int stOff, int strInd) {
  if (strInd < 0) return null;
  int strOff = stOff + LEW(xml, sitOff+strInd*4);
  return compXmlStringAt(xml, strOff);
}


public static String spaces = "                                             ";
public void prtIndent(int indent, String str) {
  prt(spaces.substring(0, Math.min(indent*2, spaces.length()))+str);
}


// compXmlStringAt -- Return the string stored in StringTable format at
// offset strOff.  This offset points to the 16 bit string length, which 
// is followed by that number of 16 bit (Unicode) chars.
public String compXmlStringAt(byte[] arr, int strOff) {
  int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
  byte[] chars = new byte[strLen];
  for (int ii=0; ii<strLen; ii++) {
    chars[ii] = arr[strOff+2+ii*2];
  }
  return new String(chars);  // Hack, just use 8 byte chars
} // end of compXmlStringAt


// LEW -- Return value of a Little Endian 32 bit word from the byte array
//   at offset off.
public int LEW(byte[] arr, int off) {
  return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
    | arr[off+1]<<8&0xff00 | arr[off]&0xFF;
} // end of LEW

This method reads the AndroidManifest into a byte[] for processing:

public void getIntents(String path) {
  try {
    JarFile jf = new JarFile(path);
    InputStream is = jf.getInputStream(jf.getEntry("AndroidManifest.xml"));
    byte[] xml = new byte[is.available()];
    int br = is.read(xml);
    //Tree tr = TrunkFactory.newTree();
    decompressXML(xml);
    //prt("XML\n"+tr.list());
  } catch (Exception ex) {
    console.log("getIntents, ex: "+ex);  ex.printStackTrace();
  }
} // end of getIntents

Most apps are stored in /system/app which is readable without root my Evo, other apps are in /data/app which I needed root to see. The 'path' argument above would be something like: "/system/app/Weather.apk"

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

How do I get the coordinate position after using jQuery drag and drop?

_x000D_
_x000D_
$(function() _x000D_
  {_x000D_
    $( "#element" ).draggable({ snap: ".ui-widget-header",grid: [ 1, 1 ]});_x000D_
  });_x000D_
    $(document).ready(function() {_x000D_
        $("#element").draggable({ _x000D_
                containment: '#snaptarget', _x000D_
                scroll: false_x000D_
         }).mousemove(function(){_x000D_
                var coord = $(this).position();_x000D_
                var width = $(this).width();_x000D_
               var height = $(this).height();_x000D_
                $("p.position").text( "(" + coord.left + "," + coord.top + ")" );_x000D_
                $("p.size").text( "(" + width + "," + height + ")" );_x000D_
         }).mouseup(function(){_x000D_
                var coord = $(this).position();_x000D_
                var width = $(this).width();_x000D_
                var height = $(this).height();_x000D_
                $.post('/test/layout_view.php', {x: coord.left, y: coord.top, w: width, h: height});_x000D_
               _x000D_
                });_x000D_
        });
_x000D_
#element {background:#666;border:1px #000 solid;cursor:move;height:110px;width:110px;padding:10px 10px 10px 10px;}_x000D_
#snaptarget { height:610px; width:1000px;}_x000D_
.draggable { width: 90px; height: 80px; float: left; margin: 0 0 0 0; font-size: .9em; }_x000D_
.wrapper_x000D_
{ _x000D_
background-image:linear-gradient(0deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent), linear-gradient(90deg, transparent 24%, rgba(255, 255, 255, .05) 25%, rgba(255, 255, 255, .05) 26%, transparent 27%, transparent 74%, rgba(255, 255, 255, .05) 75%, rgba(255, 255, 255, .05) 76%, transparent 77%, transparent);_x000D_
height:100%;_x000D_
background-size:45px 45px;_x000D_
border: 1px solid black;_x000D_
background-color: #434343;_x000D_
margin: 20px 0px 0px 20px;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <title>Layout</title>_x000D_
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
    <link rel="stylesheet" href="../themes/default/css/test4.css" type="text/css" charset="utf-8"/>_x000D_
    <script src="../themes/default/js/layout.js"></script>_x000D_
  </head>_x000D_
<body>_x000D_
    <div id="snaptarget" class="wrapper">_x000D_
        <div id="element" class="draggable ui-widget-content">_x000D_
          <p class="position"></p>_x000D_
          <p class="size"></p>_x000D_
        </div>_x000D_
    </div> _x000D_
    <div></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.

Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/

I've basic demo -

//app.js
import {sum} from './calc.js'

console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }

export {sum};
<html> 
    <head>
        <meta charset="utf-8" />
    </head>

    <body>
        <h1>ES6</h1>
        <script src="app.js" type="module"></script>
    </body>

</html>

Hope it helps!

How to create and download a csv file from php script?

Use the following,

echo "<script type='text/javascript'> window.location.href = '$file_name'; </script>";

How to unpack pkl file?

The pickle (and gzip if the file is compressed) module need to be used

NOTE: These are already in the standard Python library. No need to install anything new

How to unpackage and repackage a WAR file

you can update your war from the command line using java commands as mentioned here:

jar -uvf test.war yourclassesdir 

Other useful commands:

Command to unzip/explode the war file

jar -xvf test.war

Command to create the war file

jar -cvf test.war yourclassesdir 

Eg:

jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF

Postgresql SQL: How check boolean field with null and True,False Value?

  1. select *from table_name where boolean_column is False or Null;

    Is interpreted as "( boolean_column is False ) or (null)".

    It returns only rows where boolean_column is False as the second condition is always false.

  2. select *from table_name where boolean_column is Null or False;

    Same reason. Interpreted as "(boolean_column is Null) or (False)"

  3. select *from table_name where boolean_column is Null or boolean_column = False;

    This one is valid and returns 2 rows: false and null.

I just created the table to confirm. You might have typoed somewhere.

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

How to play a local video with Swift?

None of the above worked for me Swift 5 for Local Video Player

after reading apple documentation I was able to create simple example for playing video from Local resources

Here is code snip

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project

Ternary operator ?: vs if...else

No, they are converted to exactly the same executable code.

checked = "checked" vs checked = true

checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.

Any string value will be true. Also presence of attribute make it true:

<input type="checkbox" checked>

You can make it uncheked only making boolean change in DOM using JS.

So the answer is: they are equal.

w3c

Split string with multiple delimiters in Python

In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

By putting the delimiters in square brackets it seems to work more effectively.

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You bind in onResume but unbind in onDestroy. You should do the unbinding in onPause instead, so that there are always matching pairs of bind/unbind calls. Your intermittent errors will be where your activity is paused but not destroyed, and then resumed again.

The character encoding of the plain text document was not declared - mootool script

If you are using ASP.NET Core MVC project. This error message can be shown then you have the correct cshtml file in your Views folder but the action is missing in your controller.

Adding the missing action to the controller will fix it.

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Using mysql concat() in WHERE clause?

There's a few things that could get in the way - is your data clean?

It could be that you have spaces at the end of the first name field, which then means you have two spaces between the firstname and lastname when you concat them? Using trim(first_name)/trim(last_name) will fix this - although the real fix is to update your data.

You could also this to match where two words both occur but not necessarily together (assuming you are in php - which the $search_term variable suggests you are)

$whereclauses=array();
$terms = explode(' ', $search_term);
foreach ($terms as $term) {
    $term = mysql_real_escape_string($term);
    $whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);

Angular.js: set element height on page load

Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.

The HTML:

<div ng-grid="gridOptions" class="gridStyle"></div>

The directive:

angular.module('myApp.directives', [])
    .directive('resize', function ($window) {
        return function (scope, element) {

            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return { 'h': w.height(), 'w': w.width() };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                // resize Grid to optimize height
                $('.gridStyle').height(newValue.h - 250);
            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

The controller:

angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {

    // Retrieve data from the server
    $scope.surveys = Survey.query(function(data) {

        // Trigger resize event informing elements to resize according to the height of the window.
        $timeout(function () {
            angular.element($window).resize();
        }, 0)
    });

    // Configure ng-grid.
    $scope.gridOptions = {
        data: 'surveys',
        ...
    };
}

Java: Enum parameter in method

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

Replace non ASCII character from string

CharMatcher.retainFrom can be used, if you're using the Google Guava library:

String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

Getting The ASCII Value of a character in a C# string

Just cast each character to an int:

for (int i = 0; i < str.length; i++)  
  Console.Write(((int)str[i]).ToString());

Can someone explain how to implement the jQuery File Upload plugin?

I also struggled with this but got it working once I figured out how the paths work in UploadHandler.php: upload_dir and upload_url are about the only settings to look at to get it working. Also check your server error logs for debugging information.

UIView frame, bounds and center

Since the question I asked has been seen many times I will provide a detailed answer of it. Feel free to modify it if you want to add more correct content.

First a recap on the question: frame, bounds and center and theirs relationships.

Frame A view's frame (CGRect) is the position of its rectangle in the superview's coordinate system. By default it starts at the top left.

Bounds A view's bounds (CGRect) expresses a view rectangle in its own coordinate system.

Center A center is a CGPoint expressed in terms of the superview's coordinate system and it determines the position of the exact center point of the view.

Taken from UIView + position these are the relationships (they don't work in code since they are informal equations) among the previous properties:

  • frame.origin = center - (bounds.size / 2.0)

  • center = frame.origin + (bounds.size / 2.0)

  • frame.size = bounds.size

NOTE: These relationships do not apply if views are rotated. For further info, I will suggest you take a look at the following image taken from The Kitchen Drawer based on Stanford CS193p course. Credits goes to @Rhubarb.

Frame, bounds and center

Using the frame allows you to reposition and/or resize a view within its superview. Usually can be used from a superview, for example, when you create a specific subview. For example:

// view1 will be positioned at x = 30, y = 20 starting the top left corner of [self view]
// [self view] could be the view managed by a UIViewController
UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

When you need the coordinates to drawing inside a view you usually refer to bounds. A typical example could be to draw within a view a subview as an inset of the first. Drawing the subview requires to know the bounds of the superview. For example:

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

UIView* view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];    
view2.backgroundColor = [UIColor yellowColor];

[view1 addSubview:view2];

Different behaviours happen when you change the bounds of a view. For example, if you change the bounds size, the frame changes (and vice versa). The change happens around the center of the view. Use the code below and see what happens:

NSLog(@"Old Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"Old Center %@", NSStringFromCGPoint(view2.center));    

CGRect frame = view2.bounds;
frame.size.height += 20.0f;
frame.size.width += 20.0f;
view2.bounds = frame;

NSLog(@"New Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"New Center %@", NSStringFromCGPoint(view2.center));

Furthermore, if you change bounds origin you change the origin of its internal coordinate system. By default the origin is at (0.0, 0.0) (top left corner). For example, if you change the origin for view1 you can see (comment the previous code if you want) that now the top left corner for view2 touches the view1 one. The motivation is quite simple. You say to view1 that its top left corner now is at the position (20.0, 20.0) but since view2's frame origin starts from (20.0, 20.0), they will coincide.

CGRect frame = view1.bounds;
frame.origin.x += 20.0f;
frame.origin.y += 20.0f;
view1.bounds = frame; 

The origin represents the view's position within its superview but describes the position of the bounds center.

Finally, bounds and origin are not related concepts. Both allow to derive the frame of a view (See previous equations).

View1's case study

Here is what happens when using the following snippet.

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

NSLog(@"view1's frame is: %@", NSStringFromCGRect([view1 frame]));
NSLog(@"view1's bounds is: %@", NSStringFromCGRect([view1 bounds]));
NSLog(@"view1's center is: %@", NSStringFromCGPoint([view1 center]));

The relative image.

enter image description here

This instead what happens if I change [self view] bounds like the following.

// previous code here...
CGRect rect = [[self view] bounds];
rect.origin.x += 30.0f;
rect.origin.y += 20.0f;
[[self view] setBounds:rect];

The relative image.

enter image description here

Here you say to [self view] that its top left corner now is at the position (30.0, 20.0) but since view1's frame origin starts from (30.0, 20.0), they will coincide.

Additional references (to update with other references if you want)

About clipsToBounds (source Apple doc)

Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

In other words, if a view's frame is (0, 0, 100, 100) and its subview is (90, 90, 30, 30), you will see only a part of that subview. The latter won't exceed the bounds of the parent view.

masksToBounds is equivalent to clipsToBounds. Instead to a UIView, this property is applied to a CALayer. Under the hood, clipsToBounds calls masksToBounds. For further references take a look to How is the relation between UIView's clipsToBounds and CALayer's masksToBounds?.

How to validate an Email in PHP?

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using strlen() before filter_var(). I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

Subset a dataframe by multiple factor levels

You can use %in%

  data[data$Code %in% selected,]
  Code Value
1    A     1
2    B     2
7    A     3
8    A     4

Full width image with fixed height

If you want to have same ratio you should create a container and hide a part of the image.

_x000D_
_x000D_
.container{_x000D_
  width:100%;_x000D_
  height:60px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
.img {_x000D_
  width:100%;_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://placehold.it/100x100" class="img" alt="Our Location" /> _x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

How to check for an empty object in an AngularJS view

You have to just check that the object is null or not. AngularJs provide inbuilt directive ng-if. An example is given below.

<tr ng-repeat="key in object" ng-if="object != 'null'" >
    <td>{{object.key}}</td>
    <td>{{object.key}}</td>
</tr>

Change Oracle port from port 8080

Just open Run SQL Command Line and login as sysadmin and then enter below command

Exec DBMS_XDB.SETHTTPPORT(8181);

That's it. You are done.....

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Change your default port in [tomcat_home_dir]/conf/server.xml find

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

change it to

<Connector port="8090" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

Invoke(Delegate)

The answer to this question lies in how C# Controls work

Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.

From Control.InvokeRequired

Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.

From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.

  • Which action takes priority?
  • Is it even possible for both to happen at once?
  • What happens to all of the other commands the GUI needs to run?

Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.

To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.

This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.

Other reading you may find useful includes:

What's up with Begin Invoke

One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).

and, for a more code heavy overview with a representative sample:

Invalid Cross-thread Operations

// the canonical form (C# consumer)

public delegate void ControlStringConsumer(Control control, string text);  // defines a delegate type

public void SetText(Control control, string text) {
    if (control.InvokeRequired) {
        control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text});  // invoking itself
    } else {
        control.Text=text;      // the "functional part", executing only on the main thread
    }
}

Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.

There is also a further write up of what happened historically that may be of interest.

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

SQL Server: Query fast, but slow from procedure

This is probably unlikely, but given that your observed behaviour is unusual it needs to be checked and no-one else has mentioned it.

Are you absolutely sure that all objects are owned by dbo and you don't have a rogue copies owned by yourself or a different user present as well?

Just occasionally when I've seen odd behaviour it's because there was actually two copies of an object and which one you get depends on what is specified and who you are logged on as. For example it is perfectly possible to have two copies of a view or procedure with the same name but owned by different owners - a situation that can arise where you are not logged onto the database as a dbo and forget to specify dbo as object owner when you create the object.

In note that in the text you are running some things without specifying owner, eg

sp_recompile ViewOpener

if for example there where two copies of viewOpener present owned by dbo and [some other user] then which one you actually recompile if you don't specify is dependent upon circumstances. Ditto with the Report_Opener view - if there where two copies (and they could differ in specification or execution plan) then what is used depends upon circumstances - and as you do not specify owner it is perfectly possible that your adhoc query might use one and the compiled procedure might use use the other.

As I say, it's probably unlikely but it is possible and should be checked because your issues could be that you're simply looking for the bug in the wrong place.

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

Convert a String to int?

You can directly convert to an int using the str::parse::<T>() method.

let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();

You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

let my_int: i32 = my_string.parse().unwrap();

As mentioned in the comments, parse() returns a Result. This result will be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32).

Iterate through dictionary values?

Create the opposite dictionary:

PIX1 = {}
for key in PIX0.keys():
    PIX1[PIX0.get(key)] = key

Then run the same code on this dictionary instead (using PIX1 instead of PIX0).

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

Detect if Android device has Internet connection

public boolean isInternetWorking() {
    boolean success = false;
    try {
        URL url = new URL("https://google.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        success = connection.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return success;
}

return true if internet is actually available

Make sure you have these two permission

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

if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

android:usesCleartextTraffic="true"

What is Ad Hoc Query?

Ad hoc is latin for "for this purpose". You might call it an "on the fly" query, or a "just so" query. It's the kind of SQL query you just loosely type out where you need it

var newSqlQuery = "SELECT * FROM table WHERE id = " + myId;

...which is an entirely different query each time that line of code is executed, depending on the value of myId. The opposite of an ad hoc query is a predefined query such as a Stored Procedure, where you have created a single query for the entire generalized purpose of selecting from that table (say), and pass the ID as a variable.

How do you round a float to 2 decimal places in JRuby?

Try this:

module Util
module MyUtil



    def self.redondear_up(suma,cantidad, decimales=0)

        unless suma.present?
            return nil
        end


        if suma>0
            resultado= (suma.to_f/cantidad)
            return resultado.round(decimales)
        end


        return nil


    end

end 
end 

Override body style for content in an iframe

An iframe has another scope, so you can't access it to style or to change its content with javascript.

It's basically "another page".

The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.

How to upgrade Angular CLI project?

USEFUL:

Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide. https://update.angular.io/

See GitHub repository Angular CLI diff for comparing Angular CLI changes. https://github.com/cexbrayat/angular-cli-diff/

UPDATED 26/12/2018:

Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.

UPDATED 08/05/2018:

Angular CLI 1.7 introduced ng update.

ng update

A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.

Configuration information for ng update can be found here

1.7 to 6 update

CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.

npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1

UPDATED 30/04/2017:

1.0 Update

You should now follow the Angular CLI migration guide


UPDATED 04/03/2017:

RC Update

You should follow the Angular CLI RC migration guide


UPDATED 20/02/2017:

Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update

The pull request here states the following:

BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.

The angular-cli CHANGELOG.md states the following:

BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.


UPDATED 17/02/2017:

Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -

Global package:

npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init

ORIGINAL ANSWER

You should follow the steps from the README.md on GitHub for updating angular via the angular-cli.

Here they are:

Updating angular-cli

To update angular-cli to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

Local project package:

rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init

Running ng init will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.

git: fatal unable to auto-detect email address

Make sure you should be in your home directory not in local directory. while setting your username and e-mail ID.

git config --global user.email "[email protected]"
git config --global user.name "github_username"

Then follow the procedure on GitHub.

How to add an element to Array and shift indexes?

Here is a quasi-oneliner that does it:

String[] prependedArray = new ArrayList<String>() {
  {
    add("newElement");
    addAll(Arrays.asList(originalArray));
  }
}.toArray(new String[0]);

HttpClient 4.0.1 - how to release connection?

I'm chiming in with a detailed answer that specifically addresses Apache HttpClient 4.0.1. I'm using this HttpClient version, since it's provided by WAS v8.0, and I need to use that provided HttpClient within Apache Wink v1.1.1, also provided by WAS v8.0, to make some NTLM-authenticated REST calls to Sharepoint.

To quote Oleg Kalnichevski on the Apache HttpClient mailing list:

Pretty much all this code is not necessary. (1) HttpClient will automatically release the underlying connection as long as the entity content is consumed to the end of stream; (2) HttpClient will automatically release the underlying connection on any I/O exception thrown while reading the response content. No special processing is required in such as case.

In fact, this is perfectly sufficient to ensure proper release of resources:

HttpResponse rsp = httpclient.execute(target, req); 
HttpEntity entity = rsp.getEntity(); 
if (entity != null) {
     InputStream instream = entity.getContent();
     try {
         // process content
     } finally {
         instream.close();
         // entity.consumeContent() would also do
     } 
}

That is it.

Source

:before and background-image... should it work?

you can set an image URL for the content prop instead of the background-image.

content: url(/img/border-left3.png);

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

MySQL - count total number of rows in php

mysqli_num_rows is used in php 5 and above.

e.g

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }
mysqli_close($con);
?>

"The page you are requesting cannot be served because of the extension configuration." error message

PHP 7.3 Application IIS on Windows Server 2012 R2

This was a two step process for me.

1) Enable the WCF Services - with a server restart

2) Add a FASTCGI Module Mapping

1)

Go to Server Manager > Add roles and features Select your server from the server pool Go to Features > WCF Services I selected all categories then installed

2)

Go to IIS > selected the site In center pane select Handler Mappings Right hand pane select Add Module Mappings

Within the edit window:

Request path: *.php

Module: FastCgimodule

Executable: I browsed to the php-cgi.exe inside my PHP folder

Name: PHP7.3

Now that I think about it. There might be a way to add this handler mapping inside the web-config so if you migrate your site to another server you don't have to add this mapping over and over.

EDIT: Here it is. Add this to the section of the web-config.

<add name="PHP-FastCGI" verb="*" 
  path="*.php" 
  modules="FastCgiModule"
  scriptProcessor="c:\php\php-cgi.exe" 
  resourceType="Either" />

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Virtual box version 4.3.28 worked with Genymotion 2.5.2 for me. Nothing else seemed to work.

How do you remove Subversion control for a folder?

I use rsync:

# copy folder src to srcStripped excluding subfolders named '.svn'. retain dates, verbose output
rsync -av --exclude .svn src srcStripped

Linux delete file with size 0

To search and delete empty files in the current directory and subdirectories:

find . -type f -empty -delete

-type f is necessary because also directories are marked to be of size zero.


The dot . (current directory) is the starting search directory. If you have GNU find (e.g. not Mac OS), you can omit it in this case:

find -type f -empty -delete

From GNU find documentation:

If no files to search are specified, the current directory (.) is used.

Programmatically find the number of cores on a machine

On Linux, you can read the /proc/cpuinfo file and count the cores.

Java finished with non-zero exit value 2 - Android Gradle

In my case, I got this error when there are 2 or more libraries conflict (same library but different versions). Check your app build.gradle in dependencies block.

Request UAC elevation from within a Python script?

This may not completely answer your question but you could also try using the Elevate Command Powertoy in order to run the script with elevated UAC privileges.

http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx

I think if you use it it would look like 'elevate python yourscript.py'

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

Swift 5 - Background Thread

If an alert controller is executed on a background thread then the "Attempt to present ... whose view is not in the window hierarchy" error may occur.

So this:

present(alert, animated: true, completion: nil)
    

Was fixed with this:

DispatchQueue.main.async { [weak self] in
    self?.present(alert, animated: true, completion: nil)
}

PHP date() format when inserting into datetime in MySQL

Format time stamp to MySQL DATETIME column :

strftime('%Y-%m-%d %H:%M:%S',$timestamp);