Programs & Examples On #Mean

The arithmetic mean (or simply the mean or average when the context is clear) is the central tendency of a collection of numbers. The mean is calculated as the sum of the numbers divided by the size of the collection.

Mean Squared Error in Numpy?

Even more numpy

np.square(np.subtract(A, B)).mean()

Mean of a column in a data frame, given the column's name

I think you're asking how to compute the mean of a variable in a data frame, given the name of the column. There are two typical approaches to doing this, one indexing with [[ and the other indexing with [:

data(iris)
mean(iris[["Petal.Length"]])
# [1] 3.758
mean(iris[,"Petal.Length"])
# [1] 3.758
mean(iris[["Sepal.Width"]])
# [1] 3.057333
mean(iris[,"Sepal.Width"])
# [1] 3.057333

Calculating arithmetic mean (one type of average) in Python

I always supposed avg is omitted from the builtins/stdlib because it is as simple as

sum(L)/len(L) # L is some list

and any caveats would be addressed in caller code for local usage already.

Notable caveats:

  1. non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L) or from __future__ import division

  2. division by zero: the list may be empty. to resolve:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    

np.mean() vs np.average() in Python NumPy?

In some version of numpy there is another imporant difference that you must be aware:

average do not take in account masks, so compute the average over the whole set of data.

mean takes in account masks, so compute the mean only over unmasked values.

g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)

np.average(f)
Out: 34.0

np.mean(f)
Out: 2.0

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Improving on the answer by musiphil, you can write a standard deviation function without the temporary vector diff, just using a single inner_product call with the C++11 lambda capabilities:

double stddev(std::vector<double> const & func)
{
    double mean = std::accumulate(func.begin(), func.end(), 0.0) / func.size();
    double sq_sum = std::inner_product(func.begin(), func.end(), func.begin(), 0.0,
        [](double const & x, double const & y) { return x + y; },
        [mean](double const & x, double const & y) { return (x - mean)*(y - mean); });
    return std::sqrt(sq_sum / func.size());
}

I suspect doing the subtraction multiple times is cheaper than using up additional intermediate storage, and I think it is more readable, but I haven't tested the performance yet.

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

calculate the mean for each column of a matrix in R

class(mtcars)
my.mean <- unlist(lapply(mtcars, mean)); my.mean



   mpg        cyl       disp         hp       drat         wt       qsec         vs 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500 
        am       gear       carb 
  0.406250   3.687500   2.812500 

How to secure the ASP.NET_SessionId cookie?

Adding onto @JoelEtherton's solution to fix a newly found security vulnerability. This vulnerability happens if users request HTTP and are redirected to HTTPS, but the sessionid cookie is set as secure on the first request to HTTP. That is now a security vulnerability, according to McAfee Secure.

This code will only secure cookies if request is using HTTPS. It will expire the sessionid cookie, if not HTTPS.

    // this code will mark the forms authentication cookie and the
    // session cookie as Secure.
    if (Request.IsSecureConnection)
    {
        if (Response.Cookies.Count > 0)
        {
            foreach (string s in Response.Cookies.AllKeys)
            {
                if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
                {
                    Response.Cookies[s].Secure = true;
                }
            }
        }
    }
    else
    {
        //if not secure, then don't set session cookie
        Response.Cookies["asp.net_sessionid"].Value = string.Empty;
        Response.Cookies["asp.net_sessionid"].Expires = new DateTime(2018, 01, 01);
    }

No Exception while type casting with a null in java

This is by design. You can cast null to any reference type. Otherwise you wouldn't be able to assign it to reference variables.

Set focus to field in dynamically loaded DIV

If

$("#header").focus();

is not working then is there another element on your page with the id of header?

Use firebug to run $("#header") and see what it returns.

What is the default maximum heap size for Sun's JVM from Java SE 6?

With JDK, You can also use jinfo to connect to the JVM for the <PROCESS_ID> in question and get the value for MaxHeapSize:

jinfo -flag MaxHeapSize <PROCESS_ID>

DBMS_OUTPUT.PUT_LINE not printing

I am using Oracle SQL Developer,

In this tool, I had to enable DBMS output to view the results printed by dbms_output.put_line

You can find this option in the result pane where other query results are displayed. so, in the result pane, I have 7 tabs. 1st tab named as Results, next one is Script Output and so on. Out of this you can find a tab named as "DBMS Output" select this tab, then the 1st icon (looks like a dialogue icon) is Enable DBMS Output. Click this icon. Then you execute the PL/SQL, then select "DBMS Output tab, you should be able to see the results there.

How do I revert a Git repository to a previous commit?

There are many answers that provide removing the last commit. However, here is asked how to remove specific commits, and in this case it is to remove the last three commits, to go back to commit on November 3.

You can do this with rebase. Simply do:

git rebase -i HEAD~4

This will list your last four commits.

Now you have the option to remove commits. You do that with drop text.

  • Simply hit i on your keyboard and next to commits you want to remove write drop instead of default pick

  • On the keyboard, hit exit and :wq

To make sure that commits are removed, write:

git log

You will see that commits you saved as drop are removed.

To push those changes to your remote branch, write:

git push --force

Detect when input has a 'readonly' attribute

try this:

if($('input').attr('readonly') == undefined){
    alert("foo");
}

if it is not there it will be undefined in js

Change key pair for ec2 instance

This will work only if you have access to the instance you want to change/add the key in. You can create a new key pair. Or if you already have the key pair, then you can paste the public key of the new pair in the authorized_keys file on your instance.

vim .ssh/authorized_keys

Now you can use the private key for that pair and log in.

Hope this helps.

break out of if and foreach

For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

Merge unequal dataframes and replace missing rows with 0

Assuming df1 has all the values of x of interest, you could use a dplyr::left_join() to merge and then either a base::replace() or tidyr::replace_na() to replace the NAs as 0s:

library(tidyverse)

# dplyr only:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace(y, is.na(y), 0))

# dplyr and tidyr:
df_new <- 
  left_join(df1, df2, by = 'x') %>% 
  mutate(y = replace_na(y, 0))

# In the sample data column `x` is a factor, which will give a warning with the join. This can be prevented by converting to a character before the join:
df_new <- 
  left_join(df1 %>% mutate(x = as.character(x)), 
            df2 %>% mutate(x = as.character(x)), 
            by = 'x') %>% 
    mutate(y = replace(y, is.na(y), 0))

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

UIWebView open links in Safari

The accepted answer does not work.

If your page loads URLs via Javascript, the navigationType will be UIWebViewNavigationTypeOther. Which, unfortunately, also includes background page loads such as analytics.

To detect page navigation, you need to compare the [request URL] to the [request mainDocumentURL].

This solution will work in all cases:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
    if ([[request URL] isEqual:[request mainDocumentURL]])
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    else
    {       
        return YES;
    }
}

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

Create an array of integers property in Objective-C

I found all the previous answers too much complicated. I had the need to store an array of some ints as a property, and found the ObjC requirement of using a NSArray an unneeded complication of my software.

So I used this:

typedef struct my10ints {
    int arr[10];
} my10ints;

@interface myClasss : NSObject

@property my10ints doubleDigits;

@end

This compiles cleanly using Xcode 6.2.

My intention was to use it like this:

myClass obj;
obj.doubleDigits.arr[0] = 4;

HOWEVER, this does not work. This is what it produces:

int i = 4;
myClass obj;
obj.doubleDigits.arr[0] = i;
i = obj.doubleDigits.arr[0];
// i is now 0 !!!

The only way to use this correctly is:

int i = 4;
myClass obj;
my10ints ints;
ints = obj.doubleDigits;
ints.arr[0] = i;
obj.doubleDigits = ints;
i = obj.doubleDigits.arr[0];
// i is now 4

and so, defeats completely my point (avoiding the complication of using a NSArray).

PHP - count specific array values

If you want to count ALL the same occurences inside the array, here's a function to count them all, and return the results as a multi-dimensional array:

function countSame($array) {

$count = count($array);
$storeArray = array();
while ($count > 0) {
$count--;

if ($array[$count]) {
$a = $array[$count];
$counts = array_count_values($array);
$counts = $counts[$a];
$tempArray = array($a, $counts);
array_push($storeArray, $tempArray);

$keys = array_keys($array, $a);
foreach ($keys as $k) {
unset($array[$k]);
} //end of foreach ($keys as $k)
} //end of if ($array[$count])

} //end of while ($count > 0)

return $storeArray;

} //end of function countSame($array)

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

NodeJS - What does "socket hang up" actually mean?

it's been a long time but another case is when performing requests which takes a long time on the server side (more then 2 minutes which is the default for express) and the timeout parameter was not configured in the server side. In my case I was doing client->server->server request (Node.js express) and I should set the timeout parameter on each request router on the server and on the client. So in both servers I needed to set the request timeout by using

req.setTimeout([your needed timeout])

on the router.

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

CLEAR SCREEN - Oracle SQL Developer shortcut?

Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.

Run script.

Alt+PgDn     -  puts you in Script Output panel.
Ctrl+Shift+D -  clears panel.
Alt+PgUp     -  puts you back in editor panel. 

Java Enum return Int

Do you want to this code?

public static enum FieldIndex {
    HDB_TRX_ID,     //TRX ID
    HDB_SYS_ID      //SYSTEM ID
}

public String print(ArrayList<String> itemName){
    return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}

Compare two List<T> objects for equality, ignoring order

This is a slightly difficult problem, which I think reduces to: "Test if two lists are permutations of each other."

I believe the solutions provided by others only indicate whether the 2 lists contain the same unique elements. This is a necessary but insufficient test, for example {1, 1, 2, 3} is not a permutation of {3, 3, 1, 2} although their counts are equal and they contain the same distinct elements.

I believe this should work though, although it's not the most efficient:

static bool ArePermutations<T>(IList<T> list1, IList<T> list2)
{
   if(list1.Count != list2.Count)
         return false;

   var l1 = list1.ToLookup(t => t);
   var l2 = list2.ToLookup(t => t);

   return l1.Count == l2.Count 
       && l1.All(group => l2.Contains(group.Key) && l2[group.Key].Count() == group.Count()); 
}

