Programs & Examples On #Zfdoctrine

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:


static class Program
{
    public static Form1 form1; // = new Form1(); // Place this var out of the constructor

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form1 = new Form1()); } }

HTML5 Local storage vs. Session storage

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

How to save a data frame as CSV to a user selected location using tcltk

Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:

write.csv(x=df, file="myFileName")

How do you format a Date/Time in TypeScript?

function _formatDatetime(date: Date, format: string) {
   const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
    .replace(/yyyy/g, _padStart(date.getFullYear()))
    .replace(/dd/g, _padStart(date.getDate()))
    .replace(/mm/g, _padStart(date.getMonth() + 1))
    .replace(/hh/g, _padStart(date.getHours()))
    .replace(/ii/g, _padStart(date.getMinutes()))
    .replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
    return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
    var datetime = new Date(date);
    return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

Java String array: is there a size of method?

If you want a function to do this

Object array = new String[10];
int size = Array.getlength(array);

This can be useful if you don't know what type of array you have e.g. int[], byte[] or Object[].

What does the @Valid annotation indicate in Spring?

I wanted to add more details about how the @Valid works, especially in spring.

Everything you'd want to know about validation in spring is explained clearly and in detail in https://reflectoring.io/bean-validation-with-spring-boot/, but I'll copy the answer to how @Valid works incase the link goes down.

The @Valid annotation can be added to variables in a rest controller method to validate them. There are 3 types of variables that can be validated:

  • the request body,
  • variables within the path (e.g. id in /foos/{id}) and,
  • query parameters.

So now... how does spring "validate"? You can define constraints to the fields of a class by annotating them with certain annotations. Then, you pass an object of that class into a Validator which checks if the constraints are satisfied.

For example, suppose I had controller method like this:

@RestController
class ValidateRequestBodyController {

  @PostMapping("/validateBody")
  ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
    return ResponseEntity.ok("valid");
  }

}

So this is a POST request which takes in a response body, and we're mapping that response body to a class Input.

Here's the class Input:

class Input {

  @Min(1)
  @Max(10)
  private int numberBetweenOneAndTen;

  @Pattern(regexp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$")
  private String ipAddress;
  
  // ...
}

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations. It'll also check to make sure the ip address passed in matches the regular expression in the annotation.

side note: the regular expression isn't perfect.. you could pass in 3 digit numbers that are greater than 255 and it would still match the regular expression.


Here's an example of validating a query variable and path variable:

@RestController
@Validated
class ValidateParametersController {

  @GetMapping("/validatePathVariable/{id}")
  ResponseEntity<String> validatePathVariable(
      @PathVariable("id") @Min(5) int id) {
    return ResponseEntity.ok("valid");
  }
  
  @GetMapping("/validateRequestParameter")
  ResponseEntity<String> validateRequestParameter(
      @RequestParam("param") @Min(5) int param) { 
    return ResponseEntity.ok("valid");
  }
}

In this case, since the query variable and path variable are just integers instead of just complex classes, we put the constraint annotation @Min(5) right on the parameter instead of using @Valid.

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Javascript: Load an Image from url and display

You have to right idea generating the url based off of the input value. The only issue is you are using window.location.href. Setting window.location.href changes the url of the current window. What you probably want to do is change the src attribute of an image.

<html>
<body>
<form>
  <input type="text" value="" id="imagename">
  <input type="button" onclick="var image = document.getElementById('the-image'); image.src='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
<img id="the-image">
</body>
</html>

Python import csv to list

Using the csv module:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

If you need tuples:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = [tuple(row) for row in reader]

print(data)

Output:

[('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]

Old Python 2 answer, also using the csv module:

import csv
with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print your_list
# [['This is the first line', 'Line1'],
#  ['This is the second line', 'Line2'],
#  ['This is the third line', 'Line3']]

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

Android: Expand/collapse animation

@Tom Esterez's answer, but updated to use view.measure() properly per Android getMeasuredHeight returns wrong values !

    // http://easings.net/
    Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);

    public static Animation expand(final View view) {
        int matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
        int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
        final int targetHeight = view.getMeasuredHeight();

        // Older versions of android (pre API 21) cancel animations for views with a height of 0 so use 1 instead.
        view.getLayoutParams().height = 1;
        view.setVisibility(View.VISIBLE);

        Animation animation = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

               view.getLayoutParams().height = interpolatedTime == 1
                    ? ViewGroup.LayoutParams.WRAP_CONTENT
                    : (int) (targetHeight * interpolatedTime);

            view.requestLayout();
        }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        animation.setInterpolator(easeInOutQuart);
        animation.setDuration(computeDurationFromHeight(view));
        view.startAnimation(animation);

        return animation;
    }

    public static Animation collapse(final View view) {
        final int initialHeight = view.getMeasuredHeight();

        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    view.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        a.setInterpolator(easeInOutQuart);

        int durationMillis = computeDurationFromHeight(view);
        a.setDuration(durationMillis);

        view.startAnimation(a);

        return a;
    }

    private static int computeDurationFromHeight(View view) {
        // 1dp/ms * multiplier
        return (int) (view.getMeasuredHeight() / view.getContext().getResources().getDisplayMetrics().density);
    }

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

Subscripts in plots in R

Another example, expression works for negative superscripts without the need for quotes around the negative number:

title(xlab=expression("Nitrate Loading in kg ha"^-1*"yr"^-1))

and you only need the * to separate sections as mentioned above (when you write a superscript or subscript and need to add more text to the expression after).

Bash Templating: How to build configuration files from templates with Bash?

If using Perl is an option and you're content with basing expansions on environment variables only (as opposed to all shell variables), consider Stuart P. Bentley's robust answer.

This answer aims to provide a bash-only solution that - despite use of eval - should be safe to use.

The goals are:

  • Support expansion of both ${name} and $name variable references.
  • Prevent all other expansions:
    • command substitutions ($(...) and legacy syntax `...`)
    • arithmetic substitutions ($((...)) and legacy syntax $[...]).
  • Allow selective suppression of variable expansion by prefixing with \ (\${name}).
  • Preserve special chars. in the input, notably " and \ instances.
  • Allow input either via arguments or via stdin.

Function expandVars():

expandVars() {
  local txtToEval=$* txtToEvalEscaped
  # If no arguments were passed, process stdin input.
  (( $# == 0 )) && IFS= read -r -d '' txtToEval
  # Disable command substitutions and arithmetic expansions to prevent execution
  # of arbitrary commands.
  # Note that selectively allowing $((...)) or $[...] to enable arithmetic
  # expressions is NOT safe, because command substitutions could be embedded in them.
  # If you fully trust or control the input, you can remove the `tr` calls below
  IFS= read -r -d '' txtToEvalEscaped < <(printf %s "$txtToEval" | tr '`([' '\1\2\3')
  # Pass the string to `eval`, escaping embedded double quotes first.
  # `printf %s` ensures that the string is printed without interpretation
  # (after processing by by bash).
  # The `tr` command reconverts the previously escaped chars. back to their
  # literal original.
  eval printf %s "\"${txtToEvalEscaped//\"/\\\"}\"" | tr '\1\2\3' '`(['
}

Examples:

$ expandVars '\$HOME="$HOME"; `date` and $(ls)'
$HOME="/home/jdoe"; `date` and $(ls)  # only $HOME was expanded

$ printf '\$SHELL=${SHELL}, but "$(( 1 \ 2 ))" will not expand' | expandVars
$SHELL=/bin/bash, but "$(( 1 \ 2 ))" will not expand # only ${SHELL} was expanded
  • For performance reasons, the function reads stdin input all at once into memory, but it's easy to adapt the function to a line-by-line approach.
  • Also supports non-basic variable expansions such as ${HOME:0:10}, as long as they contain no embedded command or arithmetic substitutions, such as ${HOME:0:$(echo 10)}
    • Such embedded substitutions actually BREAK the function (because all $( and ` instances are blindly escaped).
    • Similarly, malformed variable references such as ${HOME (missing closing }) BREAK the function.
  • Due to bash's handling of double-quoted strings, backslashes are handled as follows:
    • \$name prevents expansion.
    • A single \ not followed by $ is preserved as is.
    • If you want to represent multiple adjacent \ instances, you must double them; e.g.:
      • \\ -> \ - the same as just \
      • \\\\ -> \\
    • The input mustn't contain the following (rarely used) characters, which are used for internal purposes: 0x1, 0x2, 0x3.
  • There's a largely hypothetical concern that if bash should introduce new expansion syntax, this function might not prevent such expansions - see below for a solution that doesn't use eval.

If you're looking for a more restrictive solution that only supports ${name} expansions - i.e., with mandatory curly braces, ignoring $name references - see this answer of mine.


Here is an improved version of the bash-only, eval-free solution from the accepted answer:

The improvements are:

  • Support for expansion of both ${name} and $name variable references.
  • Support for \-escaping variable references that shouldn't be expanded.
  • Unlike the eval-based solution above,
    • non-basic expansions are ignored
    • malformed variable references are ignored (they don't break the script)
 IFS= read -d '' -r lines # read all input from stdin at once
 end_offset=${#lines}
 while [[ "${lines:0:end_offset}" =~ (.*)\$(\{([a-zA-Z_][a-zA-Z_0-9]*)\}|([a-zA-Z_][a-zA-Z_0-9]*))(.*) ]] ; do
      pre=${BASH_REMATCH[1]} # everything before the var. reference
      post=${BASH_REMATCH[5]}${lines:end_offset} # everything after
      # extract the var. name; it's in the 3rd capture group, if the name is enclosed in {...}, and the 4th otherwise
      [[ -n ${BASH_REMATCH[3]} ]] && varName=${BASH_REMATCH[3]} || varName=${BASH_REMATCH[4]}
      # Is the var ref. escaped, i.e., prefixed with an odd number of backslashes?
      if [[ $pre =~ \\+$ ]] && (( ${#BASH_REMATCH} % 2 )); then
           : # no change to $lines, leave escaped var. ref. untouched
      else # replace the variable reference with the variable's value using indirect expansion
           lines=${pre}${!varName}${post}
      fi
      end_offset=${#pre}
 done
 printf %s "$lines"

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Get week number (in the year) from a date PHP

for get week number in jalai calendar you can use this:

$weeknumber = date("W"); //number week in year
$dayweek = date("w"); //number day in week
if ($dayweek == "6")
{
    $weeknumberint = (int)$weeknumber;
    $date2int++; 
    $weeknumber = (string)$date2int;
}

echo $date2;

result:

15

week number change in saturday

Removing elements from an array in C

What solution you need depends on whether you want your array to retain its order, or not.

Generally, you never only have the array pointer, you also have a variable holding its current logical size, as well as a variable holding its allocated size. I'm also assuming that the removeIndex is within the bounds of the array. With that given, the removal is simple:

Order irrelevant

array[removeIndex] = array[--logicalSize];

That's it. You simply copy the last array element over the element that is to be removed, decrementing the logicalSize of the array in the process.

If removeIndex == logicalSize-1, i.e. the last element is to be removed, this degrades into a self-assignment of that last element, but that is not a problem.

Retaining order

memmove(array + removeIndex, array + removeIndex + 1, (--logicalSize - removeIndex)*sizeof(*array));

A bit more complex, because now we need to call memmove() to perform the shifting of elements, but still a one-liner. Again, this also updates the logicalSize of the array in the process.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Change your 'a' and 'b' values to a list, as follows:

a = [2]
b = [3]

then execute the same code as follows:

df2 = pd.DataFrame({'A':a,'B':b})
df2

and you'll get:

    A   B
0   2   3

Adding to the classpath on OSX

In OSX, you can set the classpath from scratch like this:

export CLASSPATH=/path/to/some.jar:/path/to/some/other.jar

Or you can add to the existing classpath like this:

export CLASSPATH=$CLASSPATH:/path/to/some.jar:/path/to/some/other.jar

This is answering your exact question, I'm not saying it's the right or wrong thing to do; I'll leave that for others to comment upon.

Attempted to read or write protected memory

In my case this was fixed when I set up 'Enable 32 Bit applications'=True for Application pool in IIS server.

Firebug-like debugger for Google Chrome

Firebug Lite supports to inspect HTML elements, computed CSS style, and a lot more. Since it's pure JavaScript, it works in many different browsers. Just include the script in your source, or add the bookmarklet to your bookmark bar to include it on any page with a single click.

http://getfirebug.com/lite.html

Docker - Cannot remove dead container

Try running the following commands. It always works for me.

# docker volume rm $(docker volume ls -qf dangling=true)
# docker rm $(docker ps -q -f 'status=exited')

After execution of the above commands, restart docker by,

# service docker restart

Javascript "Not a Constructor" Exception while creating objects

I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with

module.exports = NAME_OF_CONSTRUCTOR

will also cause the "Not a constructor" exception.

Is Google Play Store supported in avd emulators?

When creating AVD,

  1. Pick a device with google play icon.

enter image description here

  1. Pick the google play version of the image, of your desired API level.

enter image description here

Now, after creating the AVD, you should see the google play icon .

enter image description here

How do I convert datetime.timedelta to minutes, hours in Python?

A datetime.timedelta corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).

If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:

x = datetime.timedelta(1, 5, 41038)  # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60

Is there a typical state machine implementation pattern?

There is a book titled Practical Statecharts in C/C++. However, it is way too heavyweight for what we need.

Cannot perform runtime binding on a null reference, But it is NOT a null reference

Set

 Dictionary<int, string> states = new Dictionary<int, string>()

as a property outside the function and inside the function insert the entries, it should work.

WooCommerce return product object by id

Alright, I deserve to be throttled. definitely an RTM but not for WooCommerce, for Wordpress. Solution found due to a JOLT cola (all hail JOLT cola).

TASK: Field named 'related_product_ids' added to a custom post type. So when that post is displayed mini product displays can be displayed with it.

PROBLEM: Was having a problem getting the multiple ids returned via WP_Query.

SOLUTION:

$related_id_list          = get_post_custom_values('related_product_ids');
    // Get comma delimited list from current post
$related_product_ids      = explode(",", trim($related_id_list[0],','));
    // Return an array of the IDs ensure no empty array elements from extra commas
$related_product_post_ids = array( 'post_type' => 'product', 
                                   'post__in'  => $related_product_ids,
                                   'meta_query'=> array( 
                                        array( 'key'    => '_visibility',
                                               'value'  => array('catalog', 'visible'),'compare' => 'IN'
                                        )
                            ) 
);      
    // Query to get all product posts matching given IDs provided it is a published post
$loop = new WP_Query( $related_posts );
    // Execute query
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
    // Do stuff here to display your products 
endwhile;

Thank you for anyone who may have spent some time on this.

Tim

git ignore vim temporary files

Alternatively you can configure vim to save the swapfiles to a separate location, e.g. by adding lines similar to the following to your .vimrc file:

set backupdir=$TEMP//
set directory=$TEMP//

See this vim tip for more info.

How do I check if a column is empty or null in MySQL?

Check for null

$column is null
isnull($column)

Check for empty

$column != ""

However, you should always set NOT NULL for column,
mysql optimization can handle only one IS NULL level

Encode html entities in javascript

Sometimes you just want to encode every character... This function replaces "everything but nothing" in regxp.

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

_x000D_
_x000D_
function encode(w) {_x000D_
  return w.replace(/[^]/g, function(w) {_x000D_
    return "&#" + w.charCodeAt(0) + ";";_x000D_
  });_x000D_
}_x000D_
_x000D_
test.value=encode(document.body.innerHTML.trim());
_x000D_
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>
_x000D_
_x000D_
_x000D_

UIView Infinite 360 degree rotation animation?

I has developed a shiny animation framework which can save you tone of time! Using it this animation can be created very easily:

private var endlessRotater: EndlessAnimator!
override func viewDidAppear(animated: Bool) 
{
    super.viewDidAppear(animated)
    let rotationAnimation = AdditiveRotateAnimator(M_PI).to(targetView).duration(2.0).baseAnimation(.CurveLinear)
    endlessRotater = EndlessAnimator(rotationAnimation)
    endlessRotater.animate()
}

to stop this animation simply set nil to endlessRotater.

If you are interested, please take a look: https://github.com/hip4yes/Animatics

Can't access Tomcat using IP address

Firewalls are often the problem in these situations. Personally, the Mcafee enterprise firewall was causing this issue even for requests within the network.

Disable your firewalls or add a rule for tomcat and see if this helps.

How to find the port for MS SQL Server 2008?

Here are 5 methodes i found:

  • Method 1: SQL Server Configuration Manager
  • Method 2: Windows Event Viewer
  • Method 3: SQL Server Error Logs
  • Method 4: sys.dm_exec_connections DMV
  • Method 5: Reading registry using xp_instance_regread

Method 4: sys.dm_exec_connections DMV
I think this is almost the easiest way...
DMVs return server state that can be used to monitor SQL Server Instance. We can use sys.dm_exec_connections DMV to identify the port number SQL Server Instance is listening on using below T-SQL code:

SELECT local_tcp_port
FROM   sys.dm_exec_connections
WHERE  session_id = @@SPID
GO

Result Set:
local_tcp_port
61499

(1 row(s) affected)

Method 1: SQL Server Configuration Manager

Step 1. Click Start > All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager

Step 2. Go to SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for

Step 3. Right Click on TCP/IP and select Properties

enter image description here

Step 4. In TCP/IP Properties dialog box, go to IP Addresses tab and scroll down to IPAll group.

enter image description here

If SQL Server if configured to run on a static port it will be available in TCP Port textbox, and if it is configured on dynamic port then current port will be available in TCP Dynamic Ports textbox. Here my instance is listening on port number 61499.

The other methods you can find here: http://sqlandme.com/2013/05/01/sql-server-finding-tcp-port-number-sql-instance-is-listening-on/

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

protected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
        doPost(request, response);
}

And Voila!

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

How can I enable auto complete support in Notepad++?

Don't forget to add your libraries & check your versions. Good information is in Using Notepad Plus Plus as a script editor.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

i had this problem using bitcoinJ library (org.bitcoinj:bitcoinj-core:0.14.7) added to build.gradle(in module app) a packaging options inside the android scope. it helped me.

android {
...
    packagingOptions {
        exclude 'lib/x86_64/darwin/libscrypt.dylib'
        exclude 'lib/x86_64/freebsd/libscrypt.so'
        exclude 'lib/x86_64/linux/libscrypt.so'
    }
}

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Trying to load local JSON file to show data in a html page using JQuery

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

What does "Object reference not set to an instance of an object" mean?

Another easy way to get this:

 Person myPet = GetPersonFromDatabase();
 // check for myPet == null... AND for myPet.PetType == null
 if ( myPet.PetType == "cat" ) <--- fall down go boom!

Is there a way to list all resources in AWS

EDIT: This answer is deprecated. Check the other answers.

No,
There is no way to get all resources within your account in one go. Each region is independent and for some services like IAM concept of a region does not exist at all. Although there are API calls available to list down resources and services.
For example:

  • To get list of all available regions for your account:

    output, err := client.DescribeRegions(&ec2.DescribeRegionsInput{})
    

  • To get list of IAM users, roles or group you can use:

    client.GetAccountAuthorizationDetails(&iam.GetAccountAuthorizationDetailsInput{})

    You can find more detail about API calls and their use at: https://docs.aws.amazon.com/sdk-for-go/api/service/iam/

    Above link is only for IAM. Similarly, you can find API for all other resources and services.

  • How to set tbody height with overflow scroll

    HTML:

    <table id="uniquetable">
        <thead>
          <tr>
            <th> {{ field[0].key }} </th>
            <th> {{ field[1].key }} </th>
            <th> {{ field[2].key }} </th>
            <th> {{ field[3].key }} </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="obj in objects" v-bind:key="obj.id">
            <td> {{ obj.id }} </td>
            <td> {{ obj.name }} </td>
            <td> {{ obj.age }} </td>
            <td> {{ obj.gender }} </td>
          </tr>
        </tbody>
    </table>
    

    CSS:

    #uniquetable thead{
        display:block;
        width: 100%;
    }
    #uniquetable tbody{
        display:block;
        width: 100%;
        height: 100px;
        overflow-y:overlay;
        overflow-x:hidden;
    }
    #uniquetable tbody tr,#uniquetable thead tr{
        width: 100%;
        display:table;
    }
    #uniquetable tbody tr td, #uniquetable thead tr th{
       display:table-cell;
       width:20% !important;
       overflow:hidden;
    }
    

    this will work as well:

    #uniquetable tbody {
        width:inherit !important;
        display:block;
        max-height: 400px;
        overflow-y:overlay;
      }
      #uniquetable thead {
        width:inherit !important;
        display:block;
      }
      #uniquetable tbody tr, #uniquetable thead tr {
        display:inline-flex;
        width:100%;
      }
      #uniquetable tbody tr td,  #uniquetable thead tr th {
        display:block;
        width:20%;
        border-top:none;
        text-overflow: ellipsis;
        overflow: hidden;
        max-height:400px;
      }
    

    Why are there no ++ and --? operators in Python?

    It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x".

    If you want to know the original reason, you'll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it's easy enough to justify after the fact:

    Simple increment and decrement aren't needed as much as in other languages. You don't write things like for(int i = 0; i < 10; ++i) in Python very often; instead you do things like for i in range(0, 10).

    Since it's not needed nearly as often, there's much less reason to give it its own special syntax; when you do need to increment, += is usually just fine.

    It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of += and -=).

    This is all redundant with += and -=, so it would become a net loss.

    Get the first N elements of an array?

    if you want to get the first N elements and also remove it from the array, you can use array_splice() (note the 'p' in "splice"):

    http://docs.php.net/manual/da/function.array-splice.php

    use it like so: $array_without_n_elements = array_splice($old_array, 0, N)

    Failed to Connect to MySQL at localhost:3306 with user root

    Go to system preferences, then "MySQL"

    Click on "Start MySQL Server"

    Go to system preferences, then "MySQL". Click on "Start MySQL Server".

    new Runnable() but no new thread?

    You can create a thread just like this:

     Thread thread = new Thread(new Runnable() {
                        public void run() {
    
                           }
                        });
                    thread.start();
    

    Also, you can use Runnable, Asyntask, Timer, TimerTaks and AlarmManager to excecute Threads.

    How should I import data from CSV into a Postgres table using pgAdmin 3?

    assuming you have a SQL table called mydata - you can load data from a csv file as follows:

    COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
    

    For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

    Is it possible to get the current spark context settings in PySpark?

    Simply running

    sc.getConf().getAll()
    

    should give you a list with all settings.

    Regex doesn't work in String.matches()

    You can make your pattern case insensitive by doing:

    Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
    

    Deprecated meaning?

    I think the Wikipedia-article on Deprecation answers this one pretty well:

    In the process of authoring computer software, its standards or documentation, deprecation is a status applied to software features to indicate that they should be avoided, typically because they have been superseded. Although deprecated features remain in the software, their use may raise warning messages recommending alternative practices, and deprecation may indicate that the feature will be removed in the future. Features are deprecated—rather than immediately removed—in order to provide backward compatibility, and give programmers who have used the feature time to bring their code into compliance with the new standard.

    Convert Unicode data to int in python

    int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

    Do this instead:

    limit = int(limit)
    

    Or when definiting limit:

    if 'limit' in user_data :
        limit = int(user_data['limit'])
    

    How to know when a web page was last updated?

    Take a look at archive.org

    You can find almost everything about the past of a website there.

    Rails: Check output of path helper from console

    You can always check the output of path_helpers in console. Just use the helper with app

    app.post_path(3)
    #=> "/posts/3"
    
    app.posts_path
    #=> "/posts"
    
    app.posts_url
    #=> "http://www.example.com/posts"
    

    Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

    Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

     if val.dtype == float and np.isnan(val):
    

    assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

    Uses for the '&quot;' entity in HTML

    It is impossible, and unnecessary, to know the motivation for using &quot; in element content, but possible motives include: misunderstanding of HTML rules; use of software that generates such code (probably because its author thought it was “safer”); and misunderstanding of the meaning of &quot;: many people seem to think it produces “smart quotes” (they apparently never looked at the actual results).

    Anyway, there is never any need to use &quot; in element content in HTML (XHTML or any other HTML version). There is nothing in any HTML specification that would assign any special meaning to the plain character " there.

    As the question says, it has its role in attribute values, but even in them, it is mostly simpler to just use single quotes as delimiters if the value contains a double quote, e.g. alt='Greeting: "Hello, World!"' or, if you are allowed to correct errors in natural language texts, to use proper quotation marks, e.g. alt="Greeting: “Hello, World!”"

    Get button click inside UITableViewCell

    If you want to pass parameter value from cell to UIViewController using closure then

    //Your Cell Class
    class TheCell: UITableViewCell {
    
        var callBackBlockWithParam: ((String) -> ()) = {_ in }
    
    //Your Action on button
        @IBAction func didTap(_ sender: Any) {
            callBackBlockWithParam("Your Required Parameter like you can send button as sender or anything just change parameter type. Here I am passing string")
        }
    }
    
    //Your Controller
    extension TheController: UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: TheCell.identifier, for: indexPath) as! TheCell {
                cell.callBackBlockWithParam = { (passedParamter) in 
    
                 //you will get string value from cell class
                    print(passedParamter)     
          }
                return cell
        }
    }
    

    Why Does OAuth v2 Have Both Access and Refresh Tokens?

    Assume you make the access_token last very long, and don't have refresh_token, so in one day, hacker get this access_token and he can access all protected resources!

    But if you have refresh_token, the access_token's live time is short, so the hacker is hard to hack your access_token because it will be invalid after short period of time. Access_token can only be retrieved back by using not only refresh_token but also by client_id and client_secret, which hacker doesn't have.

    live output from subprocess command

    None of the Pythonic solutions worked for me. It turned out that proc.stdout.read() or similar may block forever.

    Therefore, I use tee like this:

    subprocess.run('./my_long_running_binary 2>&1 | tee -a my_log_file.txt && exit ${PIPESTATUS}', shell=True, check=True, executable='/bin/bash')
    

    This solution is convenient if you are already using shell=True.

    ${PIPESTATUS} captures the success status of the entire command chain (only available in Bash). If I omitted the && exit ${PIPESTATUS}, then this would always return zero since tee never fails.

    unbuffer might be necessary for printing each line immediately into the terminal, instead of waiting way too long until the "pipe buffer" gets filled. However, unbuffer swallows the exit status of assert (SIG Abort)...

    2>&1 also logs stderror to the file.

    Java: how to import a jar file from command line

    You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

    java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
    

    If perchance you are using linux, you should use ":" instead of ";" in the classpath.

    Change the Arrow buttons in Slick slider

    Here's an alternative solution using javascipt:

    document.querySelector('.slick-prev').innerHTML = '<img src="path/to/chevron-left-image.svg">'>;
    document.querySelector('.slick-next').innerHTML = '<img src="path/to/chevron-right-image.svg">'>;
    

    Change the img to text or what ever you require.

    In python, what is the difference between random.uniform() and random.random()?

    According to the documentation on random.uniform:

    Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

    while random.random:

    Return the next random floating point number in the range [0.0, 1.0).

    I.e. with random.uniform you specify a range you draw pseudo-random numbers from, e.g. between 3 and 10. With random.random you get a number between 0 and 1.

    What does the "On Error Resume Next" statement do?

    When an error occurs, the execution will continue on the next line without interrupting the script.

    Sort a Custom Class List<T>

    YourVariable.Sort((a, b) => a.amount.CompareTo(b.amount));
    

    How do I update Node.js?

    The easy way to update node and npm :

    npm install -g npm@latest
    

    download the latest version of node js and update /install

    Working copy XXX locked and cleanup failed in SVN

    Clean up certainly is not enough to solve this issue sometimes.

    If you use TortoiseSVN v1.7.2 or greater, right click on the Parent directory of the locked file and select TortoiseSVN -> Repo Browser from the menu. In the Repro Browser GUI right click the file that is locked and there will be an option to remove the lock.

    Using Service to run background and create notification

    The question is relatively old, but I hope this post still might be relevant for others.

    TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

    What this test-application(and instruction) is about:

    Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

    When should you use it:

    Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

    What to do:

    1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

      activity_main.xml

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:padding="16dp">
          <Button
              android:id="@+id/sendNotifications"
              android:onClick="onSendNotificationsButtonClick"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Start Sending Notifications Every 2 Hours!" />
      </RelativeLayout>
      

      MainActivity.java

      public class MainActivity extends AppCompatActivity {
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
          }
      
          public void onSendNotificationsButtonClick(View view) {
              NotificationEventReceiver.setupAlarm(getApplicationContext());
          }   
      }
      

      and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

    2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

      Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

      Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

      NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

      NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

      NotificationEventReceiver.java

      public class NotificationEventReceiver extends WakefulBroadcastReceiver {
      
          private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
          private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
          private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
      
          public static void setupAlarm(Context context) {
              AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
              PendingIntent alarmIntent = getStartPendingIntent(context);
              alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                      getTriggerAt(new Date()),
                      NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                      alarmIntent);
          }
      
          @Override
          public void onReceive(Context context, Intent intent) {
              String action = intent.getAction();
              Intent serviceIntent = null;
              if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                  Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                  serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
              } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                  Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                  serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
              }
      
              if (serviceIntent != null) {
                  startWakefulService(context, serviceIntent);
              }
          }
      
          private static long getTriggerAt(Date now) {
              Calendar calendar = Calendar.getInstance();
              calendar.setTime(now);
              //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
              return calendar.getTimeInMillis();
          }
      
          private static PendingIntent getStartPendingIntent(Context context) {
              Intent intent = new Intent(context, NotificationEventReceiver.class);
              intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
              return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
          }
      
          public static PendingIntent getDeleteIntent(Context context) {
              Intent intent = new Intent(context, NotificationEventReceiver.class);
              intent.setAction(ACTION_DELETE_NOTIFICATION);
              return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
          }
      }
      
    3. Now let's create an IntentService to actually create notifications.

      There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

      If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

      NotificationIntentService.java

      public class NotificationIntentService extends IntentService {
      
          private static final int NOTIFICATION_ID = 1;
          private static final String ACTION_START = "ACTION_START";
          private static final String ACTION_DELETE = "ACTION_DELETE";
      
          public NotificationIntentService() {
              super(NotificationIntentService.class.getSimpleName());
          }
      
          public static Intent createIntentStartNotificationService(Context context) {
              Intent intent = new Intent(context, NotificationIntentService.class);
              intent.setAction(ACTION_START);
              return intent;
          }
      
          public static Intent createIntentDeleteNotification(Context context) {
              Intent intent = new Intent(context, NotificationIntentService.class);
              intent.setAction(ACTION_DELETE);
              return intent;
          }
      
          @Override
          protected void onHandleIntent(Intent intent) {
              Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
              try {
                  String action = intent.getAction();
                  if (ACTION_START.equals(action)) {
                      processStartNotification();
                  }
                  if (ACTION_DELETE.equals(action)) {
                      processDeleteNotification(intent);
                  }
              } finally {
                  WakefulBroadcastReceiver.completeWakefulIntent(intent);
              }
          }
      
          private void processDeleteNotification(Intent intent) {
              // Log something?
          }
      
          private void processStartNotification() {
              // Do something. For example, fetch fresh data from backend to create a rich notification?
      
              final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
              builder.setContentTitle("Scheduled Notification")
                      .setAutoCancel(true)
                      .setColor(getResources().getColor(R.color.colorAccent))
                      .setContentText("This notification has been triggered by Notification Service")
                      .setSmallIcon(R.drawable.notification_icon);
      
              PendingIntent pendingIntent = PendingIntent.getActivity(this,
                      NOTIFICATION_ID,
                      new Intent(this, NotificationActivity.class),
                      PendingIntent.FLAG_UPDATE_CURRENT);
              builder.setContentIntent(pendingIntent);
              builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
      
              final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
              manager.notify(NOTIFICATION_ID, builder.build());
          }
      }
      
    4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

      NotificationServiceStarterReceiver.java

      public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
      
          @Override
          public void onReceive(Context context, Intent intent) {
              NotificationEventReceiver.setupAlarm(context);
          }
      }
      
    5. We need to also register all our services, broadcast receivers in AndroidManifest:

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="klogi.com.notificationbyschedule">
      
          <uses-permission android:name="android.permission.INTERNET" />
          <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
          <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
          <uses-permission android:name="android.permission.WAKE_LOCK" />
      
          <application
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:supportsRtl="true"
              android:theme="@style/AppTheme">
              <activity android:name=".MainActivity">
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
      
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
      
              <service
                  android:name=".notifications.NotificationIntentService"
                  android:enabled="true"
                  android:exported="false" />
      
              <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
              <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                  <intent-filter>
                      <action android:name="android.intent.action.BOOT_COMPLETED" />
                      <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                      <action android:name="android.intent.action.TIME_SET" />
                  </intent-filter>
              </receiver>
      
              <activity
                  android:name=".NotificationActivity"
                  android:label="@string/title_activity_notification"
                  android:theme="@style/AppTheme.NoActionBar"/>
          </application>
      
      </manifest>
      

    That's it!

    The source code for this project you can find here. I hope, you will find this post helpful.

    MVC4 StyleBundle not resolving images

    Better yet (IMHO) implement a custom Bundle that fixes the image paths. I wrote one for my app.

    using System;
    using System.Collections.Generic;
    using IO = System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Optimization;
    

    ...

    public class StyleImagePathBundle : Bundle
    {
        public StyleImagePathBundle(string virtualPath)
            : base(virtualPath, new IBundleTransform[1]
          {
            (IBundleTransform) new CssMinify()
          })
        {
        }
    
        public StyleImagePathBundle(string virtualPath, string cdnPath)
            : base(virtualPath, cdnPath, new IBundleTransform[1]
          {
            (IBundleTransform) new CssMinify()
          })
        {
        }
    
        public new Bundle Include(params string[] virtualPaths)
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                // Debugging. Bundling will not occur so act normal and no one gets hurt.
                base.Include(virtualPaths.ToArray());
                return this;
            }
    
            // In production mode so CSS will be bundled. Correct image paths.
            var bundlePaths = new List<string>();
            var svr = HttpContext.Current.Server;
            foreach (var path in virtualPaths)
            {
                var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
                var contents = IO.File.ReadAllText(svr.MapPath(path));
                if(!pattern.IsMatch(contents))
                {
                    bundlePaths.Add(path);
                    continue;
                }
    
    
                var bundlePath = (IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
                var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
                var bundleFilePath = String.Format("{0}{1}.bundle{2}",
                                                   bundlePath,
                                                   IO.Path.GetFileNameWithoutExtension(path),
                                                   IO.Path.GetExtension(path));
                contents = pattern.Replace(contents, "url($1" + bundleUrlPath + "$2$1)");
                IO.File.WriteAllText(svr.MapPath(bundleFilePath), contents);
                bundlePaths.Add(bundleFilePath);
            }
            base.Include(bundlePaths.ToArray());
            return this;
        }
    
    }
    

    To use it, do:

    bundles.Add(new StyleImagePathBundle("~/bundles/css").Include(
      "~/This/Is/Some/Folder/Path/layout.css"));
    

    ...instead of...

    bundles.Add(new StyleBundle("~/bundles/css").Include(
      "~/This/Is/Some/Folder/Path/layout.css"));
    

    What it does is (when not in debug mode) looks for url(<something>) and replaces it with url(<absolute\path\to\something>). I wrote the thing about 10 seconds ago so it might need a little tweaking. I've taken into account fully-qualified URLs and base64 DataURIs by making sure there's no colons (:) in the URL path. In our environment, images normally reside in the same folder as their css files, but I've tested it with both parent folders (url(../someFile.png)) and child folders (url(someFolder/someFile.png).

    Define global constants

    Updated for Angular 4+

    Now we can simply use environments file which angular provide default if your project is generated via angular-cli.

    for example

    In your environments folder create following files

    • environment.prod.ts
    • environment.qa.ts
    • environment.dev.ts

    and each file can hold related code changes such as:

    • environment.prod.ts

      export const environment = {
           production: true,
           apiHost: 'https://api.somedomain.com/prod/v1/',
           CONSUMER_KEY: 'someReallyStupidTextWhichWeHumansCantRead', 
           codes: [ 'AB', 'AC', 'XYZ' ],
      };
      
    • environment.qa.ts

      export const environment = {
           production: false,
           apiHost: 'https://api.somedomain.com/qa/v1/',
           CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', 
           codes: [ 'AB', 'AC', 'XYZ' ],
      };
      
    • environment.dev.ts

      export const environment = {
           production: false,
           apiHost: 'https://api.somedomain.com/dev/v1/',
           CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', 
           codes: [ 'AB', 'AC', 'XYZ' ],
      };
      

    Use-case in application

    You can import environments into any file such as services clientUtilServices.ts

    import {environment} from '../../environments/environment';

    getHostURL(): string {
        return environment.apiHost;
      }
    

    Use-case in build

    Open your angular cli file .angular-cli.json and inside "apps": [{...}] add following code

     "apps":[{
            "environments": {
                "dev": "environments/environment.ts",
                "prod": "environments/environment.prod.ts",
                "qa": "environments/environment.qa.ts",
               }
             }
           ]
    

    If you want to build for production, run ng build --env=prod it will read configuration from environment.prod.ts , same way you can do it for qa or dev

    ## Older answer

    I have been doing something like below, in my provider:

    import {Injectable} from '@angular/core';
    
    @Injectable()
    export class ConstantService {
    
    API_ENDPOINT :String;
    CONSUMER_KEY : String;
    
    constructor() {
        this.API_ENDPOINT = 'https://api.somedomain.com/v1/';
        this.CONSUMER_KEY = 'someReallyStupidTextWhichWeHumansCantRead'
      }
    }
    

    Then i have access to all Constant data at anywhere

    import {Injectable} from '@angular/core';
    import {Http} from '@angular/http';
    import 'rxjs/add/operator/map';
    
    import {ConstantService} from  './constant-service'; //This is my Constant Service
    
    
    @Injectable()
    export class ImagesService {
        constructor(public http: Http, public ConstantService: ConstantService) {
        console.log('Hello ImagesService Provider');
    
        }
    
    callSomeService() {
    
        console.log("API_ENDPOINT: ",this.ConstantService.API_ENDPOINT);
        console.log("CONSUMER_KEY: ",this.ConstantService.CONSUMER_KEY);
        var url = this.ConstantService.API_ENDPOINT;
        return this.http.get(url)
      }
     }
    

    Regular expression to match any character being repeated more than 10 times

    . matches any character. Used in conjunction with the curly braces already mentioned:

    $: cat > test
    ========
    ============================
    oo
    ooooooooooooooooooooooo
    
    
    $: grep -E '(.)\1{10}' test
    ============================
    ooooooooooooooooooooooo
    

    What is the scope of variables in JavaScript?

    Javascript uses scope chains to establish the scope for a given function. There is typically one global scope, and each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the scope.

    An element in the scope chain is basically a Map with a pointer to its parent scope.

    When resolving a variable, javascript starts at the innermost scope and searches outwards.

    %i or %d to print integer in C using printf()?

    both %d and %i can be used to print an integer

    %d stands for "decimal", and %i for "integer." You can use %x to print in hexadecimal, and %o to print in octal.

    You can use %i as a synonym for %d, if you prefer to indicate "integer" instead of "decimal."

    On input, using scanf(), you can use use both %i and %d as well. %i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.

    check here for more explanation

    why does %d stand for Integer?

    Open Sublime Text from Terminal in macOS

    I'm on a mac and this worked for me:

    open /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl
    

    Getting the inputstream from a classpath resource (XML file)

    ClassLoader.class.getResourceAsStream("/path/file.ext");
    

    Check if AJAX response data is empty/blank/null/undefined/0

    $.ajax({
        type:"POST",
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: associated_buildsorprojects_form,
        success:function(data){
            // do console.log(data);
            console.log(data);
            // you'll find that what exactly inside data 
            // I do not prefer alter(data); now because, it does not 
            // completes requirement all the time 
            // After that you can easily put if condition that you do not want like
            // if(data != '')
            // if(data == null)
            // or whatever you want 
        },
        error: function(errorThrown){
            alert(errorThrown);
            alert("There is an error with AJAX!");
        }               
    });
    

    How to raise a ValueError?

    Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

    def contains(char_string, char):
        largest_index = -1
        for i, ch in enumerate(char_string):
            if ch == char:
                largest_index = i
        if largest_index > -1:  # any found?
            return largest_index  # return index of last one
        else:
            raise ValueError('could not find {!r} in {!r}'.format(char, char_string))
    
    print(contains('mississippi', 's'))  # -> 6
    print(contains('bababa', 'k'))  # ->
    
    Traceback (most recent call last):
      File "how-to-raise-a-valueerror.py", line 15, in <module>
        print(contains('bababa', 'k'))
      File "how-to-raise-a-valueerror.py", line 12, in contains
        raise ValueError('could not find {} in {}'.format(char, char_string))
    ValueError: could not find 'k' in 'bababa'
    

    Update — A substantially simpler way

    Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

    Here it is along with a quick unit test:

    def contains(char_string, char):
        #  Ending - 1 adjusts returned index to account for searching in reverse.
        return len(char_string) - char_string[::-1].index(char) - 1
    
    print(contains('mississippi', 's'))  # -> 6
    print(contains('bababa', 'k'))  # ->
    
    Traceback (most recent call last):
      File "better-way-to-raise-a-valueerror.py", line 9, in <module>
        print(contains('bababa', 'k'))
      File "better-way-to-raise-a-valueerror", line 6, in contains
        return len(char_string) - char_string[::-1].index(char) - 1
    ValueError: substring not found
    

    Using Ansible set_fact to create a dictionary from register results

    I think I got there in the end.

    The task is like this:

    - name: Populate genders
      set_fact:
        genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
      with_items: "{{ people.results }}"
    

    It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

    {
        "Bob": "male",
        "Thelma": "female"
    }
    

    It assumes the keys (the name in this case) will be unique.


    I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

    - name: Populate genders
      set_fact:
        genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
      with_items: "{{ people.results }}"
    

    This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

    [
        {'name': 'Bob', 'gender': 'male'},
        {'name': 'Thelma', 'gender': 'female'}
    ]
    

    what is the difference between json and xml

    The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.

    A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.

    To illustrate the point, let me borrow Guffa's example:

    {   "persons": [
      {
        "name": "Ford Prefect",
        "gender": "male"
     },
     {
       "name": "Arthur Dent",
       "gender": "male"
      },
      {
        "name": "Tricia McMillan",
        "gender": "female"
      }   ] }
    

    The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.

    A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:

    <xjson>   
      <object>
        <name>persons</name>
        <value>
          <array>
             <object>
                <value>Ford Prefect</value>
                <gender>male</gender>
             </object>
             <object>
                <value>Arthur Dent</value>
                <gender>male</gender>
             </object>
             <object>
                <value>Tricia McMillan</value>
                <gender>female</gender>
             </object>
          </array>
        </value>   
      </object> 
     </xjson>
    

    Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.

    So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.

    But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.

    If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.

    It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.

    It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.

    Get all attributes of an element using jQuery

    Here is a one-liner for you.

    JQuery Users:

    Replace $jQueryObject with your jQuery object. i.e $('div').

    Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
    

    Vanilla Javascript Users:

    Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').

    Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
    

    Cheers!!

    Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

    The other clean solution if you don't want to pop all stack entries...

    getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_container, fragmentInstance).addToBackStack(null).commit();
    

    This will clean the stack first and then load a new fragment, so at any given point you'll have only single fragment in stack

    Conditionally formatting cells if their value equals any value of another column

    Here is the formula

    create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A

    =NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
    


    enter image description here

    here is the example sheet to download if you encounter problems


    UPDATE
    here is @pnuts's suggestion which works perfect as well:

    =MATCH(A1,B:B,0)>0
    


    How to remove all the occurrences of a char in c++ string

    Basically, replace replaces a character with another and '' is not a character. What you're looking for is erase.

    See this question which answers the same problem. In your case:

    #include <algorithm>
    str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
    

    Or use boost if that's an option for you, like:

    #include <boost/algorithm/string.hpp>
    boost::erase_all(str, "a");
    

    All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:

    std::string output;
    output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
    for(size_t i = 0; i < str.size(); ++i)
      if(str[i] != 'a') output += str[i];
    

    How to configure WAMP (localhost) to send email using Gmail?

    PEAR: Mail worked for me sending email messages from Gmail. Also, the instructions: How to Send Email from a PHP Script Using SMTP Authentication (Using PEAR::Mail) helped greatly. Thanks, CMS!

    Is there a Sleep/Pause/Wait function in JavaScript?

    setTimeout() function it's use to delay a process in JavaScript.

    w3schools has an easy tutorial about this function.

    Chart.js - Formatting Y axis

    As Nevercom said the scaleLable should contain javascript so to manipulate the y value just apply the required formatting.

    Note the the value is a string.

    var options = {      
        scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>"
    };
    

    jsFiddle example

    if you wish to set a manual y scale you can use scaleOverride

    var options = {      
        scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>",
    
        scaleOverride: true,
        scaleSteps: 10,
        scaleStepWidth: 10,
        scaleStartValue: 0
    
    };
    

    jsFiddle example

    Hibernate table not mapped error in HQL query

    This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.

    The exception:

    org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]
    

    In simple words, this very usual exception only tells that the query is wrong in the below code.

    Session session = this.sessionFactory.getCurrentSession();
    List<Subscriber> personsList = session.createQuery(" from subscriber").list();
    

    This is how my POJO class is declared:

    @Entity
    @Table(name = "subscriber")
    public class Subscriber
    

    But the query syntax "from subscriber" is correct and the table subscriber exists. Which brings me to a key point:

    • It is an HQL query not SQL.

    and how its explained here

    HQL works with persistent objects and their properties not with the database tables and columns.

    Since the above query is an HQL one, the subscriber is supposed to be an entity name not a table name. Since I have my table subscriber mapped with the entity Subscriber. My problem solves if I change the code to this:

    Session session = this.sessionFactory.getCurrentSession();
    List<Subscriber> personsList = session.createQuery(" from Subscriber").list();
    

    Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.

    Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

    https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm

    To further understand how hibernate mapping works, please read this

    How to get first N number of elements from an array

    To get the first n elements of an array, use

    array.slice(0, n);
    

    In PHP, what is a closure and why does it use the "use" identifier?

    This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

    Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.

    How to fix the error "Windows SDK version 8.1" was not found?

    I had win10 SDK and I only had to do retarget and then I stopped getting this error. The idea was that the project needs to upgrade its target Windows SDK.

    int to unsigned int conversion

    Edit: As has been noted in the other answers, the standard actually guarantees that "the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)". So even if your platform did not store signed ints as two's complement, the behavior would be the same.


    Apparently your signed integer -62 is stored in two's complement (Wikipedia) on your platform:

    62 as a 32-bit integer written in binary is

    0000 0000 0000 0000 0000 0000 0011 1110
    

    To compute the two's complement (for storing -62), first invert all the bits

    1111 1111 1111 1111 1111 1111 1100 0001
    

    then add one

    1111 1111 1111 1111 1111 1111 1100 0010
    

    And if you interpret this as an unsigned 32-bit integer (as your computer will do if you cast it), you'll end up with 4294967234 :-)

    Java collections convert a string to a list of characters

    Use a Java 8 Stream.

    myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
    

    Breakdown:

    myString
        .chars() // Convert to an IntStream
        .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
        .collect(Collectors.toList()); // Collect in a List<Character>
    

    (I have absolutely no idea why String#chars() returns an IntStream.)

    Can an html element have multiple ids?

    Any ID assigned to a div element is unique.
    However, you can assign multiple IDs "under", and not "to" a div element.
    In that case, you have to represent those IDs as <span></span> IDs.
    
    Say, you want two links in the same HTML page to point to the same div element in  the page.
    
    The two different links
    <p><a href="#exponentialEquationsCalculator">Exponential Equations</a></p>         
    
    <p><a href="#logarithmicExpressionsCalculator"><Logarithmic Expressions</a></p>
    
    Point to the same section of the page. 
    <!-- Exponential / Logarithmic Equations Calculator -->
    <div class="w3-container w3-card white w3-margin-bottom">      
       <span id="exponentialEquationsCalculator"></span>
       <span id="logarithmicEquationsCalculator"></span>
    </div>
    

    What is the inclusive range of float and double in Java?

    Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

    You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

    Get next / previous element using JavaScript?

    Tested it and it worked for me. The element finding me change as per the document structure that you have.

    <html>
        <head>
            <script type="text/javascript" src="test.js"></script>
        </head>
        <body>
            <form method="post" id = "formId" action="action.php" onsubmit="return false;">
                <table>
                    <tr>
                        <td>
                            <label class="standard_text">E-mail</label>
                        </td>
                        <td><input class="textarea"  name="mail" id="mail" placeholder="E-mail"></label></td>
                        <td><input class="textarea"  name="name" id="name" placeholder="E-mail">   </label></td>
                        <td><input class="textarea"  name="myname" id="myname" placeholder="E-mail"></label></td>
                        <td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
                        <td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
                        <td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
                    </tr>
                </table>
                <input class="button_submit" type="submit" name="send_form" value="Register"/>
            </form>
        </body>
    </html>
    

     

    var inputs;
    document.addEventListener("DOMContentLoaded", function(event) {
        var form = document.getElementById('formId');
        inputs = form.getElementsByTagName("input");
        for(var i = 0 ; i < inputs.length;i++) {
            inputs[i].addEventListener('keydown', function(e){
                if(e.keyCode == 13) {
                    var currentIndex = findElement(e.target)
                    if(currentIndex > -1 && currentIndex < inputs.length) {
                        inputs[currentIndex+1].focus();
                    }
                }   
            });
        }
    });
    
    function findElement(element) {
        var index = -1;
        for(var i = 0; i < inputs.length; i++) {
            if(inputs[i] == element) {
                return i;
            }
        }
        return index;
    }
    

    Convert a Python list with strings all to lowercase or uppercase

    >>> map(str.lower,["A","B","C"])
    ['a', 'b', 'c']
    

    How to change PHP version used by composer

    I'm assuming Windows if you're using WAMP. Composer likely is just using the PHP set in your path: How to access PHP with the Command Line on Windows?

    You should be able to change the path to PHP using the same instructions.

    Otherwise, composer is just a PHAR file, you can download the PHAR and execute it using any PHP:

    C:\full\path\to\php.exe C:\full\path\to\composer.phar install
    

    How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

    This is working code

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                { 
                        DropDownList1.DataTextField = "user_name";
                        DropDownList1.DataValueField = "user_id";
                        DropDownList1.DataSource = getData();// get the data into the list you can set it
                        DropDownList1.DataBind();
    
        DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
                }
            }
    

    '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

    just cast the field as char

    Eg: cast(updatedate) as char as updatedate

    android:drawableLeft margin and/or padding

    android:drawablePadding will only create a padding gap between the text and the drawable if the button is small enough to squish the 2 together. If your button is wider than the combined width (for drawableLeft/drawableRight) or height (for drawableTop/drawableBottom) then drawablePadding doesn't do anything.

    I'm struggling with this right now as well. My buttons are quite wide, and the icon is hanging on the left edge of the button and the text is centered in the middle. My only way to get around this for now has been to bake in a margin on the drawable by adding blank pixels to the left edge of the canvas with photoshop. Not ideal, and not really recommended either. But thats my stop-gap solution for now, short of rebuilding TextView/Button.

    rmagick gem install "Can't find Magick-config"

    For CentOS 5/6 this is what worked for me

    yum remove ImageMagick
    yum install tcl-devel libpng-devel libjpeg-devel ghostscript-devel bzip2-devel freetype-devel libtiff-devel
    mkdir /root/imagemagick
    cd /root/imagemagick
    wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz
    tar xzvf ImageMagick.tar.gz
    cd ImageMagick-*
    ./configure --prefix=/usr/ --with-bzlib=yes --with-fontconfig=yes --with-freetype=yes --with-gslib=yes --with-gvc=yes --with-jpeg=yes --with-jp2=yes --with-png=yes --with-tiff=yes
    make
    make install
    

    For 64 bit do this

    cd /usr/lib64
    ln -s ../lib/libMagickCore.so.3 libMagickCore.so.3 
    ln -s ../lib/libMagickWand.so.3 libMagickWand.so.3
    

    Add the missing dependencies

    yum install ImageMagick-devel
    

    Then finally rmagick

    gem install rmagick
    

    If you need to start fresh remove other installs first with

    cd /root/imagemagick/ImageMagick-*
    make uninstall
    

    How to drop rows from pandas data frame that contains a particular string in a particular column?

    If your string constraint is not just one string you can drop those corresponding rows with:

    df = df[~df['your column'].isin(['list of strings'])]
    

    The above will drop all rows containing elements of your list

    How do I concatenate a boolean to a string in Python?

    answer = True

    myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this

    print(myvar)

    How to count instances of character in SQL Column

    This gave me accurate results every time...

    This is in my Stripes field...

    Yellow, Yellow, Yellow, Yellow, Yellow, Yellow, Black, Yellow, Yellow, Red, Yellow, Yellow, Yellow, Black

    • 11 Yellows
    • 2 Black
    • 1 Red
    SELECT (LEN(Stripes) - LEN(REPLACE(Stripes, 'Red', ''))) / LEN('Red') 
      FROM t_Contacts
    

    SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

    You cannot supply system properties to the jarsigner.exe tool, unfortunately.

    I have submitted defect 7177232, referencing @eckes' defect 7127374 and explaining why it was closed in error.

    My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly.

    UPDATE: Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use jarsigner -J-Djsse.enableSNIExtension=false

    How to set the height of an input (text) field in CSS?

    Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

    You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

    How to Set Focus on JTextField?

    Try this one,

    myFrame.setVisible(true);
    EventQueue.invokeLater(new Runnable() {
    
       @Override
         public void run() {
             myComponent.grabFocus();
             myComponent.requestFocus();//or inWindow
         }
    });
    

    How to access the request body when POSTing using Node.js and Express?

    You use the following code to log post data:

    router.post("/users",function(req,res){
        res.send(JSON.stringify(req.body, null, 4));
    });
    

    Rolling back bad changes with svn in Eclipse

    I have written a couple of blog posts on this subject. One that is Subclipse centric: http://markphip.blogspot.com/2007/01/how-to-undo-commit-in-subversion.html and one that is command-line centric: http://blogs.collab.net/subversion/2007/07/second-chances/

    ASP.NET strange compilation error

    I just ran into this on .NET 4.6.1 and it ultimately had a simple solution - I removed (actually commented out) the section in the web.config and the web forms application came back to life. See what-exactly-does-system-codedom-compilers-do-in-web-config-in-mvc-5 for more info.

    It worked for me.

    VSCode regex find & replace submatch math?

    To augment Benjamin's answer with an example:

    Find        Carrots(With)Dip(Are)Yummy
    Replace     Bananas$1Mustard$2Gross
    Result      BananasWithMustardAreGross
    

    Anything in the parentheses can be a regular expression.

    jQuery how to bind onclick event to dynamically added HTML element

        function load_tpl(selected=""){
            $("#load_tpl").empty();
            for(x in ds_tpl){
                $("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
            }
            $.each($("#load_tpl a"),function(){
                $(this).on("click",function(e){
                    alert(e.target.id);
                });
            });
        }
    

    Reading and writing to serial port in C on Linux

    1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

    2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

    3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

    Edited to Add:

    Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

    int tmp, serialLines;
    
    cout << "Dropping Reading DTR and RTS\n";
    ioctl ( readFd, TIOCMGET, & serialLines );
    serialLines &= ~TIOCM_DTR;
    serialLines &= ~TIOCM_RTS;
    ioctl ( readFd, TIOCMSET, & serialLines );
    usleep(100000);
    ioctl ( readFd, TIOCMGET, & tmp );
    cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
    sleep (2);
    
    cout << "Setting Reading DTR and RTS\n";
    serialLines |= TIOCM_DTR;
    serialLines |= TIOCM_RTS;
    ioctl ( readFd, TIOCMSET, & serialLines );
    ioctl ( readFd, TIOCMGET, & tmp );
    cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
    

    How to efficiently count the number of keys/properties of an object in JavaScript?

    I try to make it available to all object like this:

    Object.defineProperty(Object.prototype, "length", {
    get() {
        if (!Object.keys) {
            Object.keys = function (obj) {
                var keys = [],k;
                for (k in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, k)) {
                        keys.push(k);
                    }
                }
                return keys;
            };
        }
        return Object.keys(this).length;
    },});
    
    console.log({"Name":"Joe","Age":26}.length) //returns 2
    

    ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

    1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

    public ActionResult Logout() {
        //log out the user
        return RedirectToAction("Login");
    }
    

    2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

    Why would you want to redirect from a controller init?

    the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

    public ActionResult Index() {
        return RedirectToAction("whateverAction", "whateverController");
    }
    

    I want to calculate the distance between two points in Java

    Based on the @trashgod's comment, this is the simpliest way to calculate distance:

    double distance = Math.hypot(x1-x2, y1-y2);
    

    From documentation of Math.hypot:

    Returns: sqrt(x²+ y²) without intermediate overflow or underflow.

    PHP header() redirect with POST variables

    If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

    // form.php
    
    <?php
    
        if (!empty($_POST['submit'])) {
            // validate
    
            if ($allGood) {
                // put data into database or whatever needs to be done
    
                header('Location: nextpage.php');
                exit;
            }
        }
    
    ?>
    
    <form action="form.php">
        <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
        ...
    </form>
    

    This can be made more elegant, but you get the idea...

    What's the difference between an id and a class?

    A CLASS should be used for multiple elements that you want the same styling for. An ID should be for a unique element. See this tutorial.

    You should refer to the W3C standards if you want to be a strict conformist, or if you want your pages to be validated to the standards.

    jquery - fastest way to remove all rows from a very large table

    this works for me :

    1- add class for each row "removeRow"

    2- in the jQuery

    $(".removeRow").remove();
    

    Numpy, multiply array with scalar

    Using .multiply() (ufunc multiply)

    a_1 = np.array([1.0, 2.0, 3.0])
    a_2 = np.array([[1., 2.], [3., 4.]])
    b = 2.0 
    
    np.multiply(a_1,b)
    # array([2., 4., 6.])
    np.multiply(a_2,b)
    # array([[2., 4.],[6., 8.]])
    

    What is a Maven artifact?

    Usually, when you create a Java project you want to use functionalities made in another Java projects. For example, if your project wants to send one email you dont need to create all the necessary code for doing that. You can bring a java library that does the most part of the work. Maven is a building tool that will help you in several tasks. One of those tasks is to bring these external dependencies or artifacts to your project in an automatic way ( only with some configuration in a XML file ). Of course Maven has more details but, for your question this is enough. And, of course too, Maven can build your project as an artifact (usually a jar file ) that can be used or imported in other projects.

    This website has several articles talking about Maven :

    https://connected2know.com/programming/what-is-maven/

    https://connected2know.com/programming/maven-configuration/

    Print in Landscape format

    you cannot set this in javascript, you have to do this with html/css:

    <style type="text/css" media="print">
      @page { size: landscape; }
    </style>
    

    EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

    How to use order by with union all in sql?

    You don't really need to have parenthesis. You can sort directly:

    SELECT *, 1 AS RN FROM TABLE_A
    UNION ALL 
    SELECT *, 2 AS RN FROM TABLE_B
    ORDER BY RN, COLUMN_1
    

    file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

    if file.delete() is sending false then in most of the cases your Bufferedreader handle will not be closed. Just close and it seems to work for me normally.

    How to POST a FORM from HTML to ASPX page

    Remove runat="server" parts of data posting/posted .aspx page.

    Get single listView SelectedItem

    foreach (ListViewItem itemRow in taskShowListView.Items)
    {
        if (itemRow.Items[0].Checked == true)
        {
            int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);
    
            string taskDate = itemRow.SubItems[1].ToString();
            string taskDescription = itemRow.SubItems[2].ToString();            
        }
    }
    

    How to replace comma with a dot in the number (or any replacement)

    You can also do it like this:

    var tt="88,9827";
    tt=tt.replace(",", ".");
    alert(tt);
    

    working fiddle example

    Date vs DateTime

    You can return DateTime where the time portion is 00:00:00 and just ignore it. The dates are handled as timestamp integers so it makes sense to combine the date with the time as that is present in the integer anyway.

    Populating a ComboBox using C#

    To make it read-only, the DropDownStyle property to DropDownStyle.DropDownList.

    To populate the ComboBox, you will need to have a object like Language or so containing both for instance:

    public class Language {
        public string Name { get; set; }
        public string Code { get; set; }
    }
    

    Then, you may bind a IList to your ComboBox.DataSource property like so:

    IList<Language> languages = new List<Language>();
    languages.Add(new Language("English", "en"));
    languages.Add(new Language("French", "fr"));
    
    ComboxBox.DataSource = languages;
    ComboBox.DisplayMember = "Name";
    ComboBox.ValueMember = "Code";
    

    This will do exactly what you expect.

    How do I collapse sections of code in Visual Studio Code for Windows?

    As of Visual Studio Code version 1.12.0, April 2017, see Basic Editing > Folding section in the docs.

    The default keys are:

    Fold All: CTRL+K, CTRL+0 (zero)

    Fold Level [n]: CTRL+K, CTRL+[n]*

    Unfold All: CTRL+K, CTRL+J

    Fold Region: CTRL+K, CTRL+[

    Unfold Region: CTRL+K, CTRL+]

    *Fold Level: to fold all but the most outer classes, try CTRL+K, CTRL+1

    Macs: use ? instead of CTRL (thanks Prajeet)

    Get line number while using grep

    Line numbers are printed with grep -n:

    grep -n pattern file.txt
    

    To get only the line number (without the matching line), one may use cut:

    grep -n pattern file.txt | cut -d : -f 1
    

    Lines not containing a pattern are printed with grep -v:

    grep -v pattern file.txt
    

    Detecting EOF in C

    EOF is just a macro with a value (usually -1). You have to test something against EOF, such as the result of a getchar() call.

    One way to test for the end of a stream is with the feof function.

    if (feof(stdin))
    

    Note, that the 'end of stream' state will only be set after a failed read.

    In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.

    How to get system time in Java without creating a new Date

    This should work:

    System.currentTimeMillis();
    

    Is a new line = \n OR \r\n?

    \n is used for Unix systems (including Linux, and OSX).

    \r\n is mainly used on Windows.

    \r is used on really old Macs.

    PHP_EOL constant is used instead of these characters for portability between platforms.

    How can I sanitize user input with PHP?

    Do not try to prevent SQL injection by sanitizing input data.

    Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.

    Please see my website http://bobby-tables.com/ for more about preventing SQL injection.

    C# ASP.NET MVC Return to Previous Page

    For ASP.NET Core You can use asp-route-* attribute:

    <form asp-action="Login" asp-route-previous="@Model.ReturnUrl">
    

    An example: Imagine that you have a Vehicle Controller with actions

    Index

    Details

    Edit

    and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

    //In your viewmodel add the ReturnUrl Property
    public class VehicleViewModel
    {
         ..............
         ..............
         public string ReturnUrl {get;set;}
    }
    
    
    
    Details.cshtml
    <a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>
    
    Index.cshtml
    <a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>
    
    Edit.cshtml
    <form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
            <div class="box-footer">
                <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
                <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
            </div>
        </form>
    

    In your controller:

    // GET: Vehicle/Edit/5
        public ActionResult Edit(int id,string previous)
        {
                var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
                var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
        //or by this code if you are not use automapper
        var viewModel = new VehicleViewModel();
    
        if (!string.IsNullOrWhiteSpace(previous)
                    viewModel.ReturnUrl = previous;
                else
                    viewModel.ReturnUrl = "Index";
                return View(viewModel);
            }
    
    
    
    [HttpPost]
        public IActionResult Edit(VehicleViewModel model, string previous)
        {
                if (!string.IsNullOrWhiteSpace(previous))
                    model.ReturnUrl = previous;
                else
                    model.ReturnUrl = "Index";
                ............. 
                .............
                return RedirectToAction(model.ReturnUrl);
        }
    

    What is the meaning of Bus: error 10 in C

    Your code attempts to overwrite a string literal. This is undefined behaviour.

    There are several ways to fix this:

    1. use malloc() then strcpy() then free();
    2. turn str into an array and use strcpy();
    3. use strdup().

    Get Value of a Edit Text field

    Get value from an EditText control in android. EditText getText property use to get value an EditText:

    EditText txtname = findViewById(R.id.name);
    String name      =  txtname.getText().toString();
    

    How to change the color of header bar and address bar in newest Chrome version on Lollipop?

    You actually need 3 meta tags to support Android, iPhone and Windows Phone

    <!-- Chrome, Firefox OS and Opera -->
    <meta name="theme-color" content="#4285f4">
    <!-- Windows Phone -->
    <meta name="msapplication-navbutton-color" content="#4285f4">
    <!-- iOS Safari -->
    <meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
    

    How to format date string in java?

    package newpckg;
    
    import java.util.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    public class StrangeDate {
    
        public static void main(String[] args) {
    
            // string containing date in one format
            // String strDate = "2012-05-20T09:00:00.000Z";
            String strDate = "2012-05-20T09:00:00.000Z";
    
            try {
                // create SimpleDateFormat object with source string date format
                SimpleDateFormat sdfSource = new SimpleDateFormat(
                        "yyyy-MM-dd'T'hh:mm:ss'.000Z'");
    
                // parse the string into Date object
                Date date = sdfSource.parse(strDate);
    
                // create SimpleDateFormat object with desired date format
                SimpleDateFormat sdfDestination = new SimpleDateFormat(
                        "dd/MM/yyyy, ha");
    
                // parse the date into another format
                strDate = sdfDestination.format(date);
    
                System.out
                        .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
                System.out.println("Converted date is : " + strDate.toLowerCase());
    
            } catch (ParseException pe) {
                System.out.println("Parse Exception : " + pe);
            }
        }
    }
    

    SyntaxError: cannot assign to operator

    Well, as the error says, you have an expression (((t[1])/length) * t[1]) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string to it (which is always "") and assign it to... where? ((t[1])/length) * t[1] isn't a variable name, so you can't store the result into it.

    Did you mean string += ((t[1])/length) * t[1]? That would make more sense. Of course, you're still trying to add a number to a string, or multiply by a string... one of those t[1]s should probably be a t[0].

    Jackson - How to process (deserialize) nested JSON?

    I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    class Scratch {
        private final String aString;
        private final String bString;
        private final String cString;
        private final static String jsonString;
    
        static {
            jsonString = "{\n" +
                    "  \"wrap\" : {\n" +
                    "    \"A\": \"foo\",\n" +
                    "    \"B\": \"bar\",\n" +
                    "    \"C\": \"baz\"\n" +
                    "  }\n" +
                    "}";
        }
    
        @JsonCreator
        Scratch(@JsonProperty("A") String aString,
                @JsonProperty("B") String bString,
                @JsonProperty("C") String cString) {
            this.aString = aString;
            this.bString = bString;
            this.cString = cString;
        }
    
        @Override
        public String toString() {
            return "Scratch{" +
                    "aString='" + aString + '\'' +
                    ", bString='" + bString + '\'' +
                    ", cString='" + cString + '\'' +
                    '}';
        }
    
        public static class JsonDeserializer {
            private final Scratch scratch;
    
            @JsonCreator
            public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
                this.scratch = scratch;
            }
    
            public Scratch getScratch() {
                return scratch;
            }
        }
    
        public static void main(String[] args) throws JsonProcessingException {
            ObjectMapper objectMapper = new ObjectMapper();
            Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
            System.out.println(scratch.toString());
        }
    }
    

    However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

    IntelliJ does not show 'Class' when we right click and select 'New'

    This can also happen if your package name is invalid.

    For example, if your "package" is com.my-company (which is not a valid Java package name due to the dash), IntelliJ will prevent you from creating a Java Class in that package.

    RecyclerView onClick

    Very simple, add this class:

    public class OnItemClickListener implements View.OnClickListener {
        private int position;
        private OnItemClickCallback onItemClickCallback;
    
        public OnItemClickListener(int position, OnItemClickCallback onItemClickCallback) {
            this.position = position;
            this.onItemClickCallback = onItemClickCallback;
        }
    
        @Override
        public void onClick(View view) {
            onItemClickCallback.onItemClicked(view, position);
        }
    
        public interface OnItemClickCallback {
            void onItemClicked(View view, int position);
        }
    }
    

    Get an instance of 'OnItemClickCallback' interface and put it in your activity or fragment:

    private OnItemClickListener.OnItemClickCallback onItemClickCallback = new OnItemClickListener.OnItemClickCallback() {
        @Override
        public void onItemClicked(View view, int position) {
        }
    };
    

    Then, pass that callback to your recyclerView:

    recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(Arrays.asList("1", "2", "3"), onItemClickCallback));
    

    Finally, this would be your adapter:

    public class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
        private List<String> mValues;
        private OnItemClickListener.OnItemClickCallback onItemClickCallback;
    
        public SimpleStringRecyclerViewAdapter(List<String> items, OnItemClickListener.OnItemClickCallback onItemClickCallback) {
            mValues = items;
            this.onItemClickCallback = onItemClickCallback;
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
            public final TextView mTextView;
    
            public ViewHolder(View view) {
                super(view);
                mTextView = (TextView) view.findViewById(R.id.txt_title);
            }
        }
    
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
            return new ViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            holder.mTextView.setText(mValues.get(position));
            holder.mTextView.setOnClickListener(new OnItemClickListener(position, onItemClickCallback));
        }
    
        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }
    

    Android - Using Custom Font

    The correct way of doing this as of API 26 is described in the official documentation here :

    https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html

    This involves placing the ttf files in res/font folder and creating a font-family file.

    How do I change the UUID of a virtual disk?

    Another alternative to your original solution would be to use the escape character \ before the space:

    VBoxManage internalcommands sethduuid /home/user/VirtualBox\ VMs/drupal/drupal.vhd
    

    Is there an addHeaderView equivalent for RecyclerView?

    There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.

    Here is an example

    public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private static final int TYPE_HEADER = 0;
        private static final int TYPE_ITEM = 1;
        String[] data;
    
        public HeaderAdapter(String[] data) {
            this.data = data;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ITEM) {
                //inflate your layout and pass it to view holder
                return new VHItem(null);
            } else if (viewType == TYPE_HEADER) {
                //inflate your layout and pass it to view holder
                return new VHHeader(null);
            }
    
            throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof VHItem) {
                String dataItem = getItem(position);
                //cast holder to VHItem and set data
            } else if (holder instanceof VHHeader) {
                //cast holder to VHHeader and set data for header.
            }
        }
    
        @Override
        public int getItemCount() {
            return data.length + 1;
        }
    
        @Override
        public int getItemViewType(int position) {
            if (isPositionHeader(position))
                return TYPE_HEADER;
    
            return TYPE_ITEM;
        }
    
        private boolean isPositionHeader(int position) {
            return position == 0;
        }
    
        private String getItem(int position) {
            return data[position - 1];
        }
    
        class VHItem extends RecyclerView.ViewHolder {
            TextView title;
    
            public VHItem(View itemView) {
                super(itemView);
            }
        }
    
        class VHHeader extends RecyclerView.ViewHolder {
            Button button;
    
            public VHHeader(View itemView) {
                super(itemView);
            }
        }
    }
    

    link to gist -> here

    Sum values from an array of key-value pairs in JavaScript

    where 0 is initial value

    Array.reduce((currentValue, value) => currentValue +value,0)
    

    or

    Array.reduce((currentValue, value) =>{ return currentValue +value},0)
    

    or

    [1,3,4].reduce(function(currentValue, value) { return currentValue + value},0)
    

    Add button to a layout programmatically

    If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

    ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
    

    then you can create a new Button for example and just add it:

    Button bt = new Button(this);
    bt.setText("A Button");
    bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                        LayoutParams.WRAP_CONTENT));
    linerLayout.addView(bt);
    

    What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

    You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.

        SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength
    

    This will produce 11 for BinaryLength and 10 for TextLength.

    In a table your SQL would like this:

        SELECT * 
        FROM tblA
        WHERE DATALENGTH(MyTextField) > LEN(MyTextField)
    

    This function is usable in all versions of SQL Server beginning with 2005.

    Whether a variable is undefined

    http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

    Depends on how specific you want the test to be. You could maybe get away with

    if(page_name){ string += "&page_name=" + page_name; }
    

    Calendar Recurring/Repeating Events - Best Storage Method

    I would follow this guide: https://github.com/bmoeskau/Extensible/blob/master/recurrence-overview.md

    Also make sure you use the iCal format so not to reinvent the wheel and remember Rule #0: Do NOT store individual recurring event instances as rows in your database!

    Adding a rule in iptables in debian to open a new port

    (I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

    Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

    iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT
    

    Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

    Sending commands and strings to Terminal.app with Applescript

    As EvanK stated each do script line will open a new window however you can run
    two commands with the same do script by separating them with a semicolon. For example:

    tell application "Terminal"
        do script "date;time"
    end tell
    

    But the limit appears to be two commands.

    However, you can append "in window 1" to the do script command (for every do script after the first one) to get the same effect and continue to run as many commands as you need to in the same window:

    tell application "Terminal"
        do script "date"
        do script "time" in window 1
        do script "who" in window 1
    end tell
    


    Note that I just used the who, date, and time command as an example...replace with whatever commands you need.

    How do I include a Perl module that's in a different directory?

    Most likely the reason your push did not work is order of execution.

    use is a compile time directive. You push is done at execution time:

    push ( @INC,"directory_path/more_path");
    use Foo.pm;  # In directory path/more_path
    

    You can use a BEGIN block to get around this problem:

    BEGIN {
        push ( @INC,"directory_path/more_path");
    }
    use Foo.pm;  # In directory path/more_path
    

    IMO, it's clearest, and therefore best to use lib:

    use lib "directory_path/more_path";
    use Foo.pm;  # In directory path/more_path
    

    See perlmod for information about BEGIN and other special blocks and when they execute.

    Edit

    For loading code relative to your script/library, I strongly endorse File::FindLib

    You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

    Say your work is structured like this:

       /home/me/projects/
        |- shared/
        |   |- bin/
        |   `- lib/
        `- ossum-thing/
           `- scripts 
               |- bin/
               `- lib/
    

    Inside a script in ossum-thing/scripts/bin:

    use File::FindLib 'lib/';
    use File::FindLib 'shared/lib/';
    

    Will find your library directories and add them to your @INC.

    It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

    use File::FindLib 'lib/MyEnvironment.pm'
    

    Convert DOS line endings to Linux line endings in Vim

    Convert directory of files from DOS to Unix

    Using command line and sed, find all files in current directory with the extension ".ext" and remove all "^M"

    @ https://gist.github.com/sparkida/7773170

    find $(pwd) -type f -name "*.ext" | while read file; do sed -e 's/^M//g' -i "$file"; done;
    

    Also, as mentioned in a previous answer, ^M = Ctrl+V + Ctrl+M (don't just type the caret "^" symbol and M).

    When should you use a class vs a struct in C++?

    They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class

    The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.

    In practice, I've always used structs as data holders and classes as objects.

    How to call a function from a string stored in a variable?

    As already mentioned, there are a few ways to achieve this with possibly the safest method being call_user_func() or if you must you can also go down the route of $function_name(). It is possible to pass arguments using both of these methods as so

    $function_name = 'foobar';
    
    $function_name(arg1, arg2);
    
    call_user_func_array($function_name, array(arg1, arg2));
    

    If the function you are calling belongs to an object you can still use either of these

    $object->$function_name(arg1, arg2);
    
    call_user_func_array(array($object, $function_name), array(arg1, arg2));
    

    However if you are going to use the $function_name() method it may be a good idea to test for the existence of the function if the name is in any way dynamic

    if(method_exists($object, $function_name))
    {
        $object->$function_name(arg1, arg2);
    }
    

    jQuery callback for multiple ajax calls

    $.ajax({type:'POST', url:'www.naver.com', dataType:'text', async:false,
        complete:function(xhr, textStatus){},
        error:function(xhr, textStatus){},
        success:function( data ){
            $.ajax({type:'POST', 
                ....
                ....
                success:function(data){
                    $.ajax({type:'POST',
                        ....
                        ....
                }
            }
        });
    

    I'm sorry but I can't explain what I worte cuz I'm a Korean who can't speak even a word in english. but I think you can easily understand it.

    How to update a git clone --mirror?

    Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

    But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

    I have found this very interesting thread about cloning/mirroring the hooks:

    http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

    I learned:

    • The hooks are not considered part of the repository contents.

    • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

    • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

    • There is this interesting template feature on git.

    So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

    Well... I will just forget about hooks cloning, and stick to the git remote update way.

    • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

    Thanks! Improved a bit of my own "git-fu"... :-)

    How to use subList()

    I've implemented and tested this one; it should cover most bases:

    public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
        int size = list.size();
        if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
            return Collections.emptyList();
        }
    
        fromIndex = Math.max(0, fromIndex);
        toIndex = Math.min(size, toIndex);
    
        return list.subList(fromIndex, toIndex);
    }
    

    Installing tensorflow with anaconda in windows

    This worked for me:

    conda create -n tensorflow python=3.5
    activate tensorflow
    conda install -c conda-forge tensorflow
    

    Open Anaconda Navigator.

    Change the dropdown of "Applications on" from "root" to "tensorflow"

    see screenshot

    Launch Spyder

    Run a little code to validate you're good to go:

    import tensorflow as tf
    node1 = tf.constant(3, tf.float32)
    node2 = tf.constant(4) # also tf.float32 implicitly
    print(node1, node2)
    

    or

    hello = tf.constant('Hello, TensorFlow!')
    sess = tf.Session()
    print(sess.run(hello))
    

    htaccess redirect all pages to single page

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
    RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]
    

    Error in installation a R package

    After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

    Taking pictures with camera on Android programmatically

    For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.

    Google Chromecast sender error if Chromecast extension is not installed or using incognito

    If you want to temporarily get rid of these console errors (like I did) you can install the extension here: https://chrome.google.com/webstore/detail/google-cast/boadgeojelhgndaghljhdicfkmllpafd/reviews?hl=en

    I left a review asking for a fix. You can also do a bug report via the extension (after you install it) here. Instructions for doing so are here: https://support.google.com/chromecast/answer/3187017?hl=en

    I hope Google gets on this. I need my console to show my errors, etc. Not theirs.

    Add external libraries to CMakeList.txt c++

    I would start with upgrade of CMAKE version.

    You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

    INCLUDE_DIRECTORIES(your/header/dir)
    LINK_DIRECTORIES(your/library/dir)
    rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
    TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
    

    note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

    Hot to get all form elements values using jQuery?

    jQuery has very helpful function called serialize.

    Demo: http://jsfiddle.net/55xnJ/2/

    //Just type:
    $("#preview_form").serialize();
    
    //to get result:
    single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
    

    Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

    I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

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

    I'm targeting API 22, so don't need to explicitly ask for permissions.

    Python Pandas - Find difference between two data frames

    For rows, try this, where Name is the joint index column (can be a list for multiple common columns, or specify left_on and right_on):

    m = df1.merge(df2, on='Name', how='outer', suffixes=['', '_'], indicator=True)
    

    The indicator=True setting is useful as it adds a column called _merge, with all changes between df1 and df2, categorized into 3 possible kinds: "left_only", "right_only" or "both".

    For columns, try this:

    set(df1.columns).symmetric_difference(df2.columns)
    

    When creating a service with sc.exe how to pass in context parameters?

    I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

    {sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}
    

    Git push results in "Authentication Failed"

    May you have changed password recently for you git account You could try the git push with -u option

    git push -u origin branch_name_that_you_want_to_push
    

    After executing above command it will ask for password provide your updated password

    Hope it may help you

    PHP how to get the base domain/url?

    /**
     * Suppose, you are browsing in your localhost 
     * http://localhost/myproject/index.php?id=8
     */
    function getBaseUrl() 
    {
        // output: /myproject/index.php
        $currentPath = $_SERVER['PHP_SELF']; 
    
        // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
        $pathInfo = pathinfo($currentPath); 
    
        // output: localhost
        $hostName = $_SERVER['HTTP_HOST']; 
    
        // output: http://
        $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
    
        // return: http://localhost/myproject/
        return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
    }
    

    How to delete row based on cell value

    If you're file isn't too big you can always sort by the column that has the - and once they're all together just highlight and delete. Then re-sort back to what you want.

    tsc throws `TS2307: Cannot find module` for a local file

    In my case ,

       //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                //{
                //    HotModuleReplacement = true
                //});
    

    i commented it in startup.cs

    Visualizing branch topology in Git

    Tortoise Git has a tool called "Revision Graph". If you're on Windows it's as easy as right click on your repo --> Tortoise Git --> Revision Graph.

    resize font to fit in a div (on one line)

    Today I created a jQuery plugin called jQuery Responsive Headlines that does exactly what you want: it adjusts the font size of a headline to fit inside its containing element (a div, the body or whatever). There are some nice options that you can set to customize the behavior of the plugin and I have also taken the precaution to add support for Ben Altmans Throttle/Debounce functionality to increase performance and ease the load on the browser/computer when the user resizes the window. In it's most simple use case the code would look like this:

    $('h1').responsiveHeadlines();
    

    ...which would turn all h1 on the page elements into responsive one-line headlines that adjust their sizes to the parent/container element.

    You'll find the source code and a longer description of the plugin on this GitHub page.

    Good luck!

    How to printf long long

        // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
        double pi = 2 * acos(0.0);
        int n; // upto 6 digit
        scanf("%d",&n); //precision with which you want the value of pi
        printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision
    

    Extracting text OpenCV

    this is a VB.NET version of the answer from dhanushka using EmguCV.

    A few functions and structures in EmguCV need different consideration than the C# version with OpenCVSharp

    Imports Emgu.CV
    Imports Emgu.CV.Structure
    Imports Emgu.CV.CvEnum
    Imports Emgu.CV.Util
    
            Dim input_file As String = "C:\your_input_image.png"
            Dim large As Mat = New Mat(input_file)
            Dim rgb As New Mat
            Dim small As New Mat
            Dim grad As New Mat
            Dim bw As New Mat
            Dim connected As New Mat
            Dim morphanchor As New Point(0, 0)
    
            '//downsample and use it for processing
            CvInvoke.PyrDown(large, rgb)
            CvInvoke.CvtColor(rgb, small, ColorConversion.Bgr2Gray)
    
            '//morphological gradient
            Dim morphKernel As Mat = CvInvoke.GetStructuringElement(ElementShape.Ellipse, New Size(3, 3), morphanchor)
            CvInvoke.MorphologyEx(small, grad, MorphOp.Gradient, morphKernel, New Point(0, 0), 1, BorderType.Isolated, New MCvScalar(0))
    
            '// binarize
            CvInvoke.Threshold(grad, bw, 0, 255, ThresholdType.Binary Or ThresholdType.Otsu)
    
            '// connect horizontally oriented regions
            morphKernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, New Size(9, 1), morphanchor)
            CvInvoke.MorphologyEx(bw, connected, MorphOp.Close, morphKernel, morphanchor, 1, BorderType.Isolated, New MCvScalar(0))
    
            '// find contours
            Dim mask As Mat = Mat.Zeros(bw.Size.Height, bw.Size.Width, DepthType.Cv8U, 1)  '' MatType.CV_8UC1
            Dim contours As New VectorOfVectorOfPoint
            Dim hierarchy As New Mat
    
            CvInvoke.FindContours(connected, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple, Nothing)
    
            '// filter contours
            Dim idx As Integer
            Dim rect As Rectangle
            Dim maskROI As Mat
            Dim r As Double
            For Each hierarchyItem In hierarchy.GetData
                rect = CvInvoke.BoundingRectangle(contours(idx))
                maskROI = New Mat(mask, rect)
                maskROI.SetTo(New MCvScalar(0, 0, 0))
    
                '// fill the contour
                CvInvoke.DrawContours(mask, contours, idx, New MCvScalar(255), -1)
    
                '// ratio of non-zero pixels in the filled region
                r = CvInvoke.CountNonZero(maskROI) / (rect.Width * rect.Height)
    
                '/* assume at least 45% of the area Is filled if it contains text */
                '/* constraints on region size */
                '/* these two conditions alone are Not very robust. better to use something 
                'Like the number of significant peaks in a horizontal projection as a third condition */
                If r > 0.45 AndAlso rect.Height > 8 AndAlso rect.Width > 8 Then
                    'draw green rectangle
                    CvInvoke.Rectangle(rgb, rect, New MCvScalar(0, 255, 0), 2)
                End If
                idx += 1
            Next
            rgb.Save(IO.Path.Combine(Application.StartupPath, "rgb.jpg"))
    

    ASP.NET IIS Web.config [Internal Server Error]

    If you have python, you can use a package called iis_bridge that solves the problem. To install:

    pip install iis_bridge
    

    then in the python console:

    import iis_bridge as iis
    iis.install()
    

    Form content type for a json HTTP POST?

    I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.

    According to the spec, a POST of json data should have the content-type:
    application/json

    Relevant portion of the HTML spec

    6.7 Content types (MIME types)
    ...
    Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".

    17.13.4 Form content types
    ...
    application/x-www-form-urlencoded
    This is the default content type. Forms submitted with this content type must be encoded as follows

    Relevant portion of the JSON spec

    1. IANA Considerations
      The MIME media type for JSON text is application/json.

    What is the best way to redirect a page using React Router?

    You also can Redirect within the Route as follows. This is for handle invalid routes.

    <Route path='*' render={() => 
         (
           <Redirect to="/error"/>
         )
    }/>
    

    How to output HTML from JSP <%! ... %> block?

    You can do something like this:

    <%!
    String myMethod(String input) {
        return "test " + input;
    }
    %>
    
    <%= myMethod("1 2 3") %>
    

    This will output test 1 2 3 to the page.

    How to get progress from XMLHttpRequest

    One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

    YAML mapping values are not allowed in this context

    This is valid YAML:

    jobs:
     - name: A
       schedule: "0 0/5 * 1/1 * ? *"
       type: mongodb.cluster
       config:
         host: mongodb://localhost:27017/admin?replicaSet=rs
         minSecondaries: 2
         minOplogHours: 100
         maxSecondaryDelay: 120
     - name: B
       schedule: "0 0/5 * 1/1 * ? *"
       type: mongodb.cluster
       config:
         host: mongodb://localhost:27017/admin?replicaSet=rs
         minSecondaries: 2
         minOplogHours: 100
         maxSecondaryDelay: 120
    

    Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

    How to add text to a WPF Label in code?

    I believe you want to set the Content property. This has more information on what is available to a label.

    Commit empty folder structure (with git)

    In Git, you cannot commit empty folders, because Git does not actually save folders, only files. You'll have to create some placeholder file inside those directories if you actually want them to be "empty" (i.e. you have no committable content).

    How to use Elasticsearch with MongoDB?

    I found mongo-connector useful. It is form Mongo Labs (MongoDB Inc.) and can be used now with Elasticsearch 2.x

    Elastic 2.x doc manager: https://github.com/mongodb-labs/elastic2-doc-manager

    mongo-connector creates a pipeline from a MongoDB cluster to one or more target systems, such as Solr, Elasticsearch, or another MongoDB cluster. It synchronizes data in MongoDB to the target then tails the MongoDB oplog, keeping up with operations in MongoDB in real-time. It has been tested with Python 2.6, 2.7, and 3.3+. Detailed documentation is available on the wiki.

    https://github.com/mongodb-labs/mongo-connector https://github.com/mongodb-labs/mongo-connector/wiki/Usage%20with%20ElasticSearch

    Simple PHP form: Attachment to email (code golf)

    I haven't tested the email part of this (my test box does not send email) but I think it will work.

    <?php
    if ($_POST) {
    $s = md5(rand());
    mail('[email protected]', 'attachment', "--$s
    
    {$_POST['m']}
    --$s
    Content-Type: application/octet-stream; name=\"f\"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment
    
    ".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
    --$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
    exit;
    }
    ?>
    <form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <textarea name="m"></textarea><br>
    <input type="file" name="f"/><br>
    <input type="submit">
    </form>
    

    Checking if a variable is defined?

    As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean.

    But if you absolutely need a boolean. Use !! (bang bang) or "falsy falsy reveals the truth".

    › irb
    >> a = nil
    => nil
    >> defined?(a)
    => "local-variable"
    >> defined?(b)
    => nil
    >> !!defined?(a)
    => true
    >> !!defined?(b)
    => false
    

    Why it doesn't usually pay to coerce:

    >> (!!defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red)) == (defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red))
    => true
    

    Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.

    >> puts "var is defined? #{!!defined?(a)} vs #{defined?(a)}"
    var is defined? true vs local-variable
    => nil
    

    Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

    My problem was the cocoa pods version so I installed the latest with: sudo gem install cocoapods --pre Then pod update

    That worked for me

    AltGr key not working, instead I have to use Ctrl+AltGr

    I found a solution for my problem while writing my question !

    Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

    I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

    So it seems the problem comes from the use of RDP (windows7 and 8)

    Update 2017: Problem occurs on Windows 10 aswell.

    How to compare two dates in Objective-C

    This category offers a neat way to compare NSDates:

    #import <Foundation/Foundation.h>
    
    @interface NSDate (Compare)
    
    -(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
    -(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
    -(BOOL) isLaterThan:(NSDate*)date;
    -(BOOL) isEarlierThan:(NSDate*)date;
    //- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API
    
    @end
    

    And the implementation:

    #import "NSDate+Compare.h"
    
    @implementation NSDate (Compare)
    
    -(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
        return !([self compare:date] == NSOrderedAscending);
    }
    
    -(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
        return !([self compare:date] == NSOrderedDescending);
    }
    -(BOOL) isLaterThan:(NSDate*)date {
        return ([self compare:date] == NSOrderedDescending);
    
    }
    -(BOOL) isEarlierThan:(NSDate*)date {
        return ([self compare:date] == NSOrderedAscending);
    }
    
    @end
    

    Simple to use:

    if([aDateYouWantToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
    {
        // do your thing ...
    }
    

    Why does ASP.NET webforms need the Runat="Server" attribute?

    I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.

    This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):

    [...] but the importance of <runat="server"> is more for consistency and extensibility.

    If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.

    It continues:

    If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.

    He continues:

    Currently, If my guess is correct, the parser simply ignores all text (tags or no tags) unless it is a tag with the runat=server attribute or a “<%” prefix or ssi “<!– #include(...) Also, since ASP.NET is designed to allow separation of the web designers (foo.aspx) from the web developers (foo.aspx.vb), the web designers can use their own web designer tools to place HTML and client-side JavaScript without having to know about ASP.NET specific tags or attributes.