Programs & Examples On #Rake

Ruby build utility similar to make with build commands defined in pure Ruby.

How to rollback just one step using rake db:migrate

For starters

rake db:rollback will get you back one step

then

rake db:rollback STEP=n

Will roll you back n migrations where n is the number of recent migrations you want to rollback.

More references here.

A cron job for rails: best practices?

Both will work fine. I usually use script/runner.

Here's an example:

0 6 * * * cd /var/www/apps/your_app/current; ./script/runner --environment production 'EmailSubscription.send_email_subscriptions' >> /var/www/apps/your_app/shared/log/send_email_subscriptions.log 2>&1

You can also write a pure-Ruby script to do this if you load the right config files to connect to your database.

One thing to keep in mind if memory is precious is that script/runner (or a Rake task that depends on 'environment') will load the entire Rails environment. If you only need to insert some records into the database, this will use memory you don't really have to. If you write your own script, you can avoid this. I haven't actually needed to do this yet, but I am considering it.

how to do "press enter to exit" in batch

@echo off
echo somethink
echo Press enter to exit
set /p input=

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t
    Rake::Task["build"].reenable
    Rake::Task["build"].invoke
  end
end

That should sort you out, just needed the same thing myself.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.

Rails DB Migration - How To Drop a Table?

Open you rails console

ActiveRecord::Base.connection.execute("drop table table_name")

"Could not find bundler" error

Make sure you're entering "bundle" update, if you have the bundler gem installed.

bundle update

If you don't have bundler installed, do gem install bundler.

Rails how to run rake task

Rake::Task['reklamer:orville'].invoke

or

Rake::Task['reklamer:orville'].invoke(args)

Rails and PostgreSQL: Role postgres does not exist

This message pops up, when the database user does not exist. Compare the manual here.
Multiple local databases cannot be the explanation. Roles are valid cluster-wide. The manual again:

Note that roles are defined at the database cluster level, and so are valid in all databases in the cluster.

You must be ending up in another database-cluster. That would be another server running on the same machine, listening to a different port. Or, more likely, on a different machine.

Could it be that the message comes, in fact, from the remote server?

How to pass command line arguments to a rake task

I couldn't figure out how to pass args and also the :environment until I worked this out:

namespace :db do
  desc 'Export product data'
  task :export, [:file_token, :file_path] => :environment do |t, args|
    args.with_defaults(:file_token => "products", :file_path => "./lib/data/")

       #do stuff [...]

  end
end

And then I call like this:

rake db:export['foo, /tmp/']

What does bundle exec rake mean?

You're running bundle exec on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.

Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.

bundle exec helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.

See more on the man page.

Here's an example Gemfile:

source 'http://rubygems.org'

gem 'rails', '2.8.3'

Here, bundle exec would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.

Purge or recreate a Ruby on Rails database

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

Difference between rake db:migrate db:reset and db:schema:load

TLDR

Use

  • rake db:migrate If you wanna make changes to the schema
  • rake db:reset If you wanna drop the database, reload the schema from schema.rb, and reseed the database
  • rake db:schema:load If you wanna reset database to schema as provided in schema.rb (This will delete all data)

Explanations

rake db:schema:load will set up the schema as provided in schema.rb file. This is useful for a fresh install of app as it doesn't take as much time as db:migrate

Important note, db:schema:load will delete data on server.

rake db:migrate makes changes to the existing schema. Its like creating versions of schema. db:migrate will look in db/migrate/ for any ruby files and execute the migrations that aren't run yet starting with the oldest. Rails knows which file is the oldest by looking at the timestamp at the beginning of the migration filename. db:migrate comes with a benefit that data can also be put in the database. This is actually not a good practice. Its better to use rake db:seed to add data.

rake db:migrate provides tasks up, down etc which enables commands like rake db:rollback and makes it the most useful command.

rake db:reset does a db:drop and db:setup
It drops the database, create it again, loads the schema, and initializes with the seed data

Relevant part of the commands from databases.rake


namespace :schema do
  desc 'Creates a db/schema.rb file that is portable against any DB supported by Active Record'
  task :dump => [:environment, :load_config] do
    require 'active_record/schema_dumper'
    filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
    File.open(filename, "w:utf-8") do |file|
      ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
    end
    db_namespace['schema:dump'].reenable
  end

  desc 'Loads a schema.rb file into the database'
  task :load => [:environment, :load_config, :check_protected_environments] do
    ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA'])
  end

  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
  task :reset => [ 'db:drop', 'db:setup' ]

namespace :migrate do
  # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
  task :redo => [:environment, :load_config] do
    if ENV['VERSION']
      db_namespace['migrate:down'].invoke
      db_namespace['migrate:up'].invoke
    else
      db_namespace['rollback'].invoke
      db_namespace['migrate'].invoke
    end
  end

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

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

Below is the configuration in Maven software by default in MAVEN_HOME\conf\settings.xml.

<settings>
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

Add the below line under this configuration, will fulfill the requirement.

<localRepository>custom_path</localRepository>

Ex: <localRepository>D:/MYNAME/settings/.m2/repository</localRepository>

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

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

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

And run finds on top of it:

soup.find("div")

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;
}

Would override all link styles and make all the states the colour blue.

How to Set Opacity (Alpha) for View in Android

According to the android docs view alpha is a value between 0 and 1. So to set it use something like this:

View v;
v.setAlpha(.5f);

DateTime group by date and hour

Using MySQL I usually do it that way:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

Or in the same idea, if you need to output the date/hour:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Removing nan values from an array

filter(lambda v: v==v, x)

works both for lists and numpy array since v!=v only for NaN

How do I split a string into an array of characters?

To support emojis use this

('Dragon ').split(/(?!$)/u);

=> ['D', 'r', 'a', 'g', 'o', 'n', ' ', '']

CSS flex, how to display one item on first line and two on the next line

You can do something like this:

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.flex>div {_x000D_
  flex: 1 0 50%;_x000D_
}_x000D_
_x000D_
.flex>div:first-child {_x000D_
  flex: 0 1 100%;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div>Hi</div>_x000D_
  <div>Hello</div>_x000D_
  <div>Hello 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is a demo: http://jsfiddle.net/73574emn/1/

This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basis to be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;

How to get the value of an input field using ReactJS?

You should use constructor under the class MyComponent extends React.Component

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

Then you will get the result of title

convert an enum to another type of enum

Just cast one to int and then cast it to the other enum (considering that you want the mapping done based on value):

Gender2 gender2 = (Gender2)((int)gender1);

How to open a file for both reading and writing?

Summarize the I/O behaviors

|          Mode          |  r   |  r+  |  w   |  w+  |  a   |  a+  |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
|          Read          |  +   |  +   |      |  +   |      |  +   |
|         Write          |      |  +   |  +   |  +   |  +   |  +   |
|         Create         |      |      |  +   |  +   |  +   |  +   |
|         Cover          |      |      |  +   |  +   |      |      |
| Point in the beginning |  +   |  +   |  +   |  +   |      |      |
|    Point in the end    |      |      |      |      |  +   |  +   |

and the decision branch

enter image description here

Blade if(isset) is not working Laravel

You can use the ternary operator easily:

{{ $usersType ? $usersType : '' }}

What is the easiest way to get current GMT time in Unix timestamp format?

I like this method:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.

Make div (height) occupy parent remaining height

check the demo - http://jsfiddle.net/S8g4E/6/

use css -

#container { width: 300px; height: 300px; border:1px solid red; display: table;}
#up { background: green; display: table-row; }
#down { background:pink; display: table-row;}

What is PostgreSQL equivalent of SYSDATE from Oracle?

SYSDATE is an Oracle only function.

The ANSI standard defines current_date or current_timestamp which is supported by Postgres and documented in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

(Btw: Oracle supports CURRENT_TIMESTAMP as well)

You should pay attention to the difference between current_timestamp, statement_timestamp() and clock_timestamp() (which is explained in the manual, see the above link)


This statement:

select up_time from exam where up_time like sysdate

Does not make any sense at all. Neither in Oracle nor in Postgres. If you want to get rows from "today", you need something like:

select up_time 
from exam 
where up_time = current_date

Note that in Oracle you would probably want trunc(up_time) = trunc(sysdate) to get rid of the time part that is always included in Oracle.

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

Using Enum values as String literals

use mode1.name() or String.valueOf(Modes.mode1)

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Can I append an array to 'formdata' in javascript?

use "xxx[]" as name of the field in formdata (you will get an array of - stringified objects - in you case)

so within your loop

$('.tag-form').each(function(i){
            article = $(this).find('input[name="article"]').val();
            gender = $(this).find('input[name="gender"]').val();
            brand = $(this).find('input[name="brand"]').val();
            this_tag = new Array();
            this_tag.article = article;
            this_tag.gender = gender;
            this_tag.brand = brand;
            //tags.push(this_tag);    
            formdata.append('tags[]', this_tag);
...

Dilemma: when to use Fragments vs Activities:

My philosophy is this:

Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

It's just my philosophy since fragments were introduced.

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

Python to print out status bar and percentage

This is quite a simple approach can be used with any loop.

#!/usr/bin/python
for i in range(100001):
    s =  ((i/5000)*'#')+str(i)+(' %')
    print ('\r'+s),

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

How can I reorder a list?

One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

  1. Reorder by value - Already solved by AJ above
  2. Reorder by index

    mylist = ['a', 'b', 'c', 'd', 'e']
    myorder = [3, 2, 0, 1, 4]
    
    mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
    print [item[0] for item in mylist]
    

This will print ['c', 'd', 'b', 'a', 'e']

MySQL skip first 10 results

LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip

TNS Protocol adapter error while starting Oracle SQL*Plus

Enter SQL*Plus with:

sqlplus /nolog

And then:

connect sys@<SID> AS sysdba

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

_x000D_
_x000D_
var temp = "This is a string.";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

And, if there are no matches, it returns 0:

_x000D_
_x000D_
var temp = "Hello World!";_x000D_
var count = (temp.match(/is/g) || []).length;_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

Looping through rows in a DataView

//You can convert DataView to Table. using DataView.ToTable();

foreach (DataRow drGroup in dtGroups.Rows)
{
    dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

    if (dtForms.DefaultView.Count > 0)
    {
        foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
        {
            drNew = dtNew.NewRow();

            drNew["FormId"] = drForm["FormId"];
            drNew["FormCaption"] = drForm["FormCaption"];
            drNew["GroupName"] = drGroup["GroupName"];
            dtNew.Rows.Add(drNew);
        }
    }
}

// Or You Can Use

// 2.

dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

DataTable DTFormFilter = dtForms.DefaultView.ToTable();

foreach (DataRow drFormFilter in DTFormFilter.Rows)
{ 
                            //Your logic goes here
}

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

What is the difference between POST and GET?

The only "big" difference between POST & GET (when using them with AJAX) is since GET is URL provided, they are limited in ther length (since URL arent infinite in length).

Why is this jQuery click function not working?

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});

sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

see column-constraint .

And insert a row without providing any value.

INSERT INTO "test" DEFAULT VALUES;

Django - Did you forget to register or load this tag?

For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

For other versions use static

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

Also you have to check that you defined STATIC_URL in setting.py

At last, make sure the static files exist in the defined folder

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

$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

how to fetch data from database in Hibernate

Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.

String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
    {
         s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);

   }