how to run a command at terminal from java program?

As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.

xterm -e any command

In Java code this becomes:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Runtime.getRuntime().exec(command);

Or, using ProcessBuilder:

String[] command = { "xterm", "-e", "my", "command", "with", "parameters" };
Process proc = new ProcessBuilder(command).start();

Connect different Windows User in SQL Server Management Studio (2005 or later)

For Windows 10: Go to the Sql Management Studio Icon, or Short Cut in the menu: Right Click > Select Open File Location

enter image description here

Hold Shift and right Click the shortcut, or ssms.exe file that is in the folder. Holding shift will give you an extra option "Run as different user":

enter image description here

This will pop up a login box and you can type the credentials you would like your session to run under.

How to fix "Attempted relative import in non-package" even with __init__.py

Try this

import components
from components import *

What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

Git Symlinks in Windows

One simple trick we use is to just call git add --all twice in a row.

For example, our Windows 7 commit script calls:

$ git add --all
$ git add --all

The first add treats the link as text and adds the folders for delete.

The second add traverses the link correctly and undoes the delete by restoring the files.

It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.

How do I export a project in the Android studio?

1.- Export signed packages:

  • Use the Extract a Signed Android Application Package Wizard (On the main menu, choose Build | Generate Signed APK). The package will be signed during extraction.

    OR

  • Configure the .apk file as an artifact by creating an artifact definition of the type Android application with the Release signed package mode.

2.- Export unsigned packages: this can only be done through artifact definitions with the Debug or Release unsigned package mode specified.

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Using Angular?

This is a very important caveat to remember.

The base tag needs to not only be in the head but in the right location.

I had my base tag in the wrong place in the head, it should come before any tags with url requests. Basically placing it as the second tag underneath the title solved it for me.

<base href="/">

I wrote a little post on it here

How to delete zero components in a vector in Matlab?

Why not just, a=a(~~a) or a(~a)=[]. It's equivalent to the other approaches but certainly less key strokes.

val() doesn't trigger change() in jQuery

It looks like the events are not bubbling. Try this:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

I tried just a plain old $("#mytext").trigger('change') without saving the old value, and the .change fires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change') only if it changes.

Fill username and password using selenium in python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

# If you want to open Chrome
driver = webdriver.Chrome()
# If you want to open Firefox
driver = webdriver.Firefox()

username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
username.send_keys("YourUsername")
password.send_keys("YourPassword")
driver.find_element_by_id("submit_btn").click()

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

How do I format axis number format to thousands with a comma in matplotlib?

x = [10000.21, 22000.32, 10120.54]

Perhaps make a list (comprehension) for the labels, and then apply them "manually".

xlables = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

How do I write stderr to a file while using "tee" with a pipe?

In my case, a script was running command while redirecting both stdout and stderr to a file, something like:

cmd > log 2>&1

I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1 and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout and stderr to different files, which is not what I want, but it helped me to come up with the exact solution that I need:

(cmd 2> >(tee /dev/stderr)) > log

With the above, log will have a copy of both stdout and stderr and I can capture stderr from my script without having to worry about stdout.

How can I return the difference between two lists?

You can use CollectionUtils from Apache Commons Collections 4.0:

new ArrayList<>(CollectionUtils.subtract(a, b))

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

I meet this error too when I run a wordpress on my Fedora system.

I googled it, and find a way to fix this.

Maybe this will help you too.

  1. check mysql config : my.cnf

     cat /etc/my.cnf | grep tmpdir
    

    I can't see anything in my my.cnf

  2. add tmpdir=/tmp to my.cnf under [mysqld]

  3. restart web/app and mysql server

    /etc/init.d/mysqld restart

How to display a "busy" indicator with jQuery?

I had to use

HTML:
   <img id="loading" src="~/Images/spinner.gif" alt="Updating ..." style="display: none;" />

In script file:
  // invoked when sending ajax request
  $(document).ajaxSend(function () {
      $("#loading").show();
  });

  // invoked when sending ajax completed
  $(document).ajaxComplete(function () {
      $("#loading").hide();
  });

How to synchronize a static variable among threads running different instances of a class in Java?

You can synchronize your code over the class. That would be simplest.

   public class Test  
    {  
       private static int count = 0;  
       private static final Object lock= new Object();    
       public synchronized void foo() 
      {  
          synchronized(Test.class)
         {  
             count++;  
         }  
      }  
    }

Hope you find this answer useful.

Is it possible to set a custom font for entire of application?

In summary:

Option#1: Use reflection to apply font (combining weston & Roger Huang's answer):

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;

public final class FontsOverride { 

    public static void setDefaultFont(Context context,
            String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    } 

    protected static void replaceFont(String staticTypefaceFieldName,final Typeface newTypeface) {
        if (isVersionGreaterOrEqualToLollipop()) {
            Map<String, Typeface> newMap = new HashMap<String, Typeface>();
            newMap.put("sans-serif", newTypeface);
            try {
                final Field staticField = Typeface.class.getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
                staticField.setAccessible(true);
                staticField.set(null, newTypeface);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } 
        }
    }

} 

Usage in Application class:

public final class Application extends android.app.Application {
    @Override 
    public void onCreate() { 
        super.onCreate(); 
        FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
        FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
        FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
        FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
    } 
} 

set up a style to force that font typeface application wide (based on lovefish):

Pre-Lollipop:

<resources>
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    </style>

   <!-- Application theme. -->
   <style name="AppTheme" parent="AppBaseTheme">
       <item name="android:typeface">monospace</item>
   </style>
</resources>

Lollipop (API 21):

<resources>
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    </style>

   <!-- Application theme. -->
   <style name="AppTheme" parent="AppBaseTheme">
       <item name="android:textAppearance">@style/CustomTextAppearance</item>
   </style>

   <style name="CustomTextAppearance">
       <item name="android:typeface">monospace</item>
   </style>
</resources>

Option2: Subclass each and every View where you need to customize font, ie. ListView, EditTextView, Button, etc. (Palani's answer):

public class CustomFontView extends TextView {

public CustomFontView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(); 
} 

public CustomFontView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(); 
} 

public CustomFontView(Context context) {
    super(context);
    init(); 
} 

private void init() { 
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
        setTypeface(tf);
    } 
} 

Option 3: Implement a View Crawler that traverses through the view hierarchy of your current screen:

Variation#1 (Tom's answer):

public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect)
{ 
    if (mContainer == null || mFont == null) return;

    final int mCount = mContainer.getChildCount();

    // Loop through all of the children. 
    for (int i = 0; i < mCount; ++i)
    { 
        final View mChild = mContainer.getChildAt(i);
        if (mChild instanceof TextView)
        { 
            // Set the font if it is a TextView. 
            ((TextView) mChild).setTypeface(mFont);
        } 
        else if (mChild instanceof ViewGroup)
        { 
            // Recursively attempt another ViewGroup. 
            setAppFont((ViewGroup) mChild, mFont);
        } 
        else if (reflect)
        { 
            try { 
                Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
                mSetTypeface.invoke(mChild, mFont); 
            } catch (Exception e) { /* Do something... */ }
        } 
    } 
} 

Usage :

final ViewGroup mContainer = (ViewGroup) findViewById(
android.R.id.content).getRootView();
HomeActivity.setAppFont(mContainer, Typeface.createFromAsset(getAssets(),
"fonts/MyFont.ttf"));

Variation#2: https://coderwall.com/p/qxxmaa/android-use-a-custom-font-everywhere.

Option #4: Use 3rd Party Lib called Calligraphy.

Personally, I would recommend Option#4, as it saves a lot of headaches.

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

ASP.NET MVC 404 Error Handling

Looks like this is the best way to catch everything.

How can I properly handle 404 in ASP.NET MVC?

Output data with no column headings using PowerShell

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

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

How to convert HTML to PDF using iTextSharp

First, HTML and PDF are not related although they were created around the same time. HTML is intended to convey higher level information such as paragraphs and tables. Although there are methods to control it, it is ultimately up to the browser to draw these higher level concepts. PDF is intended to convey documents and the documents must "look" the same wherever they are rendered.

In an HTML document you might have a paragraph that's 100% wide and depending on the width of your monitor it might take 2 lines or 10 lines and when you print it it might be 7 lines and when you look at it on your phone it might take 20 lines. A PDF file, however, must be independent of the rendering device, so regardless of your screen size it must always render exactly the same.

Because of the musts above, PDF doesn't support abstract things like "tables" or "paragraphs". There are three basic things that PDF supports: text, lines/shapes and images. (There are other things like annotations and movies but I'm trying to keep it simple here.) In a PDF you don't say "here's a paragraph, browser do your thing!". Instead you say, "draw this text at this exact X,Y location using this exact font and don't worry, I've previously calculated the width of the text so I know it will all fit on this line". You also don't say "here's a table" but instead you say "draw this text at this exact location and then draw a rectangle at this other exact location that I've previously calculated so I know it will appear to be around the text".

Second, iText and iTextSharp parse HTML and CSS. That's it. ASP.Net, MVC, Razor, Struts, Spring, etc, are all HTML frameworks but iText/iTextSharp is 100% unaware of them. Same with DataGridViews, Repeaters, Templates, Views, etc. which are all framework-specific abstractions. It is your responsibility to get the HTML from your choice of framework, iText won't help you. If you get an exception saying The document has no pages or you think that "iText isn't parsing my HTML" it is almost definite that you don't actually have HTML, you only think you do.

Third, the built-in class that's been around for years is the HTMLWorker however this has been replaced with XMLWorker (Java / .Net). Zero work is being done on HTMLWorker which doesn't support CSS files and has only limited support for the most basic CSS properties and actually breaks on certain tags. If you do not see the HTML attribute or CSS property and value in this file then it probably isn't supported by HTMLWorker. XMLWorker can be more complicated sometimes but those complications also make it more extensible.

Below is C# code that shows how to parse HTML tags into iText abstractions that get automatically added to the document that you are working on. C# and Java are very similar so it should be relatively easy to convert this. Example #1 uses the built-in HTMLWorker to parse the HTML string. Since only inline styles are supported the class="headline" gets ignored but everything else should actually work. Example #2 is the same as the first except it uses XMLWorker instead. Example #3 also parses the simple CSS example.

//Create a byte array that will eventually hold our final PDF
Byte[] bytes;

//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream()) {

    //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document()) {

        //Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms)) {

            //Open the document for writing
            doc.Open();

            //Our sample HTML and CSS
            var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
            var example_css = @".headline{font-size:200%}";

            /**************************************************
             * Example #1                                     *
             *                                                *
             * Use the built-in HTMLWorker to parse the HTML. *
             * Only inline CSS is supported.                  *
             * ************************************************/

            //Create a new HTMLWorker bound to our document
            using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) {

                //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
                using (var sr = new StringReader(example_html)) {

                    //Parse the HTML
                    htmlWorker.Parse(sr);
                }
            }

            /**************************************************
             * Example #2                                     *
             *                                                *
             * Use the XMLWorker to parse the HTML.           *
             * Only inline CSS and absolutely linked          *
             * CSS is supported                               *
             * ************************************************/

            //XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(example_html)) {

                //Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            /**************************************************
             * Example #3                                     *
             *                                                *
             * Use the XMLWorker to parse HTML and CSS        *
             * ************************************************/

            //In order to read CSS as a string we need to switch to a different constructor
            //that takes Streams instead of TextReaders.
            //Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams
            using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
                using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {

                    //Parse the HTML
                    iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                }
            }


            doc.Close();
        }
    }

    //After all of the PDF "stuff" above is done and closed but **before** we
    //close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

//Now we just need to do something with those bytes.
//Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
//You could also write the bytes to a database in a varbinary() column (but please don't) or you
//could pass them to another function for further PDF processing.
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);

2017's update

There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation this year, after tests.

As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Exim 4 requires that AUTH command only be sent after the client issued EHLO - attempts to authenticate without EHLO would be rejected. Some mailservers require that EHLO be issued twice. PHPMailer apparently fails to do so. If PHPMailer does not allow you to force EHLO initiation, you really should switch to SwiftMailer 4.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How do I get the type of a variable?

If you have a variable

int k;

You can get its type using

cout << typeid(k).name() << endl;

See the following thread on SO: Similar question

What is IPV6 for localhost and 0.0.0.0?

As we all know that IPv4 address for localhost is 127.0.0.1 (loopback address).

Actually, any IPv4 address in 127.0.0.0/8 is a loopback address.

In IPv6, the direct analog of the loopback range is ::1/128. So ::1 (long form 0:0:0:0:0:0:0:1) is the one and only IPv6 loopback address.


While the hostname localhost will normally resolve to 127.0.0.1 or ::1, I have seen cases where someone has bound it to an IP address that is not a loopback address. This is a bit crazy ... but sometimes people do it.

I say "this is crazy" because you are liable to break applications assumptions by doing this; e.g. an application may attempt to do a reverse lookup on the loopback IP and not get the expected result. In the worst case, an application may end up sending sensitive traffic over an insecure network by accident ... though you probably need to make other mistakes as well to "achieve" that.


Blocking 0.0.0.0 makes no sense. In IPv4 it is never routed. The equivalent in IPv6 is the :: address (long form 0:0:0:0:0:0:0:0) ... which is also never routed.

The 0.0.0.0 and :: addresses are reserved to mean "any address". So, for example a program that is providing a web service may bind to 0.0.0.0 port 80 to accept HTTP connections via any of the host's IPv4 addresses. These addresses are not valid as a source or destination address for an IP packet.


Finally, some comments were asking about ::/128 versus ::/0 versus ::.

What is this difference?

Strictly speaking, the first two are CIDR notation not IPv6 addresses. They are actually specifying a range of IP addresses. A CIDR consists of a IP address and an additional number that specifies the number of bits in a netmask. The two together specify a range of addresses; i.e. the set of addresses formed by ignoring the bits masked out of the given address.

So:

  • :: means just the IPv6 address 0:0:0:0:0:0:0:0
  • ::/128 means 0:0:0:0:0:0:0:0 with a netmask consisting of 128 bits. This gives a network range with exactly one address in it.
  • ::/0 means 0:0:0:0:0:0:0:0 with a netmask consisting of 0 bits. This gives a network range with 2128 addresses in it.; i.e. it is the entire IPv6 address space!

For more information, read the Wikipedia pages on IPv4 & IPv6 addresses, and CIDR notation:

Way to ng-repeat defined number of times instead of repeating over array?

This is really UGLY, but it works without a controller for either an integer or variable:

integer:

<span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>

variable:

<span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>

scp with port number specified

if you need copy local file to server (specify port )

scp -P 3838 /the/source/file [email protected]:/destination/file

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Ignoring the check results in a corrupted install. This is the only solution that worked for me:

  1. Create a C# console app with the following code: Console.WriteLine(string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0"));

  2. Run the app and get the 3 digit code.

  3. Run > Regedit, open the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib

Now, if you don't have a folder underneath that path with the 3 digit code from step 2, create it. If you do have the folder, check that it has the "Counter" and "Help" values set under that path. It probably doesn't -- which is why the check fails.

Create the missing Counter and Help keys (REG_MULTI_SZ). For the values, copy them from the existing path above (probably 009).

The check should now pass.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

First include stdlib.h

#include<stdlib.h>

Then following can be a function to generate random double number between a range in C programming language.

double randomDouble() {
    double lowerRange = 1.0;
    double upperRange = 10.0;
    return ((double)rand() * (upperRange - lowerRange)) / (double)RAND_MAX + lowerRange;
}

Here RAND_MAX is defined in stdlib.h

Update values from one column in same table to another in SQL Server

You put select query before update queries, so you just see initial data. Put select * from stuff; to the end of list.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

CSS Font Border?

There's an experimental CSS property called text-stroke, supported on some browsers behind a -webkit prefix.

_x000D_
_x000D_
h1 {_x000D_
    -webkit-text-stroke: 2px black; /* width and color */_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

Another possible trick would be to use four shadows, one pixel each on all directions, using property text-shadow:

_x000D_
_x000D_
h1 {_x000D_
    /* 1 pixel black shadow to left, top, right and bottom */_x000D_
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

But it would get blurred for more than 1 pixel thickness.

HowTo Generate List of SQL Server Jobs and their owners

There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:

Run the script in your PowerShell ISE:

Loads SQL Powerhell SMO and commands:

Import-Module SQLPS -disablenamechecking

BUild list of Servers manually (this builds an array list):

$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
    ## - Add Code block:
    $MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
    DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto 
    ## - End of Code block
}

How to install package from github repo in Yarn

You can add any Git repository (or tarball) as a dependency to yarn by specifying the remote URL (either HTTPS or SSH):

yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.

Here are some examples:

yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0  [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]

(Note: Fancybox v2.6.1 isn't available in the Git version.)

To support both npm and yarn, you can use the git+url syntax:

git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch

String comparison technique used by Python

Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:

(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc

(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)

(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'

Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character) and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.

Calling dynamic function with dynamic number of parameters

The simplest way might be:

var func='myDynamicFunction_'+myHandler;
var arg1 = 100, arg2 = 'abc';

window[func].apply(null,[arg1, arg2]);

Assuming, that target function is already attached to a "window" object.

How to use a ViewBag to create a dropdownlist?

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // ??????? ?? ?????? ???? ????? ??? ??? ?? ???
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('??? ??')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('????? ?? ???')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}

Best way to change font colour halfway through paragraph?

<span style="color:orange;">orange text</span>

Is the only way I know of barring the font tag.

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

How to clear basic authentication details in chrome

The authentication is cleared when you exit Chrome.

Note however, that by default Chrome is running apps in the background, so it may not really exit even if you close all Chrome windows. You can either change this behavior under advanced setting, or e.g. under Windows, you can completely exit Chrome by using the Chrome icon in the systray. There should be an icon if Chrome is still running, but maybe you'll find it only in the popup with the hidden icons. The context menu of the Chrome icon has an entry to completely exit Chrome, and you can also change the setting for running apps in the background using that menu.

  1. Open the Chrome menu
  2. Select Settings
  3. Scroll to the bottom
  4. Click Show advanced settings...
  5. Scroll to the bottom
  6. Under System uncheck the box labeled:
    Continue running background apps when Google Chrome is closed

Pass in an enum as a method parameter

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum.

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

Then when you call your method you pass the SupportedPermissions value to your method

  var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);

Remove grid, background color, and top and right borders from ggplot2

Here's an extremely simple answer

yourPlot +
  theme(
    panel.border = element_blank(), 
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black")
    )

It's that easy. Source: the end of this article

Can I set state inside a useEffect hook

Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

useEffect is called after each render and when setState is used inside of it, it will cause the component to re-render which will call useEffect and so on and so on.

One of the popular cases that using useState inside of useEffect will not cause an infinite loop is when you pass an empty array as a second argument to useEffect like useEffect(() => {....}, []) which means that the effect function should be called once: after the first mount/render only. This is used widely when you're doing data fetching in a component and you want to save the request data in the component's state.

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files

How to force link from iframe to be opened in the parent window

<a target="parent"> will open links in a new tab/window ... <a target="_parent"> will open links in the parent/current window, without opening new tabs/windows. Don't_forget_that_underscore!

Array.push() if does not exist?

Here you have a way to do it in one line for two arrays:

const startArray = [1,2,3,4]
const newArray = [4,5,6]

const result = [...startArray, ...newArray.filter(a => !startArray.includes(a))]

console.log(result);
//Result: [1,2,3,4,5,6]

How to output to the console and file?

Probably the shortest solution:

def printLog(*args, **kwargs):
    print(*args, **kwargs)
    with open('output.out','a') as file:
        print(*args, **kwargs, file=file)

printLog('hello world')

Writes 'hello world' to sys.stdout and to output.out and works exactly the same way as print().

Note: Please do not specify the file argument for the printLog function. Calls like printLog('test',file='output2.out') are not supported.

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Remove an array element and shift the remaining ones

Just so it be noted: If the requirement to preserve the elements order is relaxed it is much more efficient to replace the element being removed with the last element.

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

This is what helped me when I found myself in the same problem:

npm uninstall -g angular-cli @angular/cli
npm cache clean --force
npm install -g @angular/cli@latest

Bootstrap full-width text-input within inline-form

The bootstrap docs says about this:

Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.

The default width of 100% as all form elements gets when they got the class form-control didn't apply if you use the form-inline class on your form.

You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:

.form-inline {

  // Kick in the inline
  @media (min-width: @screen-sm-min) {
    // Inline-block all the things for "inline"
    .form-group {
      display: inline-block;
      margin-bottom: 0;
      vertical-align: middle;
    }

    // In navbar-form, allow folks to *not* use `.form-group`
    .form-control {
      display: inline-block;
      width: auto; // Prevent labels from stacking above inputs in `.form-group`
      vertical-align: middle;
    }
    // Input groups need that 100% width though
    .input-group > .form-control {
      width: 100%;
    }

    [...]
  }
}

Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):