for fetch we need Iterator for that define and import package.

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

Should each and every table have a primary key?

I always have a primary key, even if in the beginning I don't have a purpose in mind yet for it. There have been a few times when I eventually need a PK in a table that doesn't have one and it's always more trouble to put it in later. I think there is more of an upside to always including one.

Remove unused imports in Android Studio

You can do it on the fly. You don't need to call (Ctrl+Shift+O) or "Project/Optimize Imports..." each time.

Just set this checkbox in Settings -> Editor -> General -> Auto Import -> Optimize Imports on the fly.

enter image description here

On OSX: Preferences -> Editor -> General -> Auto Import -> Optimize imports on the fly

How do I get rid of the "cannot empty the clipboard" error?

If you can't find the clipboard, then close that excel sheet and reopen it again. This will solve your problem.

"Submit is not a function" error in JavaScript

submit is not a function

means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work.

When you name the button submit, you override the submit() function on the form.

Could not autowire field:RestTemplate in Spring boot application

Depending on what technologies you're using and what versions will influence how you define a RestTemplate in your @Configuration class.

Spring >= 4 without Spring Boot

Simply define an @Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Boot <= 1.3

No need to define one, Spring Boot automatically defines one for you.

Spring Boot >= 1.4

Spring Boot no longer automatically defines a RestTemplate but instead defines a RestTemplateBuilder allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder as an argument in your @Bean method to create a RestTemplate:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

Using it in your class

@Autowired
private RestTemplate restTemplate;

Reference

JQuery DatePicker ReadOnly

Readonly datepicker with example (jquery) - 
In following example you can not open calendar popup.
Check following code see normal and readonly datepicker.

Html Code- 

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang = "en">_x000D_
   <head>_x000D_
      <meta charset = "utf-8">_x000D_
      <title>jQuery UI Datepicker functionality</title>_x000D_
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"_x000D_
         rel = "stylesheet">_x000D_
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>_x000D_
_x000D_
      <!-- Javascript -->_x000D_
      <script>_x000D_
         $(function() {_x000D_
                var currentDate=new Date();_x000D_
                $( "#datepicker-12" ).datepicker({_x000D_
                  setDate:currentDate,_x000D_
                  beforeShow: function(i) { _x000D_
                      if ($(i).attr('readonly')) { return false; } _x000D_
                   }_x000D_
                });_x000D_
                $( "#datepicker-12" ).datepicker("setDate", currentDate);_x000D_
                $("#datepicker-13").datepicker();_x000D_
                $( "#datepicker-13" ).datepicker("setDate", currentDate);_x000D_
        });_x000D_
      </script>_x000D_
   </head>_x000D_
_x000D_
   <body>_x000D_
      <!-- HTML --> _x000D_
      <p>Readonly DatePicker: <input type = "text" id = "datepicker-12" readonly="readonly"></p>_x000D_
      <p>Normal DatePicker: <input type = "text" id = "datepicker-13"></p>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

How to print Unicode character in C++?

Ultimately, this is completely platform-dependent. Unicode-support is, unfortunately, very poor in Standard C++. For GCC, you will have to make it a narrow string, as they use UTF-8, and Windows wants a wide string, and you must output to wcout.

// GCC
std::cout << "?";
// Windoze
wcout << L"?";

How do I format a number to a dollar amount in PHP

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

Note: money_format is undefined in Windows.


UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Instead, look into NumberFormatter::formatCurrency.

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

How to declare a constant map in Golang?

As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

var romanNumeralDict = struct {
    m map[int]string
}{m: map[int]string {
    1000: "M",
    900: "CM",
    //YOUR VALUES HERE
}}

func main() {
    d := 1000
    fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}

Clear image on picturebox

clear pictureBox in c# winform Application Simple way to clear pictureBox in c# winform Application

Incrementing a date in JavaScript

This a simpler method , and it will return the date in simple yyyy-mm-dd format , Here it is

function incDay(date, n) {
    var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
    fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
    return fudate;
}

example :

var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .

Note

incDay(new Date("2020-11-12"), 1); 
incDay("2020-11-12", 1); 

will return the same result .

jQuery: keyPress Backspace won't fire?

If you want to fire the event only on changes of your input use:

$('.s').bind('input', function(){
  console.log("search!");
  doSearch();
});

Does JavaScript guarantee object property order?

YES (for non-integer keys).

Most Browsers iterate object properties as:

  1. Integer keys in ascending order (and strings like "1" that parse as ints)
  2. String keys, in insertion order (ES2015 guarantees this and all browsers comply)
  3. Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

Some older browsers combine categories #1 and #2, iterating all keys in insertion order. If your keys might parse as integers, it's best not to rely on any specific iteration order.

Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.

Old Language Spec (before ES2015): Iteration order was technically undefined, but all major browsers complied with the ES2015 behavior.

Note that the ES2015 behavior was a good example of the language spec being driven by existing behavior, and not the other way round. To get a deeper sense of that backwards-compatibility mindset, see http://code.google.com/p/v8/issues/detail?id=164, a Chrome bug that covers in detail the design decisions behind Chrome's iteration order behavior. Per one of the (rather opinionated) comments on that bug report:

Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.

Stop Excel from automatically converting certain text values to dates

If you put an inverted comma at the start of the field, it will be interpreted as text.

Example: 25/12/2008 becomes '25/12/2008

You are also able to select the field type when importing.

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

How to use timeit module

lets setup the same dictionary in each of the following and test the execution time.

The setup argument is basically setting up the dictionary

Number is to run the code 1000000 times. Not the setup but the stmt

When you run this you can see that index is way faster than get. You can run it multiple times to see.

The code basically tries to get the value of c in the dictionary.

import timeit

print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))

Here are my results, yours will differ.

by index: 0.20900007452246427

by get: 0.54841166886888

How do I open a second window from the first window in WPF?

Assuming the second window is defined as public partial class Window2 : Window, you can do it by:

Window2 win2 = new Window2();
win2.Show();

Need a row count after SELECT statement: what's the optimal SQL approach?

If you are really concerned that your row count will change between the select count and the select statement, why not select your rows into a temp table first? That way, you know you will be in sync.

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

How do I abort/cancel TPL Tasks?

I use a mixed approach to cancel a task.

  • Firstly, I'm trying to Cancel it politely with using the Cancellation.
  • If it's still running (e.g. due to a developer's mistake), then misbehave and kill it using an old-school Abort method.

Checkout an example below:

private CancellationTokenSource taskToken;
private AutoResetEvent awaitReplyOnRequestEvent = new AutoResetEvent(false);

void Main()
{
    // Start a task which is doing nothing but sleeps 1s
    LaunchTaskAsync();
    Thread.Sleep(100);
    // Stop the task
    StopTask();
}

/// <summary>
///     Launch task in a new thread
/// </summary>
void LaunchTaskAsync()
{
    taskToken = new CancellationTokenSource();
    Task.Factory.StartNew(() =>
        {
            try
            {   //Capture the thread
                runningTaskThread = Thread.CurrentThread;
                // Run the task
                if (taskToken.IsCancellationRequested || !awaitReplyOnRequestEvent.WaitOne(10000))
                    return;
                Console.WriteLine("Task finished!");
            }
            catch (Exception exc)
            {
                // Handle exception
            }
        }, taskToken.Token);
}