<div class="row">
   <div class="col-lg-12">
    <div class="input-group input-group-lg">
      <input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
      <span class="input-group-btn">
        <button class="btn btn-default btn-lg" type="submit">Search</button>
      </span>
    </div>
  </div>
</div>

Why are C++ inline functions in the header?

Because the compiler needs to see them in order to inline them. And headers files are the "components" which are commonly included in other translation units.

#include "file.h"
// Ok, now me (the compiler) can see the definition of that inline function. 
// So I'm able to replace calls for the actual implementation.

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

Shorter and dealing with a column (entire, not just a section of a column):

=COUNTA(A:A)

COUNTA

Beware, a cell containing just a space would be included in the count.

brew install mysql on macOS

Just to add something to previous answers - When upgrading from MySql 5.6 to MySql 8.0, I followed the steps provided here to make a clean uninstall, yet I got following errors

2019-11-05T07:57:31.359304Z 0 [ERROR] [MY-000077] [Server] /usr/local/Cellar/mysql/8.0.18/bin/mysqld: Error while setting value 'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' to 'sql_mode'.
2019-11-05T07:57:31.359330Z 0 [ERROR] [MY-013236] [Server] The designated data directory /usr/local/var/mysql is unusable. You can remove all files that the server added to it.
2019-11-05T07:57:31.359413Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-11-05T07:57:31.359514Z 0 [Note] [MY-010120] [Server] Binlog end

Took me some time to figure it out. Found a clue here: https://discourse.brew.sh/t/clean-removal-of-mysql/2251

So, the key to my problem was removing /usr/local/etc/my.cnf file after uninstall. After that one last step, MySql finally started working.

REST API - file (ie images) processing - best practices

OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)

After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.

If you have a special endpoint for images, it gives you much more power over handling those images.

We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.

Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".

The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).

Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.


Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.

There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.

Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.

How do I list one filename per output line in Linux?

Yes, you can easily make ls output one filename per line:

ls -a | cat

Explanation: The command ls senses if the output is to a terminal or to a file or pipe and adjusts accordingly.

So, if you pipe ls -a to python it should work without any special measures.

how to bold words within a paragraph in HTML/CSS?

<p><b> BOLD TEXT </b> not in bold </p>;

Include the text you want to be in bold between <b>...</b>

Set value of hidden input with jquery

You don't need to set name , just giving an id is enough.

<input type="hidden" id="testId" />

and than with jquery you can use 'val()' method like below:

 $('#testId').val("work");

Converting an integer to a string in PHP

There's many ways to do this.

Two examples:

 $str = (string) $int;
 $str = "$int";     

See the PHP Manual on Types Juggling for more.

How to Bootstrap navbar static to fixed on scroll?

_x000D_
_x000D_
/**_x000D_
 * Scroll management_x000D_
 */_x000D_
$(document).ready(function () {_x000D_
_x000D_
    // Define the menu we are working with_x000D_
    var menu = $('.navbar.navbar-default.navbar-inverse');_x000D_
_x000D_
    // Get the menus current offset_x000D_
    var origOffsetY = menu.offset().top;_x000D_
_x000D_
    /**_x000D_
     * scroll_x000D_
     * Perform our menu mod_x000D_
     */_x000D_
    function scroll() {_x000D_
_x000D_
        // Check the menus offset. _x000D_
        if ($(window).scrollTop() >= origOffsetY) {_x000D_
_x000D_
            //If it is indeed beyond the offset, affix it to the top._x000D_
            $(menu).addClass('navbar-fixed-top');_x000D_
_x000D_
        } else {_x000D_
_x000D_
            // Otherwise, un affix it._x000D_
            $(menu).removeClass('navbar-fixed-top');_x000D_
_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // Anytime the document is scrolled act on it_x000D_
    document.onscroll = scroll;_x000D_
_x000D_
});
_x000D_
.navbar-wrapper{_x000D_
    background:url('http://www.wallpaperup.com/uploads/wallpapers/2012/10/21/20181/cad2441dd3252cf53f12154412286ba0.jpg');_x000D_
    height: 100vh;_x000D_
  padding-top: 50px;_x000D_
}_x000D_
_x000D_
h1{_x000D_
  font-size: 50px;_x000D_
  font-weight: 700;_x000D_
}_x000D_
_x000D_
#login-dp{_x000D_
    min-width: 250px;_x000D_
    padding: 14px 14px 0;_x000D_
    overflow:hidden;_x000D_
    background-color:rgba(255,255,255,.8);_x000D_
}_x000D_
#login-dp .help-block{_x000D_
    font-size:12px    _x000D_
}_x000D_
#login-dp .bottom{_x000D_
    background-color:rgba(255,255,255,.8);_x000D_
    border-top:1px solid #ddd;_x000D_
    clear:both;_x000D_
    padding:14px;_x000D_
}_x000D_
#login-dp .social-buttons{_x000D_
    margin:12px 0    _x000D_
}_x000D_
#login-dp .social-buttons a{_x000D_
    width: 49%;_x000D_
}_x000D_
#login-dp .form-group {_x000D_
    margin-bottom: 10px;_x000D_
}_x000D_
.btn-fb{_x000D_
    color: #fff;_x000D_
    background-color:#3b5998;_x000D_
}_x000D_
.btn-fb:hover{_x000D_
    color: #fff;_x000D_
    background-color:#496ebc _x000D_
}_x000D_
.btn-tw{_x000D_
    color: #fff;_x000D_
    background-color:#55acee;_x000D_
}_x000D_
.btn-tw:hover{_x000D_
    color: #fff;_x000D_
    background-color:#59b5fa;_x000D_
}_x000D_
@media(max-width:768px){_x000D_
    #login-dp{_x000D_
        background-color: inherit;_x000D_
        color: #fff;_x000D_
    }_x000D_
    #login-dp .bottom{_x000D_
        background-color: inherit;_x000D_
        border-top:0 none;_x000D_
    }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<body>_x000D_
<div class="navbar-wrapper">  _x000D_
  <div class="container">_x000D_
    <nav class="navbar navbar-default navbar-inverse" role="navigation">_x000D_
  _x000D_
    <!-- Brand and toggle get grouped for better mobile display -->_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
        <span class="sr-only">Toggle navigation</span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
      </button>_x000D_
      <a class="navbar-brand" href="#">Login dropdown</a>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
        <ul class="nav navbar-nav">_x000D_
          <li class="active"><a href="#">Link</a></li>_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li class="dropdown">_x000D_
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">One more separated link</a></li>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      _x000D_
      </div><!-- /.navbar-collapse -->_x000D_
    </nav>_x000D_
  </div><!-- container -->_x000D_
</div><!-- /.navbar-wrapper -->_x000D_
  _x000D_
 <section>_x000D_
   <div class="container">_x000D_
     <div class="row">_x000D_
       <h1>Content</h1>_x000D_
       <p>_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue luctus placerat. Sed nisl sem, pellentesque at risus eget, consequat bibendum velit. Sed interdum accumsan luctus. Duis rhoncus suscipit hendrerit. Vestibulum ut lobortis diam. Donec magna est, euismod non ligula in, congue aliquet diam. Sed pellentesque erat nibh, et blandit quam auctor eget. Integer fringilla turpis ac sagittis mattis. In in metus posuere, tincidunt orci non, lobortis ipsum. Praesent porttitor orci a ligula facilisis porta. Nullam tincidunt feugiat dignissim._x000D_
       </p>_x000D_
       <p>_x000D_
         Pellentesque cursus suscipit massa ut molestie. Duis malesuada consequat venenatis. Vestibulum accumsan lorem sit amet vehicula tristique. Donec nec mauris quis mi imperdiet vestibulum. Praesent tempor velit at posuere posuere. Mauris tellus diam, dictum sed molestie eu, lobortis nec diam. Mauris molestie nulla vulputate, lobortis urna eget, gravida erat. Phasellus in ullamcorper lacus, eget ullamcorper odio._x000D_
       </p>_x000D_
       <p>_x000D_
         Quisque gravida nulla eros. Duis sit amet rhoncus felis. Etiam in malesuada nisl. Proin sit amet elit sit amet erat dapibus pretium. Duis a dignissim lacus, vitae mollis nunc. Donec ut tempor magna. Maecenas eget felis eget ipsum porttitor dapibus vitae vitae magna. Cras et felis eros. Nam dolor odio, bibendum ut ex eu, facilisis suscipit ipsum. Aliquam sit amet nunc volutpat, aliquet nunc ut, tempor augue. Pellentesque semper vestibulum lacinia. Nam lacinia erat interdum purus consequat elementum. Phasellus volutpat sed libero id molestie. Quisque nec iaculis nisl, vitae accumsan justo. Suspendisse sollicitudin metus in libero cursus tempor in eget enim._x000D_
       </p>_x000D_
       <p>_x000D_
         Suspendisse nibh lacus, consequat et tincidunt eget, interdum mollis velit. Etiam lobortis ac tellus et pretium. Nunc a tincidunt nulla. Cras vel nulla in neque accumsan fermentum. Etiam ac erat leo. Vestibulum aliquam dignissim lectus, tincidunt consequat augue malesuada at. Pellentesque semper viverra elit quis vestibulum. Aliquam rutrum justo dignissim ligula fringilla, ac viverra metus efficitur._x000D_
       </p>_x000D_
       <p>_x000D_
         Mauris quis nisi convallis, rhoncus odio non, sodales urna. Donec ac ante at nisi pulvinar eleifend. Duis vel suscipit est. Nullam quis aliquet eros. Maecenas tincidunt augue condimentum nisi pharetra, in molestie libero condimentum. In hac habitasse platea dictumst. Morbi quis elit id nunc faucibus egestas. Sed non vehicula ligula, quis viverra urna. Nunc nec eleifend elit. Sed aliquam nibh non turpis congue, a condimentum mauris dictum. Vivamus laoreet nulla vel elit consequat, non convallis nibh dapibus. Mauris maximus nibh maximus, sollicitudin odio nec, semper nunc. Nunc consequat convallis lobortis. Aliquam pulvinar porttitor lorem. Donec luctus, libero a interdum posuere, est tellus tincidunt risus, a fermentum lacus odio at metus. Donec maximus ante massa, imperdiet consequat magna lobortis sed._x000D_
       </p>_x000D_
     </div>_x000D_
   </div>_x000D_
 </section>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Change Manually :

string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);

From 11/22/2015 it will be converted in 22/11/2015

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)

Output PowerShell variables to a text file

I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:

# Construct an out-array to use for data export
$OutArray = @()

# The computer loop you already have
foreach ($server in $serverlist)
    {
        # Construct an object
        $myobj = "" | Select "computer", "Speed", "Regcheck"

        # Fill the object
        $myobj.computer = $computer
        $myobj.speed = $speed
        $myobj.regcheck = $regcheck

        # Add the object to the out-array
        $outarray += $myobj

        # Wipe the object just to be sure
        $myobj = $null
    }

# After the loop, export the array to CSV
$outarray | export-csv "somefile.csv"

Configuring IntelliJ IDEA for unit testing with JUnit

One way of doing this is to do add junit.jar to your $CLASSPATH as an external dependency.

adding junit intellij

So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.

In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Sometimes type setting:

max_allowed_packet = 16M

in my.ini is not working.

Try to determine the my.ini as follows:

set-variable = max_allowed_packet = 32M

or

set-variable = max_allowed_packet = 1000000000

Then restart the server:

/etc/init.d/mysql restart

Better way to sum a property value in an array

I know that this question has an accepted answer but I thought I'd chip in with an alternative which uses array.reduce, seeing that summing an array is the canonical example for reduce:

$scope.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + b[prop];
    }, 0);
};

$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');

Fiddle

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I experienced this error and did all the suggestions from you guys here but none had any effect for my error.

I caught the culprit: if you are using *.ini file for your system, you might want to check what server name was input there and make sure it is the same as the one in your web.config connection string.

How to print out a variable in makefile

If you simply want some output, you want to use $(info) by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:

$(info VAR="$(VAR)")

Will output VAR="<value of VAR>" whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info) expansion happens AFTER everything that could modify $(VAR) has already happened!

A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor) function will tell you what kind of a variable something is. So in this rule:

print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
  • $* expands to the stem that the % pattern matched in the rule.
  • $($*) expands to the value of the variable whose name is given by by $*.
  • The [ and ] clearly delineate the variable expansion. You could also use " and " or similar.
  • $(flavor $*) tells you what kind of variable it is. NOTE: $(flavor) takes a variable name, and not its expansion. So if you say make print-LDFLAGS, you get $(flavor LDFLAGS), which is what you want.
  • $(info text) provides output. Make prints text on its stdout as a side-effect of the expansion. The expansion of $(info) though is empty. You can think of it like @echo, but importantly it doesn't use the shell, so you don't have to worry about shell quoting rules.
  • @true is there just to provide a command for the rule. Without that, make will also output print-blah is up to date. I feel @true makes it more clear that it's meant to be a no-op.

Running it, you get

$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Uncaught syntaxerror: unexpected identifier?

There are errors here :

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

The code must change to:

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

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

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Wait some seconds without blocking UI execution

This is a good case for using another thread:

// Call some method
this.Method();

Task.Factory.StartNew(() =>
{
    Thread.Sleep(20000);

    // Do things here.
    // NOTE: You may need to invoke this to your main thread depending on what you're doing
});

The above code expects .NET 4.0 or above, otherwise try:

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
    Thread.Sleep(20000);

    // Do things here
}));

How do I access refs of a child component in the parent component

I think this guide explains it pretty well https://github.com/yannickcr/eslint-plugin-react/issues/678