/// <summary>
///     Stop running task
/// </summary>
void StopTask()
{
    // Attempt to cancel the task politely
    if (taskToken != null)
    {
        if (taskToken.IsCancellationRequested)
            return;
        else
            taskToken.Cancel();
    }

    // Notify a waiting thread that an event has occurred
    if (awaitReplyOnRequestEvent != null)
        awaitReplyOnRequestEvent.Set();

    // If 1 sec later the task is still running, kill it cruelly
    if (runningTaskThread != null)
    {
        try
        {
            runningTaskThread.Join(TimeSpan.FromSeconds(1));
        }
        catch (Exception ex)
        {
            runningTaskThread.Abort();
        }
    }
}

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {
  $(":button.brown.selected").removeClass("selected");
  $(this).addClass("selected");
});

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

How do I plot in real-time in a while loop using matplotlib?

The top (and many other) answers were built upon plt.pause(), but that was an old way of animating the plot in matplotlib. It is not only slow, but also causes focus to be grabbed upon each update (I had a hard time stopping the plotting python process).

TL;DR: you may want to use matplotlib.animation (as mentioned in documentation).

After digging around various answers and pieces of code, this in fact proved to be a smooth way of drawing incoming data infinitely for me.

Here is my code for a quick start. It plots current time with a random number in [0, 100) every 200ms infinitely, while also handling auto rescaling of the view:

from datetime import datetime
from matplotlib import pyplot
from matplotlib.animation import FuncAnimation
from random import randrange

x_data, y_data = [], []

figure = pyplot.figure()
line, = pyplot.plot_date(x_data, y_data, '-')

def update(frame):
    x_data.append(datetime.now())
    y_data.append(randrange(0, 100))
    line.set_data(x_data, y_data)
    figure.gca().relim()
    figure.gca().autoscale_view()
    return line,

animation = FuncAnimation(figure, update, interval=200)

pyplot.show()

You can also explore blit for even better performance as in FuncAnimation documentation.

An example from the blit documentation:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

Convert a matrix to a 1 dimensional array

Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.

> m=matrix(1:12,3,4)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> as.vector(m)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
> as.vector(t(m))
 [1]  1  4  7 10  2  5  8 11  3  6  9 12

Python loop to run for certain amount of seconds

If I understand you, you can do it with a datetime.timedelta -

import datetime

endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
  if datetime.datetime.now() >= endTime:
    break
  # Blah
  # Blah

How do you change text to bold in Android?

You can use this for font

create a Class Name TypefaceTextView and extend the TextView

private static Map mTypefaces;

public TypefaceTextView(final Context context) {
    this(context, null);
}

public TypefaceTextView(final Context context, final AttributeSet attrs) {
    this(context, attrs, 0);
}

public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);
    if (mTypefaces == null) {
        mTypefaces = new HashMap<String, Typeface>();
    }

    if (this.isInEditMode()) {
        return;
    }

    final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
    if (array != null) {
        final String typefaceAssetPath = array.getString(
                R.styleable.TypefaceTextView_customTypeface);

        if (typefaceAssetPath != null) {
            Typeface typeface = null;

            if (mTypefaces.containsKey(typefaceAssetPath)) {
                typeface = mTypefaces.get(typefaceAssetPath);
            } else {
                AssetManager assets = context.getAssets();
                typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                mTypefaces.put(typefaceAssetPath, typeface);
            }

            setTypeface(typeface);
        }
        array.recycle();
    }
}

paste the font in the fonts folder created in the asset folder

<packagename.TypefaceTextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1.5"
        android:gravity="center"
        android:text="TRENDING TURFS"
        android:textColor="#000"
        android:textSize="20sp"
        app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**

Place the lines in the parent layout in the xml

 xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"

Get response from PHP file using AJAX

<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                dataType:'text'; //or HTML, JSON, etc.
                success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
            });
        }
    </script>

Why does adb return offline after the device string?

I had the same issue and none of the other answers worked. It seems to occur frequently when you connect to the device using the wifi mode (running command 'adb tcpip 5555'). I found this solution, its sort of a workaround but it does work.

  1. Disconnect the usb (or turn off devices wifi if your connected over wifi)
  2. Close eclipse/other IDE
  3. Check your running programs for adb.exe (Task manager in Windows). If its running, Terminate it.
  4. Restart your android device
  5. After your device restarts, connect it via USB and run 'adb devices'. This should start the adb daemon. And you should see your device online again.

This process is a little lengthy but its the only one that has worked everytime for me.

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

Going from MM/DD/YYYY to DD-MMM-YYYY in java

Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.

Here's some code:

    SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
    Date date = format1.parse("05/01/1999");
    System.out.println(format2.format(date));

Output:

01-May-99

How to create a multi line body in C# System.Net.Mail.MailMessage

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

docker cannot start on windows

One of my friends was having a similar issue, we tried this and it worked.

Hyper-V, despite being listed under "Turn Windows features on or off" as being active, was not in fact active. This became apparent when running systeminfo under PowerShell, and seeing that the requirements were listed as met (which is not the output you would expect were Hyper-V actually running).Steps:

  1. Open "Turn Windows features on or off"
  2. If you are not sure how to do this please refer https://www.howtogeek.com/250228/what-windows-10s-optional-features-do-and-how-to-[turn-them-on-or-off/][1]
  3. Turn Hyper-V off (uncheck box, making sure all sub-components are marked as off)
  4. Hit "Ok" - and your machine will reboot.
  5. When your computer starts up again, open "Turn Windows features on or off" and turn Hyper-V back on. Your machine will reboot again.

Now you can test by running docker hello-world image.

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

AngularJS directive does not update on scope variable changes

You should create a bound scope variable and watch its changes:

return {
   restrict: 'E',
   scope: {
     name: '='
   },
   link: function(scope) {
     scope.$watch('name', function() {
        // all the code here...
     });
   }
};

C# How can I check if a URL exists/is valid?

Here is another implementation of this solution:

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TRUE if the Status code == 200
        response.Close();
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

From: http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/

Getting raw SQL query string from PDO prepared statements

You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):

class DebugPDOStatement extends \PDOStatement{
  private $bound_variables=array();
  protected $pdo;

  protected function __construct($pdo) {
    $this->pdo = $pdo;
  }

  public function bindValue($parameter, $value, $data_type=\PDO::PARAM_STR){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);
    return parent::bindValue($parameter, $value, $data_type);
  }

  public function bindParam($parameter, &$variable, $data_type=\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);
    return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
  }

  public function debugBindedVariables(){
    $vars=array();

    foreach($this->bound_variables as $key=>$val){
      $vars[$key] = $val->value;

      if($vars[$key]===NULL)
        continue;

      switch($val->type){
        case \PDO::PARAM_STR: $type = 'string'; break;
        case \PDO::PARAM_BOOL: $type = 'boolean'; break;
        case \PDO::PARAM_INT: $type = 'integer'; break;
        case \PDO::PARAM_NULL: $type = 'null'; break;
        default: $type = FALSE;
      }

      if($type !== FALSE)
        settype($vars[$key], $type);
    }

    if(is_numeric(key($vars)))
      ksort($vars);

    return $vars;
  }

  public function debugQuery(){
    $queryString = $this->queryString;

    $vars=$this->debugBindedVariables();
    $params_are_numeric=is_numeric(key($vars));

    foreach($vars as $key=>&$var){
      switch(gettype($var)){
        case 'string': $var = "'{$var}'"; break;
        case 'integer': $var = "{$var}"; break;
        case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;
        case 'NULL': $var = 'NULL';
        default:
      }
    }

    if($params_are_numeric){
      $queryString = preg_replace_callback( '/\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);
    }else{
      $queryString = strtr($queryString, $vars);
    }

    echo $queryString.PHP_EOL;
  }
}


class DebugPDO extends \PDO{
  public function __construct($dsn, $username="", $password="", $driver_options=array()) {
    $driver_options[\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));
    $driver_options[\PDO::ATTR_PERSISTENT] = FALSE;
    parent::__construct($dsn,$username,$password, $driver_options);
  }
}

And then you can use this inherited class for debugging purpouses.

$dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');

$var='user_test';
$sql=$dbh->prepare("SELECT user FROM users WHERE user = :test");
$sql->bindValue(':test', $var, PDO::PARAM_STR);
$sql->execute();

$sql->debugQuery();
print_r($sql->debugBindedVariables());

Resulting in

SELECT user FROM users WHERE user = 'user_test'

Array ( [:test] => user_test )

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

Android button font size

Button butt= new Button(_context);
butt.setTextAppearance(_context, R.style.ButtonFontStyle);

and in res/values/style.xml

<resources>   
    <style name="ButtonFontStyle">
            <item name="android:textSize">12sp</item>
    </style>
</resources>

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

You could use lookarounds also.

test.replaceAll("^ +| +$|(?<= ) ", "");

OR

test.replaceAll("^ +| +$| (?= )", "")

<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.

Example:

    String[] tests = {
            "  x  ",          // [x]
            "  1   2   3  ",  // [1 2 3]
            "",               // []
            "   ",            // []
        };
        for (String test : tests) {
            System.out.format("[%s]%n",
                test.replaceAll("^ +| +$| (?= )", "")
            );
        }