class Field extends Component {
  const { inputRef } = this.props;
  render() {
    return (
      <input type="text" ref={inputRef} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

How do you join tables from two different SQL Server instances in one SQL query

You can create a linked server and reference the table in the other instance using its fully qualified Server.Catalog.Schema.Table name.

Radio button validation in javascript

<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">

    <div class="text-input">
        <label>Gender: </label>
        <input class="form-control" type="radio" name="gender" id="male" value="male" />
        <label for="male">Male</label>
        <input class="form-control" type="radio" name="gender" id="female" value="female" />
        <label for="female">Female</label>
    </div>
    <div class="text-input" align="center">
        <input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
    </div>

</form>

<script type="text/javascript">
    function radioValidation(){

        var gender = document.getElementsByName('gender');
        var genValue = false;

        for(var i=0; i<gender.length;i++){
            if(gender[i].checked == true){
                genValue = true;    
            }
        }
        if(!genValue){
            alert("Please Choose the gender");
            return false;
        }

    }
</script>

Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html

remove script tag from HTML content

I would use BeautifulSoup if it's available. Makes this sort of thing very easy.

Don't try to do it with regexps. That way lies madness.

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

Operator overloading ==, !=, Equals

public class BOX
{
    double height, length, breadth;

    public static bool operator == (BOX b1, BOX b2)
    {
        if (b1 is null)
            return b2 is null;

        return b1.Equals(b2);
    }

    public static bool operator != (BOX b1, BOX b2)
    {
        return !(b1 == b2);
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        return obj is BOX b2? (length == b2.length && 
                               breadth == b2.breadth && 
                               height == b2.height): false;

    }

    public override int GetHashCode()
    {
        return (height,length,breadth).GetHashCode();
    }
}

Get a CSS value with JavaScript

In 2020

check before use

You can use computedStyleMap()

The answer is valid but sometimes you need to check what unit it returns, you can get that without any slice() or substring() string.

var element = document.querySelector('.js-header-rep');
element.computedStyleMap().get('padding-left');

_x000D_
_x000D_
var element = document.querySelector('.jsCSS');_x000D_
var con = element.computedStyleMap().get('padding-left');_x000D_
console.log(con);
_x000D_
.jsCSS {_x000D_
  width: 10rem;_x000D_
  height: 10rem;_x000D_
  background-color: skyblue;_x000D_
  padding-left: 10px;_x000D_
}
_x000D_
<div class="jsCSS"></div>
_x000D_
_x000D_
_x000D_

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

Converting List<String> to String[] in Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

Combine [NgStyle] With Condition (if..else)

To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :

<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

eg1:
director:Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class 
operate:checkout ???
eg2:
1.impl class add @service
like this:
@Service
public class CityServiceImpl implements CityService{
@Autowired
private CityDao cityDao;

like this
2.dao file class add @Repository
@Repository
public interface CityDao {

Spring get current ApplicationContext

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org

Codeigniter how to create PDF

I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:

 /**
 * This function is used to display data in PDF file.
 * function is using mpdf api to generate pdf.
 * @param number $id : This is unique id of table.
 */
function generatePDF($id){
    require APPPATH . '/third_party/mpdf/vendor/autoload.php';
    //$mpdf=new mPDF();
    $mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

    $checkRecords =  $this->user_model->getCheckInfo($id);      
    foreach ($checkRecords as $key => $value) {
        $data['info'] = $value;
        $filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
        $mpdf->WriteHTML($filename); 
    }

    $mpdf->Output(); //output pdf document.
    //$content = $mpdf->Output('', 'S'); //get pdf document content's as variable. 

}

div inside table

While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.

There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.

Then again, if you're not fussy about how things look, disregard this advice.

How to best display in Terminal a MySQL SELECT returning too many fields?

If you are using MySQL interactively, you can set your pager to use sed like this:

$ mysql -u <user> p<password>
mysql> pager sed 's/,/\n/g' 
PAGER set to 'sed 's/,/\n/g''
mysql> SELECT blah FROM blah WHERE blah = blah 
.
.
.
"blah":"blah"
"blah":"blah"
"blah":"blah"

If you don't use sed as the pager, the output is like this:

"blah":"blah","blah":"blah","blah":"blah"

C++ getters/setters coding style

Avoid public variables, except for classes that are essentially C-style structs. It's just not a good practice to get into.

Once you've defined the class interface, you might never be able to change it (other than adding to it), because people will build on it and rely on it. Making a variable public means that you need to have that variable, and you need to make sure it has what the user needs.

Now, if you use a getter, you're promising to supply some information, which is currently kept in that variable. If the situation changes, and you'd rather not maintain that variable all the time, you can change the access. If the requirements change (and I've seen some pretty odd requirements changes), and you mostly need the name that's in this variable but sometimes the one in that variable, you can just change the getter. If you made the variable public, you'd be stuck with it.

This won't always happen, but I find it a lot easier just to write a quick getter than to analyze the situation to see if I'd regret making the variable public (and risk being wrong later).

Making member variables private is a good habit to get into. Any shop that has code standards is probably going to forbid making the occasional member variable public, and any shop with code reviews is likely to criticize you for it.

Whenever it really doesn't matter for ease of writing, get into the safer habit.

Android button font size

I tried to put the font size in the styles.xml but when i went to use it it was only allowing resources from the dimen folder so put it in there instead, dont know it this is right

        <Button
                android:layout_weight="1"
                android:id="@+id/three_btn"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:onClick="onButtonClick"
                android:textColor="#EEEEEE"
                android:textStyle="bold"
                android:textSize="@dimen/buttonFontSize"
                android:text="3"/>

Types in MySQL: BigInt(20) vs Int(20)

The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20) does not mean you can store values up to 10^20 in it:

[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...

The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.

For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

JavaScript: Create and save file

StreamSaver is an alternative to save very large files without having to keep all data in the memory.
In fact it emulates everything the server dose when saving a file but all client side with service worker.

You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream

There is a few example showcasing:

  • How to save multiple files as a zip
  • piping a readableStream from eg Response or blob.stream() to StreamSaver
  • manually writing to the writable stream as you type something
  • or recoding a video/audio

Here is an example in it's simplest form:

const fileStream = streamSaver.createWriteStream('filename.txt')

new Response('StreamSaver is awesome').body
  .pipeTo(fileStream)
  .then(success, error)

If you want to save a blob you would just convert that to a readableStream

new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference

Get ID from URL with jQuery

var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);

How to make a SIMPLE C++ Makefile

Why does everyone like to list out source files? A simple find command can take care of that easily.

Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...

appname := myapp

CXX := clang++
CXXFLAGS := -std=c++11

srcfiles := $(shell find . -name "*.C")
objects  := $(patsubst %.C, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Disable a Maven plugin defined in a parent POM

I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.

I had the following in my pom.xml.

<build>
    ...
    <plugins>
         <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <execution>
                        <id>generate-citrus-war</id>
                        <goals>
                            <goal>test-war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
</build>

What I wanted, was to disable the execution of generate-citrus-war for a specific profile and this was the solution:

<profile>
    <id>it</id>
    <build>
        <plugins>
            <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <!-- disable generating the war for this profile -->
                    <execution>
                        <id>generate-citrus-war</id>
                        <phase/>
                    </execution>

                    <!-- do something else -->
                    <execution>
                        ...
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

How to find if a given key exists in a C++ std::map

Use map::find

if ( m.find("f") == m.end() ) {
  // not found
} else {
  // found
}

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

MessageBox with YesNoCancel - No & Cancel triggers same event

The way I use a yes/no prompt is:

If MsgBox("Are you sure?", MsgBoxStyle.YesNo) <> MsgBoxResults.Yes Then
    Exit Sub
End If

Foreach loop, determine which is the last iteration of the loop

The iterator implementation does not provide that. Your collection might be an IList that is accessible via an index in O(1). In that case you can use a normal for-loop:

for(int i = 0; i < Model.Results.Count; i++)
{
  if(i == Model.Results.Count - 1) doMagic();
}

If you know the count, but cannot access via indices (thus, result is an ICollection), you can count yourself by incrementing an i in the foreach's body and comparing it to the length.

All this isn't perfectly elegant. Chris's solution may be the nicest I've seen so far.

Brew doctor says: "Warning: /usr/local/include isn't writable."

You can alias the command to fix this problem in your .bash_profile and run it every time you encounter it:

At the end of the file ~/.bash_profile, add:

alias fix_brew='sudo chown -R $USER /usr/local/'

And now inside your terminal you can run:

$ fix_brew

UITableViewCell, show delete button on swipe

I had a problem which I have just managed to solve so I am sharing it as it may help someone.

I have a UITableView and added the methods shown to enable swipe to delete:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.

It turns out that adding the following line to viewDidLoad was the issue:

self.tableView.allowsMultipleSelectionDuringEditing = YES;

With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.

The fix:

Add the following method to your viewController:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    self.tableView.allowsMultipleSelectionDuringEditing = editing; 
    [super setEditing:editing animated:animated];
}

Then in your method that puts the table into editing mode (from a button press for example) you should use:

[self setEditing:YES animated:YES];

instead of:

[self.tableView setEditing:YES animated:YES];

This means that multiselect is only enabled when the table is in editing mode.

CSS transition fade in

OK, first of all I'm not sure how it works when you create a div using (document.createElement('div')), so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?

If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?

Here's the code for my example:

HTML

<a href="#new">Click</a> 
<div id="new">
    Fade in ... 
</div>

CSS

#new {
    width: 100px;
    height: 100px;
    border: 1px solid #000000;
    opacity: 0;    
}


#new:target {
    -webkit-transition: opacity 2.0s ease-in;
       -moz-transition: opacity 2.0s ease-in;
         -o-transition: opacity 2.0s ease-in;
                                  opacity: 1;
}

... and here's a jsFiddle

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

node.js - how to write an array to file

To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1','2','3','4','5','6','7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

C++ How do I convert a std::chrono::time_point to long and back

time_point objects only support arithmetic with other time_point or duration objects.

You'll need to convert your long to a duration of specified units, then your code should work correctly.

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

Using querySelectorAll to retrieve direct children

Here's a flexible method, written in vanilla JS, that allows you to run a CSS selector query over only the direct children of an element:

var count = 0;
function queryChildren(element, selector) {
  var id = element.id,
      guid = element.id = id || 'query_children_' + count++,
      attr = '#' + guid + ' > ',
      selector = attr + (selector + '').replace(',', ',' + attr, 'g');
  var result = element.parentNode.querySelectorAll(selector);
  if (!id) element.removeAttribute('id');
  return result;
}

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

sqlite3.OperationalError: unable to open database file

had the same problem but top answer is too long for me so I suggest to open another shell window type cd #enter and try again

JUnit Testing Exceptions

are you sure you told it to expect the exception?

for newer junit (>= 4.7), you can use something like (from here)

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}

and for older junit, this:

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
  int i = 1/0;
}

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

How to get height and width of device display in angular2 using typescript?

export class Dashboard {
    innerHeight: any;
    innerWidth: any;
    constructor() {
        this.innerHeight = (window.screen.height) + "px";
        this.innerWidth = (window.screen.width) + "px";
    }
}

How to clear a chart from a canvas so that hover events cannot be triggered?

Using CanvasJS, this works for me clearing chart and everything else, might work for you as well, granting you set your canvas/chart up fully before each processing elsewhere:

var myDiv= document.getElementById("my_chart_container{0}";
myDiv.innerHTML = "";

Best GUI designer for eclipse?

well check out the eclipse distro easyeclipse at EasyEclipse. it has Visual editor project already added as a plugin, so no hassles of eclipse version compatibility.Plus the eclipse help section has a tutorial on VE.

How to import Swagger APIs into Postman?

I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.

Sample document

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

This can be imported into Postman as follow.

  1. Click on the 'Import' button in the top left corner of Postman UI.
  2. You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
  3. Paste the JSON format in the text area and click import.
  4. You will see all your APIs as 'Postman Collection' and can use it from the Postman.

Importing the JSON into Postman

Imported APIs

You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.

This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

How to search a Git repository by commit message?

To search across all the branches

git log --all --grep='Build 0051'

Once you know which commit you want to get to

git checkout <the commit hash>

Equivalent of typedef in C#

C# supports some inherited covariance for event delegates, so a method like this:

void LowestCommonHander( object sender, EventArgs e ) { ... } 

Can be used to subscribe to your event, no explicit cast required

gcInt.MyEvent += LowestCommonHander;

You can even use lambda syntax and the intellisense will all be done for you:

gcInt.MyEvent += (sender, e) =>
{
    e. //you'll get correct intellisense here
};

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Precision String Format Specifier In Swift

here a "pure" swift solution

 var d = 1.234567
operator infix ~> {}
@infix func ~> (left: Double, right: Int) -> String {
    if right == 0 {
        return "\(Int(left))"
    }
    var k = 1.0
    for i in 1..right+1 {
        k = 10.0 * k
    }
    let n = Double(Int(left*k)) / Double(k)
    return "\(n)"
}
println("\(d~>2)")
println("\(d~>1)")
println("\(d~>0)")

How to get the html of a div on another page with jQuery ajax?

You can use JQuery .load() method:

http://api.jquery.com/load/

 $( "#content" ).load( "ajax/test.html div#content" );

How to maintain page scroll position after a jquery event is carried out?

For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:

<a  
href='javascript:void(0)'  
onclick='javascript:whatever causing the page to scroll to the top'  
></a>

Changing the image source using jQuery

Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

_x000D_
_x000D_
let pic=[
  "https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif",
  "https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif"
];

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>
_x000D_
_x000D_
_x000D_

What are the differences between a multidimensional array and an array of arrays in C#?

Simply put multidimensional arrays are similar to a table in DBMS.
Array of Array (jagged array) lets you have each element hold another array of the same type of variable length.

So, if you are sure that the structure of data looks like a table (fixed rows/columns), you can use a multi-dimensional array. Jagged array are fixed elements & each element can hold an array of variable length

E.g. Psuedocode:

int[,] data = new int[2,2];
data[0,0] = 1;
data[0,1] = 2;
data[1,0] = 3;
data[1,1] = 4;

Think of the above as a 2x2 table:

1 | 2
3 | 4
int[][] jagged = new int[3][]; 
jagged[0] = new int[4] {  1,  2,  3,  4 }; 
jagged[1] = new int[2] { 11, 12 }; 
jagged[2] = new int[3] { 21, 22, 23 }; 

Think of the above as each row having variable number of columns:

 1 |  2 |  3 | 4
11 | 12
21 | 22 | 23

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Conditional formatting using AND() function

I had a similar problem with a less complicated formula:

= If (x > A & x <= B) 

and found that I could Remove the AND and join the two comparisons with +

  = (x > A1) + (x <= B1)        [without all the spaces]

Hope this helps others with less complex comparisons.

How to use CSS to surround a number with a circle?

You work like with a standard block, that is a square

.circle {
    width: 10em; height: 10em; 
    -webkit-border-radius: 5em; -moz-border-radius: 5em;
  }

This is feature of CSS 3 and it is not very well suporrted, you can count on firefox and safari for sure.

<div class="circle"><span>1234</span></div>

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

There is a big difference between an empty collection and a null reference to a collection.

When you use foreach, internally, this is calling the IEnumerable's GetEnumerator() method. When the reference is null, this will raise this exception.

However, it is perfectly valid to have an empty IEnumerable or IEnumerable<T>. In this case, foreach will not "iterate" over anything (since the collection is empty), but it will also not throw, since this is a perfectly valid scenario.


Edit:

Personally, if you need to work around this, I'd recommend an extension method:

public static IEnumerable<T> AsNotNull<T>(this IEnumerable<T> original)
{
     return original ?? Enumerable.Empty<T>();
}

You can then just call:

foreach (int i in returnArray.AsNotNull())
{
    // do some more stuff
}

Read values into a shell variable from a pipe

read won't read from a pipe (or possibly the result is lost because the pipe creates a subshell). You can, however, use a here string in Bash:

$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3

But see @chepner's answer for information about lastpipe.

How do I create a MongoDB dump of my database?

You need to open command prompt as an administrator in a folder where your Mongo is installed (in my case: C:\Program Files\MongoDB\Server\3.4\bin). If you want to dump your whole database, you can just use:

mongodump --db database_name

You also have posibilities to dump only certain collection(s), or to dump all but certain collection(s).

If you want to dump only one collection (for example users):

mongodump  --db database_name --collection users

If you want to dump all but users collection:

mongodump  --db database_name --excludeCollection=users

It is also possible to output the dump to an archive file:

mongodump --archive=test.archive --db database_name

Valid characters in a Java class name

Class names should be nouns in UpperCamelCase, with the first letter of every word capitalised. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). The naming conventions can be read over here:

http://www.oracle.com/technetwork/java/codeconventions-135099.html

Run/install/debug Android applications over Wi-Fi?

If you want to enable wireless adb on the device without connecting with a USB cable at all (root required):

  1. Install a terminal app on the device (like Android Terminal Emulator) Type the following
  2. su
  3. setprop service.adb.tcp.port 5555
  4. stop adbd
  5. start adbd

Since you already have the terminal opened, you can find the IP address of the device:

ip addr show

Then in your debugging environment run command:

adb connect ip.of.the.device

This will make the device to be listed as any other emulators you might have. Note that the TCP will stay opened until you reset the device. You might also want to install a Wi-Fi Keep Alive app if you often experience disconnects.

Remember to close the TCP when connecting to public networks if you want to feel safe. You can do the following or simply restart the device:

  1. su
  2. setprop service.adb.tcp.port -1
  3. stop adbd
  4. start adbd

Creating an abstract class in Objective-C

If you are used to the compiler catching abstract instantiation violations in other languages, then the Objective-C behavior is disappointing.

As a late binding language it is clear that Objective-C cannot make static decisions on whether a class truly is abstract or not (you might be adding functions at runtime...), but for typical use cases this seems like a shortcoming. I would prefer the compiler flat-out prevented instantiations of abstract classes instead of throwing an error at runtime.

Here is a pattern we are using to get this type of static checking using a couple of techniques to hide initializers:

//
//  Base.h
#define UNAVAILABLE __attribute__((unavailable("Default initializer not available.")));

@protocol MyProtocol <NSObject>
-(void) dependentFunction;
@end

@interface Base : NSObject {
    @protected
    __weak id<MyProtocol> _protocolHelper; // Weak to prevent retain cycles!
}

- (instancetype) init UNAVAILABLE; // Prevent the user from calling this
- (void) doStuffUsingDependentFunction;
@end

//
//  Base.m
#import "Base.h"

// We know that Base has a hidden initializer method.
// Declare it here for readability.
@interface Base (Private)
- (instancetype)initFromDerived;
@end

@implementation Base
- (instancetype)initFromDerived {
    // It is unlikely that this becomes incorrect, but assert
    // just in case.
    NSAssert(![self isMemberOfClass:[Base class]],
             @"To be called only from derived classes!");
    self = [super init];
    return self;
}

- (void) doStuffUsingDependentFunction {
    [_protocolHelper dependentFunction]; // Use it
}
@end

//
//  Derived.h
#import "Base.h"

@interface Derived : Base
-(instancetype) initDerived; // We cannot use init here :(
@end

//
//  Derived.m
#import "Derived.h"

// We know that Base has a hidden initializer method.
// Declare it here.
@interface Base (Private)
- (instancetype) initFromDerived;
@end

// Privately inherit protocol
@interface Derived () <MyProtocol>
@end

@implementation Derived
-(instancetype) initDerived {
    self= [super initFromDerived];
    if (self) {
        self->_protocolHelper= self;
    }
    return self;
}

// Implement the missing function
-(void)dependentFunction {
}
@end

Trying to handle "back" navigation button action in iOS

Try this code using VIewWillDisappear method to detect the press of The back button of NavigationItem:

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    {
        // Navigation button was pressed. Do some stuff 
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

OR There is another way to get Action of the Navigation BAck button.

Create Custom button for UINavigationItem of back button .

For Ex:

In ViewDidLoad :

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
}

-(void)home:(UIBarButtonItem *)sender 
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Swift :

override func willMoveToParentViewController(parent: UIViewController?) 
{
    if parent == nil 
    {
        // Back btn Event handler
    }
}

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;

If you want to enable this for newly created relations too, then set the default permissions:

ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;

However, seeing that you use 8.1 you have to code it yourself:

CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS $$
DECLARE
  rel RECORD;
BEGIN
  FOR rel IN
    SELECT c.relname
    FROM pg_class c
    JOIN pg_namespace s ON c.namespace = s.oid
    WHERE s.nspname = schname
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
  END LOOP;
  RETURN 1;
END; $$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on pg_class.relkind. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

Effective method to hide email from spam bots

Here is my working version:


Create somewhere a container with a fallback text:

<div id="knock_knock">Activate JavaScript, please.</div>

And add at the bottom of the DOM (w.r.t. the rendering) the following snippet:

<script>
  (function(d,id,lhs,rhs){
    d.getElementById(id).innerHTML = "<a rel=\"nofollow\" href=\"mailto"+":"+lhs+"@"+rhs+"\">"+"Mail"+"<\/a>";
  })(window.document, "knock_knock", "your.name", "example.com");
</script>

It adds the generated hyperlink to the specified container:

<div id="knock_knock"><a rel="nofollow" href="[email protected]">Mail</a></div>

In addition here is a minified version:

<script>(function(d,i,l,r){d.getElementById(i).innerHTML="<a rel=\"nofollow\" href=\"mailto"+":"+l+"@"+r+"\">"+"Mail"+"<\/a>";})(window.document,"knock_knock","your.name","example.com");</script>

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

Try this one:

h1 {
    text-align: center;
    background-color: green;
    visibility: hidden;
}

h1:after {
    content:'The Last Will and Testament of Eric Jones';
    visibility: visible;
    display: block;
    position: absolute;
    background-color: inherit;
    padding: 5px;
    top: 10px;
    left: calc(30% - 5px);
}

Please note that calc is not compatible to all browsers :) Just want to be consistent with the alignment in the original post.

https://jsfiddle.net/richardferaro/ssyc04o4/

How do I use the CONCAT function in SQL Server 2008 R2?

Yes the function is not in sql 2008. You can use the cast operation to do that.

For example we have employee table and you want name with applydate.

so you can use

Select   cast(name as varchar) + cast(applydate as varchar) from employee

It will work where concat function is not working.

How to implement the Android ActionBar back button?

AndroidManifest file:

    <activity android:name=".activity.DetailsActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="br.com.halyson.materialdesign.activity.HomeActivity" />
    </activity>

add in DetailsActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);   
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

it's work :]

Convert negative data into positive data in SQL Server

An easy and straightforward solution using the CASE function:

SELECT CASE WHEN ( a > 0 ) THEN (a*-1) ELSE (a*-1) END AS NegativeA,
       CASE WHEN ( b > 0 ) THEN (b*-1) ELSE (b*-1) END AS PositiveB
FROM YourTableName

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.

MongoDB: How to query for records where field is null or not set?

Use:

db.emails.count({sent_at: null})

Which counts all emails whose sent_at property is null or is not set. The above query is same as below.

db.emails.count($or: [
  {sent_at: {$exists: false}},
  {sent_at: null}
])

SSRS Field Expression to change the background color of the Cell

The problem with IIF(Fields!column.Value = "Approved", "Green") is that you are missing the third parameter. The correct syntax is IIF( [some boolean expression], [result if boolean expression is true], [result if boolean is false])

Try this

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Here is a list of expression examples Expression Examples in Reporting Services

IIF in SSRS report

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

REST API Login Pattern

A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.

Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.

But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401 "unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.

TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)

An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401 if not provided.

Java, reading a file from current directory?

If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:

URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());

reader = new BufferedReader(new FileReader(f));

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();
        MessageBox.Show(sResult);
    }

And you're done. enter image description here

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Try [^- ], \s will match 5 other characters beside the space (like tab, newline, formfeed, carriage return).

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

Super-simple example of C# observer/observable with delegates

I've tied together a couple of the great examples above (thank you as always to Mr. Skeet and Mr. Karlsen) to include a couple of different Observables and utilized an interface to keep track of them in the Observer and allowed the Observer to to "observe" any number of Observables via an internal list:

namespace ObservablePattern
{
    using System;
    using System.Collections.Generic;

    internal static class Program
    {
        private static void Main()
        {
            var observable = new Observable();
            var anotherObservable = new AnotherObservable();

            using (IObserver observer = new Observer(observable))
            {
                observable.DoSomething();
                observer.Add(anotherObservable);
                anotherObservable.DoSomething();
            }

            Console.ReadLine();
        }
    }