Why would $_FILES be empty when uploading files to PHP?

Here's a check-list for file uploading in PHP:

  1. Check php.ini for:
    file_uploads = On
    post_max_size = 100M
    upload_max_filesize = 100M

    • You might need to use .htaccess or .user.ini if you are on shared hosting and don't have access to php.ini.
    • Make sure you’re editing the correct ini file – use the phpinfo() function to verify your settings are actually being applied.
    • Also make sure you don’t misspell the sizes - it should be 100M not 100MB.
  2. Make sure your <form> tag has the enctype="multipart/form-data" attribute. No other tag will work, it has to be your FORM tag. Double check that it is spelled correctly. Double check that multipart/form-data is surrounded by STRAIGHT QUOTES, not smart quotes pasted in from Word OR from a website blog (WordPress converts straight quotes to angle quotes!). If you have multiple forms on the page, make sure they both have this attribute. Type them in manually, or try straight single quotes typed in manually.

  3. Make sure you do not have two input file fields with the same name attribute. If you need to support multiple, put square brackets at the end of the name:

    <input type="file" name="files[]">
    <input type="file" name="files[]">
    
  4. Make sure your tmp and upload directories have the correct read+write permissions set. The temporary upload folder is specified in PHP settings as upload_tmp_dir.

  5. Make sure your file destination and tmp/upload directories do not have spaces in them.

  6. Make sure all <form>'s on your page have </form> close tags.

  7. Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.

  8. Make sure your file input tag has a NAME attribute. An ID attribute is NOT sufficient! ID attributes are for use in the DOM, not for POST payloads.

  9. Make sure you are not using Javascript to disable your <input type="file"> field on submission

  10. Make sure you're not nesting forms like <form><form></form></form>

  11. Check your HTML structure for invalid/overlapping tags like <div><form></div></form>

  12. Also make sure that the file you are uploading does not have any non-alphanumeric characters in it.

  13. Once, I just spent hours trying to figure out why this was happening to me all of a sudden. It turned out that I had modified some of the PHP settings in .htaccess, and one of them (not sure which yet) was causing the upload to fail and $_FILES to be empty.

  14. You could potentially try avoiding underscores (_) in the name="" attribute of the <input> tag

  15. Try uploading very small files to narrow down whether it's a file-size issue.

  16. Check your available disk space. Although very rare, it is mentioned in this PHP Manual page comment:

    If the $_FILES array suddenly goes mysteriously empty, even though your form seems correct, you should check the disk space available for your temporary folder partition. In my installation, all file uploads failed without warning. After much gnashing of teeth, I tried freeing up additional space, after which file uploads suddenly worked again.

  17. Be sure that you're not submitting the form through an AJAX POST request instead of a normal POST request that causes a page to reload. I went through each and every point in the list above, and finally found out that the reason due to which my $_FILES variable was empty was that I was submitting the form using an AJAX POST request. I know that there are methods to upload files using ajax too, but this could be a valid reason why your $_FILES array is empty.

Source for some of these points:
http://getluky.net/2004/10/04/apachephp-_files-array-mysteriously-empty/

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

add image to uitableview cell

cell.imageView.image = [UIImage imageNamed:@"image.png"];

UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.

Why should a Java class implement comparable?

Here is a real life sample. Note that String also implements Comparable.

class Author implements Comparable<Author>{
    String firstName;
    String lastName;

    @Override
    public int compareTo(Author other){
        // compareTo should return < 0 if this is supposed to be
        // less than other, > 0 if this is supposed to be greater than 
        // other and 0 if they are supposed to be equal
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

later..

/**
 * List the authors. Sort them by name so it will look good.
 */
public List<Author> listAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    Collections.sort(authors);
    return authors;
}

/**
 * List unique authors. Sort them by name so it will look good.
 */
public SortedSet<Author> listUniqueAuthors(){
    List<Author> authors = readAuthorsFromFileOrSomething();
    return new TreeSet<Author>(authors);
}

How to convert An NSInteger to an int?

Commonly used in UIsegmentedControl, "error" appear when compiling in 64bits instead of 32bits, easy way for not pass it to a new variable is to use this tips, add (int):

[_monChiffre setUnite:(int)[_valUnites selectedSegmentIndex]];

instead of :

[_monChiffre setUnite:[_valUnites selectedSegmentIndex]];

How to scale Docker containers in production

You can try Tsuru. Tsuru is a opensource PaaS inspired in Heroku, and it is already with some products in production at Globo.com(internet arm of the biggest Broadcast Television Company in Brazil)

It manages the entire flow of an application, since the container creation, deploy, routing(with hipache) with many nice features as docker cluster, scaling of units, segregated deploy, etc.

Take a look in our documentation bellow: http://docs.tsuru.io/

Here our post covering our environment: http://blog.tsuru.io/2014/04/04/running-tsuru-in-production-scaling-and-segregating-docker-containers/

How to drop all stored procedures at once in SQL Server database?

Try this, it work for me

DECLARE @spname sysname;
DECLARE SPCursor CURSOR FOR
SELECT SCHEMA_NAME(schema_id) + '.' + name
FROM sys.objects
WHERE type = 'P';
OPEN SPCursor;
FETCH NEXT FROM SPCursor INTO @spname;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('DROP PROCEDURE ' + @spname);
FETCH NEXT FROM SPCursor INTO @spname;
END
CLOSE SPCursor;
DEALLOCATE SPCursor;

Android Studio: Can't start Git

In Windows, my git was located at

C:\Users\<username>\AppData\Local\Programs\Git\bin\git.exe

href image link download on click

<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
    <img alt="ImageName" src="/path/to/image">
</a>

It's not yet fully supported caniuse, but you can use with modernizr (under Non-core detects) to check the support of the browser.

Eclipse/Maven error: "No compiler is provided in this environment"

For me (on windows 10), I was getting the error "No compiler is provided in this environment" at the Windows command prompt when I ran mvn install. The fix was changing the JAVA_HOME environment variable to point to my jdk (C:\Program Files\Java\jdk1.8.0_101); previously it had pointed to the jre.

And to get Eclipse to use the new jdk, I edited eclipse.ini in my eclipse distribution and changed the line for -vm to C:\Program Files\Java\jdk1.8.0_101\bin.

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

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

VBoxManage: error: Failed to create the host-only adapter

I fixed this error by installing VirtualBox 4.2 instead of 4.3. I think the latest version of vagrant and VB 4.3 are incompatible on a fedora system.

Sqlite primary key on multiple columns

PRIMARY KEY (id, name) didn't work for me. Adding a constraint did the job instead.

CREATE TABLE IF NOT EXISTS customer (
    id INTEGER, name TEXT,
    user INTEGER,
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)

"No backupset selected to be restored" SQL Server 2012

I got the same error message even though I backup and restore on the same single machine.

The issue was from here: when backup, i had 2 item in the destination box.

So the fix would be: make sure only 1 item in the 'destination' box. Remove all the others if there are.

How to explain callbacks in plain english? How are they different from calling one function from another function?

A callback is a method that is scheduled to be executed when a condition is met.

An "real world" example is a local video game store. You are waiting for Half-Life 3. Instead of going to the store every day to see if it is in, you register your email on a list to be notified when the game is available. The email becomes your "callback" and the condition to be met is the game's availability.

A "programmers" example is a web page where you want to perform an action when a button is clicked. You register a callback method for a button and continue doing other tasks. When/if the user cicks on the button, the browser will look at the list of callbacks for that event and call your method.

A callback is a way to handle events asynchronously. You can never know when the callback will be executed, or if it will be executed at all. The advantage is that it frees your program and CPU cycles to perform other tasks while waiting for the reply.

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

Get path of executable

This is a Windows specific way, but it is at least half of your answer.

GetThisPath.h

/// dest is expected to be MAX_PATH in length.
/// returns dest
///     TCHAR dest[MAX_PATH];
///     GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);

GetThisPath.cpp

#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
    if (!dest) return NULL;
    if (MAX_PATH > destSize) return NULL;

    DWORD length = GetModuleFileName( NULL, dest, destSize );
    PathRemoveFileSpec(dest);
    return dest;
}

mainProgram.cpp

TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);

I would suggest using platform detection as preprocessor directives to change the implementation of a wrapper function that calls GetThisPath for each platform.

Unable to start Service Intent

I've found the same problem. I lost almost a day trying to start a service from OnClickListener method - outside the onCreate and after 1 day, I still failed!!!! Very frustrating! I was looking at the sample example RemoteServiceController. Theirs works, but my implementation does not work!

The only way that was working for me, was from inside onCreate method. None of the other variants worked and believe me I've tried them all.

Conclusion:

  • If you put your service class in different package than the mainActivity, I'll get all kind of errors
  • Also the one "/" couldn't find path to the service, tried starting with Intent(package,className) and nothing , also other type of Intent starting

  • I moved the service class in the same package of the activity Final form that works

  • Hopefully this helps someone by defining the listerners onClick inside the onCreate method like this:

    public void onCreate() {
    //some code......
        Button btnStartSrv  = (Button)findViewById(R.id.btnStartService);
        Button btnStopSrv  = (Button)findViewById(R.id.btnStopService);
    
        btnStartSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startService(new Intent("RM_SRV_AIDL"));
            }
        });
    
        btnStopSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent("RM_SRV_AIDL"));
            }
        });
    
    } // end onCreate
    

Also very important for the Manifest file, be sure that service is child of application:

<application ... >
    <activity ... >
     ...
    </activity>
    <service
        android:name="com.mainActivity.MyRemoteGPSService"
        android:label="GPSService"
        android:process=":remote">

        <intent-filter>
             <action android:name="RM_SRV_AIDL" />
        </intent-filter>
    </service>
</application>

Using Regular Expressions to Extract a Value in Java

Try doing something like this:

Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");

if (m.find()) {
    System.out.println(m.group(1));
}

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

In PHP, how do you change the key of an array element?

I like KernelM's solution, but I needed something that would handle potential key conflicts (where a new key may match an existing key). Here is what I came up with:

function swapKeys( &$arr, $origKey, $newKey, &$pendingKeys ) {
    if( !isset( $arr[$newKey] ) ) {
        $arr[$newKey] = $arr[$origKey];
        unset( $arr[$origKey] );
        if( isset( $pendingKeys[$origKey] ) ) {
            // recursion to handle conflicting keys with conflicting keys
            swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );
            unset( $pendingKeys[$origKey] );
        }
    } elseif( $newKey != $origKey ) {
        $pendingKeys[$newKey] = $origKey;
    }
}

You can then cycle through an array like this:

$myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );
$pendingKeys = array();
foreach( $myArray as $key => $myArrayValue ) {
    // NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)
    $timestamp = strtotime( $myArrayValue );
    swapKeys( $myArray, $key, $timestamp, $pendingKeys );
}
// RESULT: $myArray == array( 1=>'1970-01-01 00:00:01', 60=>'1970-01-01 00:01:00' )

How to handle configuration in Go

have a look at gonfig

// load
config, _ := gonfig.FromJson(myJsonFile)
// read with defaults
host, _ := config.GetString("service/host", "localhost")
port, _ := config.GetInt("service/port", 80)
test, _ := config.GetBool("service/testing", false)
rate, _ := config.GetFloat("service/rate", 0.0)
// parse section into target structure
config.GetAs("service/template", &template)

How to support UTF-8 encoding in Eclipse

Try this

  • 1) Window > Preferences > General > Content Types, set UTF-8 as the default encoding for all content types.

  • 2) Window > Preferences > General > Workspace, set Text file encoding to Other : UTF-8

how to delete files from amazon s3 bucket?

It's worked for me try it.

import boto
import sys
from boto.s3.key import Key
import boto.s3.connection

AWS_ACCESS_KEY_ID = '<access_key>'
AWS_SECRET_ACCESS_KEY = '<secret_access_key>'
Bucketname = 'bucket_name' 

conn = boto.s3.connect_to_region('us-east-2',
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        is_secure=True,              
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn.get_bucket(Bucketname)

k = Key(bucket)

k.key = 'filename to delete'
bucket.delete_key(k)   

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

Format decimal for percentage values?

If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.

For example, to get a decimal value with a trailing "%" and no space between the value and the "%":

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

More complete example:

using System.Globalization; 

...

decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

It's quite possible to do this in JavaScript as long as your fallback is another applink. Building on Nathan's suggestion:

<html>
  <head>
    <meta name="viewport" content="width=device-width" />
  </head>
  <body>

    <h2><a id="applink1" href="fb://profile/116201417">open facebook with fallback to appstore</a></h2>
    <h2><a id="applink2" href="unknown://nowhere">open unknown with fallback to appstore</a></h2>
    <p><i>Only works on iPhone!</i></p>    

  <script type="text/javascript">

// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";

function applink(fail){
    return function(){
        var clickedAt = +new Date;
        // During tests on 3g/3gs this timeout fires immediately if less than 500ms.
        setTimeout(function(){
            // To avoid failing on return to MobileSafari, ensure freshness!
            if (+new Date - clickedAt < 2000){
                window.location = fail;
            }
        }, 500);    
    };
}

document.getElementById("applink1").onclick = applink(appstorefail);
document.getElementById("applink2").onclick = applink(appstorefail);

</script>
</body>
</html>

Check out a live demo here.

Stacking DIVs on top of each other?

If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index CSS attribute. This should work (untested)

<div>
    <div style='z-index: 1'>1</div>
    <div style='z-index: 2'>2</div>
    <div style='z-index: 3'>3</div>
    <div style='z-index: 4'>4</div>
</div>

This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

How do I run a node.js app as a background service?

This answer is quite late to the party, but I found that the best solution was to write a shell script that used the both the screen -dmS and nohup commands.

screen -dmS newScreenName nohup node myserver.js >> logfile.log

I also add the >> logfile bit on the end so I can easily save the node console.log() statements.

Why did I use a shell script? Well I also added in an if statement that checked to see if the node myserver.js process was already running.

That way I was able to create a single command line option that both lets me keep the server going and also restart it when I have made changes, which is very helpful for development.

Adding elements to an xml file in C#

I've used XDocument.Root.Add to add elements. Root returns XElement which has an Add function for additional XElements

Output data with no column headings using PowerShell

A better answer is to leave your script as it was. When doing the Select name, follow it by -ExpandProperty Name like so:

Get-ADGroupMember 'Domain Admins' | Select Name -ExpandProperty Name | out-file Admins.txt

Is there a way to do repetitive tasks at intervals?

If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.

i.e.

package main

import "fmt"
import "time"

func main() {
    go heartBeat()
    time.Sleep(time.Second * 5)
}

func heartBeat() {
    for range time.Tick(time.Second * 1) {
        fmt.Println("Foo")
    }
}

Playground

Git Pull While Ignoring Local Changes?

For me the following worked:

(1) First fetch all changes:

$ git fetch --all

(2) Then reset the master:

$ git reset --hard origin/master

(3) Pull/update:

$ git pull

I forgot the password I entered during postgres installation

  1. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and find the following line:

    local   all             postgres                                md5
    
  2. Edit the line and change md5 at the end to trust and save the file

  3. Reload the postgresql service

    $ sudo service postgresql reload
    
  4. This will load the configuration files. Now you can modify the postgres user by logging into the psql shell

    $ psql -U postgres
    
  5. Update the postgres user's password

    alter user postgres with password 'secure-passwd-here';
    
  6. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and change trust back to md5 and save the file

  7. Reload the postgresql service

    $ sudo service postgresql reload
    
  8. Verify that the password change is working

    $ psql -U postgres -W
    

How do I disable a Pylint warning?

pylint --generate-rcfile shows it like this:

[MESSAGES CONTROL]

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
#disable=

So it looks like your ~/.pylintrc should have the disable= line/s in it inside a section [MESSAGES CONTROL].

Adding one day to a date

The modify() method that can be used to add increments to an existing DateTime value.

Create a new DateTime object with the current date and time:

$due_dt = new DateTime();

Once you have the DateTime object, you can manipulate its value by adding or subtracting time periods:

$due_dt->modify('+1 day');

You can read more on the PHP Manual.

How to generate sample XML documents from their DTD or XSD?

Liquid XML Studio has an XML Sample Generator wizard which will build sample XML files from an XML Schema. The resulting data seems to comply with the schema (it just can't generate data for regex patterns).

Generate an XML Sample from an XSD

Getting Google+ profile picture url with user_id

Approach 1: (no longer works)

https://plus.google.com/s2/photos/profile/<user_id>?sz=<your_desired_size>

Approach 2: (each request counts in your api rate limits which is 10k requests per day for free)

https://www.googleapis.com/plus/v1/people/<user_id>?fields=image&key={YOUR_API_KEY}

with the following response format:

{ "image": { "url": "lh5.googleusercontent.com/-keLR5zGxWOg/.../photo.jpg?sz=50"; } }

Approach 3: (donot require api key)

http://picasaweb.google.com/data/entry/api/user/<user_id>?alt=json

in the json response you get a property named "gphoto$thumbnail", which contains the profile picture url like the following:

http://lh6.ggpht.com/-btLsReiDeF0/AAAAAAAAAAI/AAAAAAAAAAA/GXBpycNk984/s64-c/filename.jpg

You may notice in the url the portion "s64-c" which means the image size to be 64, I've tried using other values like "s100-c" and they worked. Also if you remove the "s64-c" part and append the "?sz=100" parameter, that will also work as of now. Though this is not very good way of getting the profile picture of a gplus user, but the advantage is it do not require any api key.

How to set top position using jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

How can I download a specific Maven artifact in one command line?

With the latest version (2.8) of the Maven Dependency Plugin, downloading an artifact from the Maven Central Repository is as simple as:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=groupId:artifactId:version[:packaging[:classifier]]

where groupId:artifactId:version, etc. are the Maven coordinates

An example, tested with Maven 2.0.9, Maven 2.2.1, and Maven 3.0.4:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -Dartifact=org.hibernate:hibernate-entitymanager:3.4.0.GA:jar:sources

(Thanks to Pascal Thivent for providing his wonderful answer in the first place. I am adding another answer, because it wouldn't fit in a comment and it would be too extensive for an edit.)

In SQL Server, what does "SET ANSI_NULLS ON" mean?

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql

When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.

For e.g

DECLARE @TempVariable VARCHAR(10)
SET @TempVariable = NULL

SET ANSI_NULLS ON
SELECT 'NO ROWS IF SET ANSI_NULLS ON' where    @TempVariable = NULL
-- IF ANSI_NULLS ON , RETURNS ZERO ROWS


SET ANSI_NULLS OFF
SELECT 'THERE WILL BE A ROW IF ANSI_NULLS OFF' where    @TempVariable =NULL
-- IF ANSI_NULLS OFF , THERE WILL BE ROW !

How can I tell when HttpClient has timed out?

_httpClient = new HttpClient(handler) {Timeout = TimeSpan.FromSeconds(5)};

is what I usually do, seems to work out pretty good for me, its especially good when using proxies.

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

Get month name from number

For arbitaray range of month numbers

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.

How do you check if a JavaScript Object is a DOM Object?

Test if obj inherits from Node.

if (obj instanceof Node){
    // obj is a DOM Object
}

Node is a basic Interface from which HTMLElement and Text inherit.

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Input jQuery get old value before onchange and get value after on change

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

Clear listview content?

There is a solution for the duplicate entry in listview. You have to declare the onBackPress()-method on your activity and write down the highlight code given below:

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    **

    attendence_webdata.clear(); list.setAdapter(null);
    --------------------------------------------------

    **
 }

convert strtotime to date time format in php

FORMAT DATE STRTOTIME OR TIME STRING TO DATE FORMAT
$unixtime = 1307595105;
function formatdate($unixtime) 
{ 
        return $time = date("m/d/Y h:i:s",$unixtime);
} 

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I've experienced the same problem. The thing is that I forgot to start the apache and mysql in xampp... :S

Show spinner GIF during an $http request in AngularJS?

The following way will take note of all requests, and hide only once all requests are done:

_x000D_
_x000D_
app.factory('httpRequestInterceptor', function(LoadingService, requestCount) {_x000D_
    return {_x000D_
        request: function(config) {_x000D_
            if (!config.headers.disableLoading) {_x000D_
                requestCount.increase();_x000D_
                LoadingService.show();_x000D_
            }_x000D_
            return config;_x000D_
        }_x000D_
    };_x000D_
}).factory('httpResponseInterceptor', function(LoadingService, $timeout, error, $q, requestCount) {_x000D_
    function waitAndHide() {_x000D_
        $timeout(function() {_x000D_
            if (requestCount.get() === 0){_x000D_
                LoadingService.hide();_x000D_
            }_x000D_
            else{_x000D_
                waitAndHide();_x000D_
            }_x000D_
        }, 300);_x000D_
    }_x000D_
_x000D_
    return {_x000D_
        response: function(config) {_x000D_
            requestCount.descrease();_x000D_
            if (requestCount.get() === 0) {_x000D_
                waitAndHide();_x000D_
            }_x000D_
            return config;_x000D_
        },_x000D_
        responseError: function(config) {_x000D_
            requestCount.descrease();_x000D_
            if (requestCount.get() === 0) {_x000D_
                waitAndHide();_x000D_
            }_x000D_
            var deferred = $q.defer();_x000D_
            error.show(config.data, function() {_x000D_
                deferred.reject(config);_x000D_
            });_x000D_
            return deferred.promise;_x000D_
        }_x000D_
    };_x000D_
}).factory('requestCount', function() {_x000D_
    var count = 0;_x000D_
    return {_x000D_
        increase: function() {_x000D_
            count++;_x000D_
        },_x000D_
        descrease: function() {_x000D_
            if (count === 0) return;_x000D_
            count--;_x000D_
        },_x000D_
        get: function() {_x000D_
            return count;_x000D_
        }_x000D_
    };_x000D_
})
_x000D_
_x000D_
_x000D_

How to reduce the space between <p> tags?

I'll suggest to set padding and margin to 0.

If this does not solve your problem you can try playing with line-height even if not reccomended.

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

How to import an existing project from GitHub into Android Studio

Unzip the github project to a folder. Open Android Studio. Go to File -> New -> Import Project. Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.

P.S: In some versions of Android Studio a certain error occurs-
error:package android.support.v4.app does not exist.
To fix it go to Gradle Scripts->build.gradle(Module:app) and the add the dependecies:

dependencies {      
    compile fileTree(dir: 'libs', include: ['*.jar'])  
    compile 'com.android.support:appcompat-v7:21.0.3'  
}

Enjoy working in Android Studio

How to define custom sort function in javascript?

or shorter

_x000D_
_x000D_
function sortBy(field) {_x000D_
  return function(a, b) {_x000D_
    return (a[field] > b[field]) - (a[field] < b[field])_x000D_
  };_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
    {tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
    {tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
    {tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
    {tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
    {tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

Move to another EditText when Soft Keyboard Next is clicked on Android

In some cases you may need to move the focus to the next field manually :

focusSearch(FOCUS_DOWN).requestFocus();

You might need this if, for example, you have a text field that opens a date picker on click, and you want the focus to automatically move to the next input field once a date is selected by the user and the picker closes. There's no way to handle this in XML, it has to be done programmatically.

Android: Share plain text using intent (to all messaging apps)

This a great example about share with Intents in Android:

* Share with Intents in Android

//Share text:

Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(Intent.createChooser(intent2, "Share via"));

//via Email:

Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("message/rfc822");
intent2.putExtra(Intent.EXTRA_EMAIL, new String[]{EMAIL1, EMAIL2});
intent2.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(intent2);

//Share Files:

//Image:

boolean isPNG = (path.toLowerCase().endsWith(".png")) ? true : false;

Intent i = new Intent(Intent.ACTION_SEND);
//Set type of file
if(isPNG)
{
    i.setType("image/png");//With png image file or set "image/*" type
}
else
{
    i.setType("image/jpeg");
}

Uri imgUri = Uri.fromFile(new File(path));//Absolute Path of image
i.putExtra(Intent.EXTRA_STREAM, imgUri);//Uri of image
startActivity(Intent.createChooser(i, "Share via"));
break;

//APK:

File f = new File(path1);
if(f.exists())
{

   Intent intent2 = new Intent();
   intent2.setAction(Intent.ACTION_SEND);
   intent2.setType("application/vnd.android.package-archive");//APk file type  
   intent2.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );  
   startActivity(Intent.createChooser(intent2, "Share via"));
}
break;

net::ERR_INSECURE_RESPONSE in Chrome

This happens when you update from Chrome 55 to Chrome 56 (56.0.2924.87).
This is an increase in security enforcement.
It doesn't go away by restarting the browser, and it's not a bug.

Mountain View says it's hoping you don't ever encounter the message, because Certificate Authorities are required to stop issuing SHA-1 certificates in 2016. Just in case, Google plans to continue issuing warnings until Chrome completely stops supporting SHA-1 on January 1st, 2017. When that day comes, a website that still uses the function will trigger a fatal network error. (Source: Engadget.com)

If this happens, the most-likely cause is that your (or the website's) SSL-certificate uses SHA1.
SHA1 is broken, and SSL certificates using SHA1 are not secure anymore (it's now been a long time that Chrome showed this to you - now it blocks NET::ERR_CERT_WEAK_SIGNATURE_ALGORITHM).

Another likely cause is that your SSL-certificate expired
Also, you should disable backwards-compatiblity with SSL2 & SSL3 (Poodle Attack).
You should only be using TLS (SSL 3.1+).

To test your domain's SSL-certificate, you can use SSL labs SSL test.

To find out what exactly the issue is: Open the chrome developer console (CTRL + SHIFT + J OR F12) And change to the security tab

Security

Console

Details

For more information:
https://support.google.com/chrome/answer/95617?visit_id=1-636221396724527190-3454695657&p=ui_security_indicator&rd=1

FYI:

SHA-1 has been growing weaker and more insecure everyday for a decade now, which is dangerous considering we tend to trust websites with "https://" in their URLs. Other browsers like Mozilla Firefox and Microsoft Edge also plan to stop supporting it in an effort to encourage website owners to switch to more secure SHA-2 certificates as soon as possible.

If you urgently need to get around it (you need to close all running instances of Chrome first - otherwise it won't work):

chrome --args --ignore-certificate-errors

Please note: don't go online-banking or gmail'ing with those command-line settings active in your Chrome instance.

Javascript get object key name

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

Trim characters in Java

You could use removeStart and removeEnd from Apache Commons Lang StringUtils

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Code for download video from Youtube on Java, Android

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

CSS to select/style first word

There isn't a plain CSS method for this. You might have to go with JavaScript + Regex to pop in a span.

Ideally, there would be a pseudo-element for first-word, but you're out of luck as that doesn't appear to work. We do have :first-letter and :first-line.

You might be able to use a combination of :after or :before to get at it without using a span.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

You can also use SET instead of DECLARE

SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);

SELECT myvar;

Simple java program of pyramid

public static void printPyramid(int number) {
    int size = 5;
    for (int k = 1; k <= size; k++) {
        for (int i = (size+2); i > k; i--) {
            System.out.print(" ");
        }
        for (int j = 1; j <= k; j++) {
            System.out.print(" *");
        }
        System.out.println();
    }
}

Find size of object instance in bytes in c#

You can use reflection to gather all the public member or property information (given the object's type). There is no way to determine the size without walking through each individual piece of data on the object, though.

How to use ArrayList.addAll()?

Collections.addAll is what you want.

Collections.addAll(myArrayList, '+', '-', '*', '^');

Another option is to pass the list into the constructor using Arrays.asList like this:

List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^'));

If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...). Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.

Get HTML code from website in C#

Try this solution. It works fine.

 try{
        String url = textBox1.Text;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(sr);
        var aTags = doc.DocumentNode.SelectNodes("//a");
        int counter = 1;
        if (aTags != null)
        {
            foreach (var aTag in aTags)
            {
                richTextBox1.Text +=  aTag.InnerHtml +  "\n" ;
                counter++;
            }
        }
        sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to retrieve related keywords." + ex);
        }

linux: kill background task

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

Save modifications in place with awk

Using tee

 awk '{awk code}' file | tee file

the tee command take place and executed after the awk command is finished due to the |.

How to run cron once, daily at 10pm

To run once, daily at 10PM you should do something like this:

0 22 * * *

enter image description here

Full size image: http://i.stack.imgur.com/BeXHD.jpg

Source: softpanorama.org

Linq: GroupBy, Sum and Count

I don't understand where the first "result with sample data" is coming from, but the problem in the console app is that you're using SelectMany to look at each item in each group.

I think you just want:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

The use of First() here to get the product name assumes that every product with the same product code has the same product name. As noted in comments, you could group by product name as well as product code, which will give the same results if the name is always the same for any given code, but apparently generates better SQL in EF.

I'd also suggest that you should change the Quantity and Price properties to be int and decimal types respectively - why use a string property for data which is clearly not textual?

Running windows shell commands with python

Refactoring of @srini-beerge's answer which gets the output and the return code

import subprocess
def run_win_cmd(cmd):
    result = []
    process = subprocess.Popen(cmd,
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    for line in process.stdout:
        result.append(line)
    errcode = process.returncode
    for line in result:
        print(line)
    if errcode is not None:
        raise Exception('cmd %s failed, see above for details', cmd)

Converting double to string

double.toString() should work. Not the variable type Double, but the variable itself double.

How to get the current directory of the cmdlet being executed

Most answers don't work when debugging in the following IDEs:

  • PS-ISE (PowerShell ISE)
  • VS Code (Visual Studio Code)

Because in those the $PSScriptRoot is empty and Resolve-Path .\ (and similars) will result in incorrect paths.

Freakydinde's answer is the only one that resolves those situations, so I up-voted that, but I don't think the Set-Location in that answer is really what is desired. So I fixed that and made the code a little clearer:

$directorypath = if ($PSScriptRoot) { $PSScriptRoot } `
    elseif ($psise) { split-path $psise.CurrentFile.FullPath } `
    elseif ($psEditor) { split-path $psEditor.GetEditorContext().CurrentFile.Path }

How can I tell gcc not to inline a function?

Use the noinline attribute:

int func(int arg) __attribute__((noinline))
{
}

You should probably use it both when you declare the function for external use and when you write the function.

Get class list for element with jQuery

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);

What is "String args[]"? parameter in main method Java

String [] args is also how you declare an array of Strings in Java.

In this method signature, the array args will be filled with values when the method is called (as the other examples here show). Since you're learning though, it's worth understanding that this args array is just like if you created one yourself in a method, as in this:

public void foo() {
    String [] args = new String[2];
    args[0] = "hello";
    args[1] = "every";

    System.out.println("Output: " + args[0] + args[1]);

    // etc... the usage of 'args' here and in the main method is identical
}

CSS rounded corners in IE8

As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.

You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/

ERROR: Cannot open source file " "

You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h resides, the other issue could be that GameEngine.h is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA and ProjectB, if you are including GameEngine.h in some source/header file in ProjectA then to include it properly, assuming that ProjectB is in the same parent folder do this:

include "../ProjectB/GameEngine.h"

This is if you have a structure like this:

Root\ProjectA

Root\ProjectB <- GameEngine.h actually lives here

Capitalize the first letter of both words in a two word string

This gives capital Letters to all major words

library(lettercase)
xString = str_title_case(xString)

I want to convert std::string into a const wchar_t *

If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).

  • mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.

  • wcs stand for Wide Char String and is an array of wchar_t.

For more background details on wide chars have a look at glibc documentation here.

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

Fixed point vs Floating point number

A fixed point number just means that there are a fixed number of digits after the decimal point. A floating point number allows for a varying number of digits after the decimal point.

For example, if you have a way of storing numbers that requires exactly four digits after the decimal point, then it is fixed point. Without that restriction it is floating point.

Often, when fixed point is used, the programmer actually uses an integer and then makes the assumption that some of the digits are beyond the decimal point. For example, I might want to keep two digits of precision, so a value of 100 means actually means 1.00, 101 means 1.01, 12345 means 123.45, etc.

Floating point numbers are more general purpose because they can represent very small or very large numbers in the same way, but there is a small penalty in having to have extra storage for where the decimal place goes.

C# Macro definitions in Preprocessor

I would suggest you to write extension, something like below.

public static class WriteToConsoleExtension
{
   // Extension to all types
   public static void WriteToConsole(this object instance, 
                                     string format, 
                                     params object[] data)
   {
       Console.WriteLine(format, data);
   }
}

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        // Usage of extension
        p.WriteToConsole("Test {0}, {1}", DateTime.Now, 1);
    }
}

Hope this helps (and not too late :) )

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

To remove & delete all changes git clean -d -f

Facebook page automatic "like" URL (for QR Code)

Have you tried using the fb:// protocol?

To have them like your page when they scan the qr code, it goes like this:

fb://page/(pageID)/addfan

If you need to get the pageID, replace "www" with "graph" in the Facebook url when you visit your page in a desktop browser and it will display the ID and other data.

Not only does this add them automatically, but it opens up the page in the FB app instead of the mobile browser.

As far as legality, I would assume as long as you put something like "Scan to like our page", you're in the clear. They know what they're getting into.

Change navbar color in Twitter Bootstrap

Do you have to change the CSS directly? What about...

<nav class="navbar navbar-inverse" style="background-color: #333399;">
<div class="container-fluid">
<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>                        
  </button>
  <a class="navbar-brand" href="#">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Projects</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
  <ul class="nav navbar-nav navbar-right">
    <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
  </ul>
</div>

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

You should add namespace if you are not using it:

System.Windows.Forms.MessageBox.Show("Some text", "Some title", 
    System.Windows.Forms.MessageBoxButtons.OK, 
    System.Windows.Forms.MessageBoxIcon.Error);

Alternatively, you can add at the begining of your file:

using System.Windows.Forms

and then use (as stated in previous answers):

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

How does MySQL process ORDER BY and LIMIT in a query?

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

All details on: http://dev.mysql.com/doc/refman/5.0/en/select.html

How to get the index of an element in an IEnumerable?

A bit late in the game, i know... but this is what i recently did. It is slightly different than yours, but allows the programmer to dictate what the equality operation needs to be (predicate). Which i find very useful when dealing with different types, since i then have a generic way of doing it regardless of object type and <T> built in equality operator.

It also has a very very small memory footprint, and is very, very fast/efficient... if you care about that.

At worse, you'll just add this to your list of extensions.

Anyway... here it is.

 public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate)
 {
     int retval = -1;
     var enumerator = source.GetEnumerator();

     while (enumerator.MoveNext())
     {
         retval += 1;
         if (predicate(enumerator.Current))
         {
             IDisposable disposable = enumerator as System.IDisposable;
             if (disposable != null) disposable.Dispose();
             return retval;
         }
     }
     IDisposable disposable = enumerator as System.IDisposable;
     if (disposable != null) disposable.Dispose();
     return -1;
 }

Hopefully this helps someone.

Add Header and Footer for PDF using iTextsharp

As already answered by @Bruno you need to use pageEvents.

Please check out the sample code below:

private void CreatePDF()
{
    string fileName = string.Empty;    
    DateTime fileCreationDatetime = DateTime.Now;    
    fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));    
    string pdfPath = Server.MapPath(@"~\PDFs\") +   fileName;

    using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
    {
        //step 1
        using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
        {
            try
            {
                // step 2
                PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                pdfWriter.PageEvent = new Common.ITextEvents();

                //open the stream 
                pdfDoc.Open();

                for (int i = 0; i < 10; i++)
                {
                    Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));    
                    para.Alignment = Element.ALIGN_CENTER;    
                    pdfDoc.Add(para);    
                    pdfDoc.NewPage();
                }

                pdfDoc.Close();    
            }
            catch (Exception ex)
            {
                //handle exception
            }    
            finally
            { 
            }    
        }    
    }
}

And create one class file named ITextEvents.cs and add following code:

public class ITextEvents : PdfPageEventHelper
{    
    // This is the contentbyte object of the writer
    PdfContentByte cb;

    // we will put the final number of pages in a template
    PdfTemplate headerTemplate, footerTemplate;

    // this is the BaseFont we are going to use for the header / footer
    BaseFont bf = null;

    // This keeps track of the creation time
    DateTime PrintTime = DateTime.Now;    

    #region Fields
    private string _header;
    #endregion

    #region Properties
    public string Header
    {
        get { return _header; }
        set { _header = value; }
    }
    #endregion    

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        try
        {
            PrintTime = DateTime.Now;
            bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb = writer.DirectContent;
            headerTemplate = cb.CreateTemplate(100, 100);
            footerTemplate = cb.CreateTemplate(50, 50);
        }
        catch (DocumentException de)
        {    
        }
        catch (System.IO.IOException ioe)
        {    
        }
    }

    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
    {
        base.OnEndPage(writer, document);    
        iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);    
        iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);    
        Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);

        //Create PdfTable object
        PdfPTable pdfTab = new PdfPTable(3);

        //We will have to create separate cells to include image logo and 2 separate strings
        //Row 1
        PdfPCell pdfCell1 = new PdfPCell();
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell();
        String text = "Page " + writer.PageNumber + " of ";    

        //Add paging to header
        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            //Adds "12" in Page 1 of 12
            cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
        }
        //Add paging to footer
        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
        }

        //Row 2
        PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));

        //Row 3 
        PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
        PdfPCell pdfCell6 = new PdfPCell();
        PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));    

        //set the alignment of all three cells and set border to 0
        pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;    

        pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
        pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
        pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;    

        pdfCell4.Colspan = 3;  

        pdfCell1.Border = 0;
        pdfCell2.Border = 0;
        pdfCell3.Border = 0;
        pdfCell4.Border = 0;
        pdfCell5.Border = 0;
        pdfCell6.Border = 0;
        pdfCell7.Border = 0;    

        //add all three cells into PdfTable
        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        pdfTab.AddCell(pdfCell4);
        pdfTab.AddCell(pdfCell5);
        pdfTab.AddCell(pdfCell6);
        pdfTab.AddCell(pdfCell7);

        pdfTab.TotalWidth = document.PageSize.Width - 80f;
        pdfTab.WidthPercentage = 70;
        //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;    

        //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
        //first param is start row. -1 indicates there is no end row and all the rows to be included to write
        //Third and fourth param is x and y position to start writing
        pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
        //set pdfContent value

        //Move the pointer and draw line to separate header section from rest of page
        cb.MoveTo(40, document.PageSize.Height - 100);
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
        cb.Stroke();

        //Move the pointer and draw line to separate footer section from rest of page
        cb.MoveTo(40, document.PageSize.GetBottom(50) );
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
        cb.Stroke();
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);

        headerTemplate.BeginText();
        headerTemplate.SetFontAndSize(bf, 12);
        headerTemplate.SetTextMatrix(0, 0);
        headerTemplate.ShowText((writer.PageNumber - 1).ToString());
        headerTemplate.EndText();

        footerTemplate.BeginText();
        footerTemplate.SetFontAndSize(bf, 12);
        footerTemplate.SetTextMatrix(0, 0);
        footerTemplate.ShowText((writer.PageNumber - 1).ToString());
        footerTemplate.EndText();  
    }
}

I hope it helps!

Finalize vs Dispose

There're some keys about from the book MCSD Certification Toolkit (exam 70-483) pag 193:

destructor ˜(it's almost equal to) base.Finalize(), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. Then its totally non deterministic you can't able to know when will be called because depends on GC.

If a class contains no managed resources and no unmanaged resources, it shouldn't implement IDisposable or have a destructor.

If the class has only managed resources, it should implement IDisposable but it shouldn't have a destructor. (When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose() methods anyway.)

If the class has only unmanaged resources, it needs to implement IDisposable and needs a destructor in case the program doesn’t call Dispose().

Dispose() method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.

Dispose() should free both managed and unmanaged resources.

The destructor should free only unmanaged resources. When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose methods anyway. This is obtained by using the canonical protected void Dispose(bool disposing) pattern, where only managed resources are freed (disposed) when disposing == true.

After freeing resources, Dispose() should call GC.SuppressFinalize, so the object can skip the finalization queue.

An Example of a an implementation for a class with unmanaged and managed resources:

using System;

class DisposableClass : IDisposable
{
    // A name to keep track of the object.
    public string Name = "";

    // Free managed and unmanaged resources.
    public void Dispose()
    {
        FreeResources(true);

        // We don't need the destructor because
        // our resources are already freed.
        GC.SuppressFinalize(this);
    }

    // Destructor to clean up unmanaged resources
    // but not managed resources.
    ~DisposableClass()
    {
        FreeResources(false);
    }

    // Keep track if whether resources are already freed.
    private bool ResourcesAreFreed = false;

    // Free resources.
    private void FreeResources(bool freeManagedResources)
    {
        Console.WriteLine(Name + ": FreeResources");
        if (!ResourcesAreFreed)
        {
            // Dispose of managed resources if appropriate.
            if (freeManagedResources)
            {
                // Dispose of managed resources here.
                Console.WriteLine(Name + ": Dispose of managed resources");
            }

            // Dispose of unmanaged resources here.
            Console.WriteLine(Name + ": Dispose of unmanaged resources");

            // Remember that we have disposed of resources.
            ResourcesAreFreed = true;
        }
    }
}

Javascript Date: next month

If you are able to get your hands on date-fns library v2+, you can import the function addMonths, and use that to get the next month

_x000D_
_x000D_
<script type="module">
  import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm'; 
  
  const current = new Date();
  const nextMonth = addMonths(current, 1);
  console.log(`Next month is ${nextMonth}`);
</script>
_x000D_
_x000D_
_x000D_

Generate a sequence of numbers in Python

Includes some guessing on the exact sequence you are expecting:

>>> l = list(range(1, 100, 4)) + list(range(2, 100, 4))
>>> l.sort()
>>> ','.join(map(str, l))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'

As one-liner:

>>> ','.join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))

(btw. this is Python 3 compatible)

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

How do you overcome the svn 'out of date' error?

Perform the move directly in the repository.

forEach() in React JSX does not output any HTML

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;

Byte Array in Python

An alternative that also has the added benefit of easily logging its output:

hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)

allows you to do easy substitutions like so:

hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)

"import datetime" v.s. "from datetime import datetime"

try this:

import datetime
from datetime import datetime as dt

today_date = datetime.date.today()
date_time = dt.strptime(date_time_string, '%Y-%m-%d %H:%M')

strp() doesn't exist. I think you mean strptime.

Java - Convert image to Base64

I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

public class Base64Example {

    public static void main(String[] args) {

        Base64Example tempObject = new Base64Example();

        // convert file to regular byte array
        byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");

        // encoded file in Base64
        byte[] encodedFile = Base64.encodeBase64(codedFile);

        // print out the byte array
        System.out.println(Arrays.toString(encodedFile));

        // print the encoded String
        System.out.println(encodedFile);

        // decode file back to regular byte array
        byte[] decodedByteArray = Base64.decodeBase64(encodedFile);

        // save decoded byte array to a file
        boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);

        // print out success
        System.out.println("success : " + success);
    }

    public byte[] convertFileToByteArray(String filePath) {

        Path path = Paths.get(filePath);

        byte[] codedFile = null;

        try {
            codedFile = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return codedFile;
    }

    public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {

        boolean success = false;

        Path path = Paths.get(filePath);

        try {
            Files.write(path, decodedByteArray);
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success;
    }
}

Repeat a string in JavaScript a number of times

/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..

 if (model is ViewDataDictionary)
 {
     controller.ViewData = model as ViewDataDictionary;
 } else {
     controller.ViewData.Model = model;
 }

How to create an instance of System.IO.Stream stream

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

Editing dictionary values in a foreach loop

Call the ToList() in the foreach loop. This way we dont need a temp variable copy. It depends on Linq which is available since .Net 3.5.

using System.Linq;

foreach(string key in colStates.Keys.ToList())
{
  double  Percent = colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

How do you access the matched groups in a JavaScript regular expression?

I you are like me and wish regex would return an Object like this:

{
    match: '...',
    matchAtIndex: 0,
    capturedGroups: [ '...', '...' ]
}

then snip the function from below

_x000D_
_x000D_
/**_x000D_
 * @param {string | number} input_x000D_
 *          The input string to match_x000D_
 * @param {regex | string}  expression_x000D_
 *          Regular expression _x000D_
 * @param {string} flags_x000D_
 *          Optional Flags_x000D_
 * _x000D_
 * @returns {array}_x000D_
 * [{_x000D_
    match: '...',_x000D_
    matchAtIndex: 0,_x000D_
    capturedGroups: [ '...', '...' ]_x000D_
  }]     _x000D_
 */_x000D_
function regexMatch(input, expression, flags = "g") {_x000D_
  let regex = expression instanceof RegExp ? expression : new RegExp(expression, flags)_x000D_
  let matches = input.matchAll(regex)_x000D_
  matches = [...matches]_x000D_
  return matches.map(item => {_x000D_
    return {_x000D_
      match: item[0],_x000D_
      matchAtIndex: item.index,_x000D_
      capturedGroups: item.length > 1 ? item.slice(1) : undefined_x000D_
    }_x000D_
  })_x000D_
}_x000D_
_x000D_
let input = "key1:value1, key2:value2 "_x000D_
let regex = /(\w+):(\w+)/g_x000D_
_x000D_
let matches = regexMatch(input, regex)_x000D_
_x000D_
console.log(matches)
_x000D_
_x000D_
_x000D_

Functional programming vs Object Oriented programming

  1. If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.

  2. In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.

How to get numbers after decimal point?

5.55 % 1

Keep in mind this won't help you with floating point rounding problems. I.e., you may get:

0.550000000001

Or otherwise a little off the 0.55 you are expecting.