    internal interface IObservable
    {
        event EventHandler SomethingHappened;
    }

    internal sealed class Observable : IObservable
    {
        public event EventHandler SomethingHappened;

        public void DoSomething()
        {
            var handler = this.SomethingHappened;

            Console.WriteLine("About to do something.");
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }

    internal sealed class AnotherObservable : IObservable
    {
        public event EventHandler SomethingHappened;

        public void DoSomething()
        {
            var handler = this.SomethingHappened;

            Console.WriteLine("About to do something different.");
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }

    internal interface IObserver : IDisposable
    {
        void Add(IObservable observable);

        void Remove(IObservable observable);
    }

    internal sealed class Observer : IObserver
    {
        private readonly Lazy<IList<IObservable>> observables =
            new Lazy<IList<IObservable>>(() => new List<IObservable>());

        public Observer()
        {
        }

        public Observer(IObservable observable) : this()
        {
            this.Add(observable);
        }

        public void Add(IObservable observable)
        {
            if (observable == null)
            {
                return;
            }

            lock (this.observables)
            {
                this.observables.Value.Add(observable);
                observable.SomethingHappened += HandleEvent;
            }
        }

        public void Remove(IObservable observable)
        {
            if (observable == null)
            {
                return;
            }

            lock (this.observables)
            {
                observable.SomethingHappened -= HandleEvent;
                this.observables.Value.Remove(observable);
            }
        }

        public void Dispose()
        {
            for (var i = this.observables.Value.Count - 1; i >= 0; i--)
            {
                this.Remove(this.observables.Value[i]);
            }
        }

        private static void HandleEvent(object sender, EventArgs args)
        {
            Console.WriteLine("Something happened to " + sender);
        }
    }
}

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I was using the p12 which I exported with Keychain in my MacBook, however, it didn't work on my java-apns server code. What I had to do was to create a new p12 key as stated here, using my already generated pem keys:

openssl pkcs12 -export -in your_app.pem -inkey your_key.pem -out your_app_key.p12

Then updated the path to that new p12 file and everything worked perfectly.

Reading Xml with XmlReader in C#

We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account> element, after parsing the reader will index the </Accounts> closing tag.

The parsing code looks something like this:

public class Account
{
    string _accountId;
    string _nameOfKin;
    Statements _statmentsAvailable;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read node attributes
        _accountId = reader.GetAttribute( "accountId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                switch( reader.Name )
                {
                    // Read element for a property of this class
                    case "NameOfKin":
                        _nameOfKin = reader.ReadElementContentAsString();
                        break;

                    // Starting sub-list
                case "StatementsAvailable":
                    _statementsAvailable = new Statements();
                    _statementsAvailable.Read( reader );
                    break;

                    default:
                        reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }       
    }
}

The Statements class just reads in the <StatementsAvailable> node

public class Statements
{
    List<Statement> _statements = new List<Statement>();

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();
        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                if( reader.Name == "Statement" )
                {
                    var statement = new Statement();
                    statement.ReadFromXml( reader );
                    _statements.Add( statement );               
                }
                else
                {
                    reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }
    }
}

The Statement class would look very much the same

public class Statement
{
    string _satementId;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read noe attributes
        _statementId = reader.GetAttribute( "statementId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {           
            ....same basic loop
        }       
    }
}

How to convert C++ Code to C

There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

How to use wait and notify in Java without IllegalMonitorStateException?

For this particular problem, why not store up your various results in variables and then when the last of your thread is processed you can print in whatever format you want. This is especially useful if you are gonna be using your work history in other projects.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I solved this issue following the indication provided in the article http://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/ with little changes.

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
SSLSocketFactory noSSLv3Factory = null;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
    noSSLv3Factory = new TLSSocketFactory(sslContext.getSocketFactory());
} else {
    noSSLv3Factory = sslContext.getSocketFactory();
}
connection.setSSLSocketFactory(noSSLv3Factory);

This is the code of the custom TLSSocketFactory:

public static class TLSSocketFactory extends SSLSocketFactory {

    private SSLSocketFactory internalSSLSocketFactory;

    public TLSSocketFactory(SSLSocketFactory delegate) throws KeyManagementException, NoSuchAlgorithmException {
        internalSSLSocketFactory = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return internalSSLSocketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return internalSSLSocketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
    }

    /*
     * Utility methods
     */

    private static Socket enableTLSOnSocket(Socket socket) {
        if (socket != null && (socket instanceof SSLSocket)
                && isTLSServerEnabled((SSLSocket) socket)) { // skip the fix if server doesn't provide there TLS version
            ((SSLSocket) socket).setEnabledProtocols(new String[]{TLS_v1_1, TLS_v1_2});
        }
        return socket;
    }

    private static boolean isTLSServerEnabled(SSLSocket sslSocket) {
        System.out.println("__prova__ :: " + sslSocket.getSupportedProtocols().toString());
        for (String protocol : sslSocket.getSupportedProtocols()) {
            if (protocol.equals(TLS_v1_1) || protocol.equals(TLS_v1_2)) {
                return true;
            }
        }
        return false;
    }
}

Edit: Thank's to ademar111190 for the kotlin implementation (link)

class TLSSocketFactory constructor(
        private val internalSSLSocketFactory: SSLSocketFactory
) : SSLSocketFactory() {

    private val protocols = arrayOf("TLSv1.2", "TLSv1.1")

    override fun getDefaultCipherSuites(): Array<String> = internalSSLSocketFactory.defaultCipherSuites

    override fun getSupportedCipherSuites(): Array<String> = internalSSLSocketFactory.supportedCipherSuites

    override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean) =
            enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose))

    override fun createSocket(host: String, port: Int) =
            enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))

    override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int) =
            enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort))

    override fun createSocket(host: InetAddress, port: Int) =
            enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))

    override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int) =
            enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort))

    private fun enableTLSOnSocket(socket: Socket?) = socket?.apply {
        if (this is SSLSocket && isTLSServerEnabled(this)) {
            enabledProtocols = protocols
        }
    }

    private fun isTLSServerEnabled(sslSocket: SSLSocket) = sslSocket.supportedProtocols.any { it in protocols }

}

Quickest way to convert a base 10 number to any base in .NET?

This is a fairly straightforward way to do this, but it may not be the fastest. It is quite powerful because it is composable.

public static IEnumerable<int> ToBase(this int x, int b)
{
    IEnumerable<int> ToBaseReverse()
    {
        if (x == 0)
        {
            yield return 0;
            yield break;
        }
        int z = x;
        while (z > 0)
        {
            yield return z % b;
            z = z / b;
        }
    }

    return ToBaseReverse().Reverse();
}

Combine this with this simple extension method and any getting any base is now possible:

public static string ToBase(this int number, string digits) =>
    String.Concat(number.ToBase(digits.Length).Select(x => digits[x]));

It can be used like this:

var result = 23.ToBase("01");
var result2 = 23.ToBase("012X");

Console.WriteLine(result);
Console.WriteLine(result2);

The output is:

10111
11X

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Regarding to sampopes answer from Jun 6 '14 at 11:59:

I have insert a css style with font-size of 20px to display the excel data greater. In sampopes code the leading <tr> tags are missing, so i first output the headline and than the other tables lines within a loop.

function fnExcelReport()
{
    var tab_text = '<table border="1px" style="font-size:20px" ">';
    var textRange; 
    var j = 0;
    var tab = document.getElementById('DataTableId'); // id of table
    var lines = tab.rows.length;

    // the first headline of the table
    if (lines > 0) {
        tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
    }

    // table data lines, loop starting from 1
    for (j = 1 ; j < lines; j++) {     
        tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");             //remove if u want links in your table
    tab_text = tab_text.replace(/<img[^>]*>/gi,"");                 // remove if u want images in your table
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");    // reomves input params
    // console.log(tab_text); // aktivate so see the result (press F12 in browser)

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

     // if Internet Explorer
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
    }  
    else // other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}   

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

CardView background color always white

If you want to change the card background color, use:

app:cardBackgroundColor="@somecolor"

like this:

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@color/white">

</android.support.v7.widget.CardView>

Edit: As pointed by @imposible, you need to include

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

in your root XML tag in order to make this snippet function

Angular - POST uploaded file

Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.

For very basic file upload I created such service function as a workaround (using ???????'s answer):

  uploadFile(file:File):Promise<MyEntity> {
    return new Promise((resolve, reject) => {

        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(<MyEntity>JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.getServiceUrl(), true);

        let formData = new FormData();
        formData.append("file", file, file.name);
        xhr.send(formData);
    });
}

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

NEVER DELETE apply plugin: 'com.google.gms.google-services' from the gradle. Sometimes you are using com.google.gms:google-services:3.1.0 , without apply plugin: 'com.google.gms.google-services' your gradle build successfully. BUT IT IS COMPLETELY WRONG !!!! This error comes due to google-service.json file is not at the correct location. Go to your PROJECT TAB at left side above. If you display it as ANDROID make it PROJECT then check your google-service.json file is at this location. EXPAND app then see google-service.json file below the build.gradle. IF NOT PLACE IT THERE BY RIGHT CLICK ON THE app .

Padding is invalid and cannot be removed?

Make sure that the keys you use to encrypt and decrypt are the same. The padding method even if not explicitly set should still allow for proper decryption/encryption (if not set they will be the same). However if you for some reason are using a different set of keys for decryption than used for encryption you will get this error:

Padding is invalid and cannot be removed

If you are using some algorithm to dynamically generate keys that will not work. They need to be the same for both encryption and decryption. One common way is to have the caller provide the keys in the constructor of the encryption methods class, to prevent the encryption/decryption process having any hand in creation of these items. It focuses on the task at hand (encrypting and decrypting data) and requires the iv and key to be supplied by the caller.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

find the path to imdb.py then just add the flag to np.load(path,...flag...)

    def load_data(.......):
    .......................................
    .......................................
    - with np.load(path) as f:
    + with np.load(path,allow_pickle=True) as f: